Главная » Просмотр файлов » Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU

Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 42

Файл №779891 Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (Symbian Books) 42 страницаWiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891) страница 422018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 42)

The APIs in this classcover a few key areas of interest, which I’ll discuss now.ThreadsNKern provides a static interface to nanothread manipulation, using anNThread* parameter. This allows callers to create a nanothread, to killit, to suspend it, to release it and more. Here are a couple of examples:static void ThreadKill(NThread* aThread)static void ThreadSetPriority(NThread* aThread, TInt aPriority);TimersAs we saw in Chapter 2, Hardware for Symbian OS, the kernel needshardware to provide a periodic tick interrupt; this timer must be startedfrom the ASSP’s or variant’s Init3() function. The period of this tickdetermines the timer resolution and is usually set to 1 ms – hence it isfrequently known as the millisecond timer.

The tick interrupt’s interrupthandler calls the Tick() method in the nanokernel’s timer queue class,NTimerQ.Nanokernel timers provide the most fundamental system timing functions in the operating system. Symbian OS tick-based timers and time-ofday functions are both derived from nanokernel timers. In addition, thenanokernel timer service supports timed wait services, if implemented.The tick interrupt is also used to drive the round-robin scheduling forequal-priority thread.I will discuss timers in more detail in Section 5.5.Fast semaphores and mutexesThe NKern semaphore and mutex APIs allow their callers to wait on andsignal nanokernel fast mutexes and semaphores.

Here are the two fastmutex APIs:static void FMWait(NFastMutex* aMutex);static void FMSignal(NFastMutex* aMutex);InterruptsThe NKern interrupt APIs allow their callers to enable and disableinterrupts: globally, or to a certain level. For example:static TInt DisableAllInterrupts();void EnableAllInterrupts();SERVICES PROVIDED BY THE KERNEL TO THE KERNEL189Read-modify-writeThe NKern read-modify-write APIs allow their callers to atomicallyincrement or decrement a counter, preventing side-effects from twothreads attempting to access the same counter.

For example:static TInt LockedInc(TInt& aCount);static TInt LockedDec(TInt& aCount);Key concrete classesThe independent nanokernel also provides key classes that are used bythe rest of the kernel. I have covered or will cover these in other chapters,so here it will suffice to enumerate them:• NFastSemaphore• NFastMutex• TDfc.5.4.1.2 Symbian OS kernelThe static interface to the independent Symbian OS is provided throughthe class Kern, which is defined in kernel.h.

The APIs in this classcover a wide miscellany of topics, of which I’ll pick out a few.Thread read and writeThe Kern class provides APIs to allow other parts of the kernel to safelyread and write from threads’ address spaces.static TInt ThreadDesRead(DThread* aThread, const TAny* aSrc,TDes8& aDest, TInt aOffset, TInt aMode);static TInt ThreadRawRead(DThread* aThread, const TAny* aSrc,TAny* aDest, TInt aSize);static TInt ThreadDesWrite(DThread* aThread, TAny* aDest,const TDesC8& aSrc, TInt aOffset, TInt aMode,Thread* aOrigThread);static TInt ThreadRawWrite(DThread* aThread, TAny* aDest,const TAny* aSrc, TInt aSize,DThread* aOrigThread=NULL);Access to kernel variablesIn this case, a variety of examples is worth a thousand words:staticstaticstaticstaticstaticstaticstaticTTimeK SystemTime();DPowerModel* PowerModel();DObjectCon* const *Containers();TSuperPage& SuperPage();TMachineConfig& MachineConfig();DThread& CurrentThread();DProcess& CurrentProcess();190KERNEL SERVICESKey concrete classesAt this level, the Symbian OS kernel provides the abstractions of key kernelobjects such as DThread, DProcess, and DChunk.

I discuss these indetail in Chapter 3, Threads, Processes and Libraries and Chapter 7,Memory Models.5.4.2 Platform (or image) layer5.4.2.1 Memory modelThe memory model is the only module in the platform layer, becausethis layer is essentially concerned with executable images on disk, andprocesses in memory. This means that there are only two possibilities atthe platform layer: EPOC for a real mobile phone platform or WIN32 forthe emulator.The platform layer provides static APIs to the independent layer in theclass P, which is defined in kern_priv.h. This is very short, so I’ll showyou all of it:class P{public:staticstaticstaticstaticstaticstaticstaticstatic};TIntvoidvoidvoidInitSystemTime();CreateVariant();StartExtensions();KernelInfo(TProcessCreateInfo& aInfo,TAny*& aStack, TAny*& aHeap);void NormalizeExecutableFileName(TDes& aFileName);void SetSuperPageSignature();TBool CheckSuperPageSignature();DProcess* NewProcess();You can see that the platform layer takes part, as expected, in certainkey initializations.

It starts the system clock (reading the system timeon Win32, the RTC on a mobile phone), starts the extensions (including the variant) and then creates the actual variant object by callingA::CreateVariant(). I will talk about this more in Chapter 16, BootProcesses.Key concrete classesThe most important class with a platform specific implementationis the Symbian OS process, DProcess.

The implementation is provided by the derived DEpocProcess class on the EPOC platform andDWin32Platform on the emulator.5.4.3 Model layer5.4.3.1 Memory modelThe model layer is the place in which we have isolated all the kernel’sassumptions about memory hardware and layout. The main functions thatSERVICES PROVIDED BY THE KERNEL TO THE KERNEL191this layer provides are low-level memory management – how the MMUis used and how the address space is configured.Symbian OS currently supports four memory models – one for theWIN32 platform (the emulator model) and three for the EPOC platform(moving, multiple and direct).

If you want to find out more, turn toChapter 7, Memory Models.There are two static interfaces to the memory model. The first is definedin the class Epoc, in platform.h. This is a common interface to allEPOC memory models, which is provided for use by extensions anddevice drivers. It looks like this:class Epoc{public:IMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CstaticstaticstaticstaticstaticstaticstaticstaticIMPORT_CIMPORT_CIMPORT_CIMPORT_Cstaticstaticstaticstaticvoid SetMonitorEntryPoint(TDfcFn aFunction);void SetMonitorExceptionHandler(TLinAddr aHandler);TAny* ExceptionInfo();const TRomHeader& RomHeader();TInt AllocShadowPage(TLinAddr aRomAddr);TInt FreeShadowPage(TLinAddr aRomAddr);TInt FreezeShadowPage(TLinAddr aRomAddr);TInt AllocPhysicalRam(TInt aSize, TPhysAddr& aPhysAddr,TInt aAlign=0);TInt FreePhysicalRam(TPhysAddr aPhysAddr, TInt aSize);TInt ClaimPhysicalRam(TPhysAddr aPhysAddr, TInt aSize);TPhysAddr LinearToPhysical(TLinAddr aLinAddr);void RomProcessInfo(TProcessCreateInfo& aInfo,const TRomImageHeader& aRomImageHeader);};You can see that this interface provides functions for allocating physicalRAM, for finding information in ROM, and for converting linear addressesto physical ones.The second interface to the memory model is in class M, inkern_priv.h.

This consists of functions provided by the memory modelto the independent layer. Here it is:class M{public:staticstaticstaticstaticstaticstaticstaticstaticvoid Init1();void Init2();TInt InitSvHeapChunk(DChunk* aChunk, TInt aSize);TInt InitSvStackChunk();TBool IsRomAddress(const TAny* aPtr);TInt PageSizeInBytes();void SetupCacheFlushPtr(TInt aCache, SCacheInfo& c);void FsRegisterThread();192KERNEL SERVICESstatic DCodeSeg* NewCodeSeg(TCodeSegCreateInfo& aInfo);};You can see that this class mainly provides initialization functions thatthe independent layer calls during startup.Key concrete classesAt this level you can find model specific implementations of manykey Symbian OS classes. For example, DMemModelChunk derives fromDChunk and DMemModelThread derives from DThread.

On the EPOCplatform the DMemModelProcess class derives from DEpocProcess,which in turn derives from DProcess. On the emulator the concreteclass representing a process is DWin32Process, which derives directlyfrom DProcess.5.4.4 CPU layer5.4.4.1 Nanokernel and Symbian OS kernelThe CPU layer is where we make assumptions about the particularprocessor we’re running on – is it X86 or ARM? This is the layer in whichyou might expect to see some assembler making an appearance. In fact, asizable proportion of the code in the ARM CPU layer of the Symbian OSkernel is actually independent layer functionality that has been assemblercoded for improved performance.There are two static interfaces to the CPU layer nanokernel andSymbian OS kernel. The first is provided in the class Arm, which isdefined in arm.h, and is an interface to the ARM CPU layer for the useof the variant.

(There is a similar class X86 for the X86 CPU layer.) TheArm class looks like this:class Arm{public:enum {EDebugPortJTAG=42};static void Init1Interrupts();static TInt AdjustRegistersAfterAbort(TAny* aContext);static void GetUserSpAndLr(TAny* /*aReg[2]*/);static void SetUserSpAndLr(TAny* /*aReg[2]*/);IMPORT_C static void SetIrqHandler(TLinAddr aHandler);IMPORT_C static void SetFiqHandler(TLinAddr aHandler);IMPORT_C static TInt DebugOutJTAG(TUint aChar);IMPORT_C static TInt DebugInJTAG(TUint32& aRxData);IMPORT_C static void SetCpInfo(TInt aCpNum,const SCpInfo* aInfo);IMPORT_C static void SetStaticCpContextSize(TInt aSize);IMPORT_C static void AllocExtraContext(TInt aRequiredSize);static void CpInit0();static void CpInit1();SERVICES PROVIDED BY THE KERNEL TO THE KERNEL193static Uint64 IrqStack[KIrqStackSize/8];static Uint64 FiqStack[KFiqStackSize/8];static Uint64 ExceptionStack[KExceptionStackSize/8];}You can see that a key use case is to allow the variant to install primaryinterrupt dispatchers.The second interface class, class A, provided in kern_priv.h, contains CPU layer APIs that are called by both the memory model andindependent layer – but mainly the latter.class A{public:staticstaticstaticstaticstaticstaticstaticstaticstaticstaticstaticstaticstaticstaticstatic};voidvoidvoidvoidvoidInit1();Init2();Init3();DebugPrint(const TDesC8& aDes);UserDebugPrint(const TText* aPtr, TInt aLen,TBool aNewLine);TInt CreateVariant(const TAny* aFile);TInt NullThread(TAny*);DPlatChunkHw* NewHwChunk();TPtr8 MachineConfiguration();void StartCrashDebugger(const TDesC8& aDes, TInt aFault);TInt MsTickPeriod();TInt CallSupervisorFunction(TSupervisorFunction aFunction,TAny* aParameter);TInt VariantHal(TInt aFunction, TAny* a1, TAny* a2);TInt SystemTimeInSecondsFrom2000(TInt& aTime);TInt SetSystemTimeInSecondsFrom2000(TInt aTime);Again you can see that a large part of this interface’s purpose is toassist at initialization time.5.4.4.2 Memory modelThe memory model also appears in the CPU layer.

Характеристики

Тип файла
PDF-файл
Размер
6,63 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее