Главная » Просмотр файлов » 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), страница 57

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

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

The memorymapping is adjusted to record that the old page is now saved to disk andis not present in memory. When this page is accessed once more a pagefault occurs, and a special fault handler determines that the contents ofthe page are on disk, and arranges for it to be loaded back into sparephysical memory before restarting the program that faulted.EKA2 does not support demand paging.7.2.2 CacheThe second key element of the hardware memory sub-system is thecache. This is very fast (1- or 2-cycle) memory that sits right next tothe CPU. The data in the most recently accessed memory is containedhere, substantially reducing the number of external memory accesses andtherefore improving performance and efficiency.In Chapter 2, Hardware for Symbian OS, I have discussed caches insome detail.7.3 The memory model interfaceThe memory model is a distinct architectural block in the EKA2 kernel.As a result the rest of the kernel can be almost entirely independent ofthe chosen memory architecture and hardware support.

To provide thatencapsulation, the memory model defines a standard API to which allmemory model implementations must conform.The basic API is in the two classes P and M defined in kern_priv.h.P denotes the API exposed by the platform layer in the EKA2 softwareTHE MEMORY MODEL INTERFACE263layer diagram, and M denotes the API exposed by the model layer in thesame diagram:class P{public:static TIntstatic voidstatic voidstatic voidstaticstaticstaticstatic};class M{public:staticstaticstaticstaticstaticstaticstaticstaticstatic};InitSystemTime();CreateVariant();StartExtensions();KernelInfo(TProcessCreateInfo& aInfo, TAny*& aStack,TAny*& aHeap);void NormalizeExecutableFileName(TDes& aFileName);void SetSuperPageSignature();TBool CheckSuperPageSignature();DProcess* NewProcess();void 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();DCodeSeg* NewCodeSeg(TCodeSegCreateInfo& aInfo);This appears to be a very small API indeed, but it does hide a fewsecrets.All but four of the functions are related to startup.

The result ofinvoking the startup functions is both to initialize the memory modelwithin the kernel, but also to configure the kernel for the memory model.In particular:M::Init1()During this initialization phase the processcontext switch callback is registered with thescheduler. This callback will be used for alladdress space changes triggered by a contextswitch.M::SetupCacheFlushPtr()Provides the memory address to be usedby the cache manager when flushing thecaches.The two most interesting functions here are P::NewProcess() andM::NewCodeSeg().

These are not expected to return exact DProcess264MEMORY MODELSand DCodeSeg objects, but rather classes derived from them. We had abrief look at DProcess in Chapter 3, Threads, Processes and Libraries,but what you should note is that it has a number of virtual members – andamong them are further factory functions DProcess::NewChunk() andDProcess::NewThread() designed to return memory model-specificclasses derived from DChunk and DThread.It is these four classes – DProcess, DThread, DChunk and DCodeSeg – that provide the main API between the generic layers of the kerneland the memory model.7.3.1 DChunkIn Symbian OS, the chunk is the fundamental means by which theoperating system allocates memory and makes it available to codeoutside of the memory model.A chunk is a contiguous range of addressable (reserved) memory ofwhich a sub-set will contain accessible (committed) memory.

On systemswithout an MMU, the addresses are physical addresses, and the entirechunk is accessible.On systems with an MMU, Symbian OS provides three fundamentaltypes of chunk, depending on which sub-sets of the address range containcommitted memory.1.NORMAL. These chunks have a committed region consisting of asingle contiguous range beginning at the chunk base address with asize that is a multiple of the MMU page size2.DOUBLE ENDED. These chunks have a committed region consistingof a single contiguous range with arbitrary lower and upper endpointswithin the reserved region, subject to the condition that both the lowerand upper endpoints must be a multiple of the MMU page size3.DISCONNECTED. These have a committed region consisting of anarbitrary set of MMU pages within the reserved region – that is, eachpage-sized address range within the reserved region that begins on apage boundary may be committed independently.Although it is obvious that a normal chunk is just a special case of adouble-ended chunk, and both of these are special cases of a disconnected chunk, we decided to separate the types because the specializedforms occur frequently and we can implement them more efficientlythan the general purpose disconnected chunk.

Figure 7.8 shows the different types of chunks and the common terminology used to describetheir attributes.As with other types of kernel resource, you can create chunks thatare local, or private, to the creating process or chunks that are global.Local chunks cannot be mapped into any other process and thus theTHE MEMORY MODEL INTERFACE265reserved memoryNormal chunkcommitted memorybasesizemax.

sizesizeDouble-endedchunkbottomtopDisconnectedchunksizeFigure 7.8 Fundamental chunk typesoperating system uses them for any memory that does not need to beshared. Conversely, you can map a global chunk into one or more otherprocesses. A process can discover and map global chunks that are named,whereas the only way for a process to access an unnamed global chunkis for it to receive a handle to the chunk from a process that alreadyhas one.The operating system uses chunks for different purposes, and thisinformation is also specified when creating a chunk.

The memory modeluses this information to determine where in the virtual address space toallocate a chunk, which access permissions must be applied and howto map the chunk into the kernel or user process memory context. Thekernel uses the TChunkType enumeration to describe the purpose ofthe chunk to the memory model, and the following table explains thedifferent types:ValueEKernelDataDescriptionThere is a single chunk of this type used to managethe global data for all XIP kernel-mode software, theinitial (null) thread stack and the dynamic kernelheap. The virtual address for this chunk depends onthe memory model, but is set during ROM266ValueMEMORY MODELSDescriptionconstruction and extracted from the ROM header atruntime. It is used to calculate the runtime dataaddresses for relocating the XIP code in ROM.EKernelStackThere is single chunk of this type used to allocate allkernel-mode thread stacks.

The difference withEKernelData is that the address range for thischunk is reserved dynamically during boot.EKernelCodeThere is at most a single chunk of this type, used toallocate memory for all non-XIP kernel-mode code,such as device drivers loaded from disk. It differsfrom the previous type by requiring executepermissions and I-cache management.Edll EUserCodeThe kernel uses these chunks to allocate memory orpage mappings for non-XIP user-mode code. Thememory model determines how these chunks areused and how code is allocated in them.ERamDriveThis chunk contains the RAM drive, if present. Thevirtual address of the RAM drive is defined by thememory model – this allows the contents to berecovered after a software reboot.EUserDataGeneral purpose chunks for user-mode processes.The kernel uses these chunks for program variables,stacks and heaps.

May be private to a process orshared with one or more other processes.EDllDataThis chunk allocates memory for writable staticvariables in user DLLs. The virtual address for thischunk must be fixed by the memory model, as it isused to calculate the runtime data address for XIPcode in the ROM. Non-XIP DLLs have their dataaddresses allocated at load time.Each user process that links to or loads a DLL that haswritable static data will have one of these chunks.EuserSelfModCodeThis is a special type of user-mode chunk that isallowed to contain executable code. For example, aJIT compiler in a Java runtime would use one for theTHE MEMORY MODEL INTERFACEValue267Descriptioncompiled code sequences. This type of chunk differsfrom EUserData in the access permissions and alsothe cache management behavior.ESharedKernelSingleThe kernel provides these shared chunk types forESharedKernelMultiple memory that needs to be shared between deviceESharedIodrivers and user-mode programs.

Unlike otheruser-mode accessible chunks, these can only havethe mapping adjusted by kernel software, whichmakes them suitable for direct access by hardwaredevices.ESharedKernelMirrorSome memory models map shared chunks into thekernel memory context using an independentmapping – in this case, this chunk owns theadditional mapping.Here is the DChunk class:class DChunk : public DObject{public:enum TChunkAttributes{ENormal=0x00,EDoubleEnded=0x01,EDisconnected=0x02,EConstructed=0x04,EMemoryNotOwned=0x08};enum TCommitType{ECommitDiscontiguous= 0,ECommitContiguous= 1,ECommitPhysicalMask= 2,ECommitDiscontiguousPhysical=ECommitDiscontiguous|ECommitPhysicalMask,ECommitContiguousPhysical=ECommitContiguous|ECommitPhysicalMask,};DChunk();∼DChunk();TInt Create(SChunkCreateInfo& aInfo);inline TInt Size() const {return iSize;}inline TInt MaxSize() const {return iMaxSize;}inline TUint8 *Base() const {return iBase;}268MEMORY MODELSinline TInt Bottom() const {return iStartPos;}inline TInt Top() const {return iStartPos+iSize;}inline DProcess* OwningProcess() const{return iOwningProcess;}public:virtual TInt AddToProcess(DProcess* aProcess);virtual TInt DoCreate(SChunkCreateInfo& aInfo)=0;virtual TInt Adjust(TInt aNewSize)=0;virtual TInt AdjustDoubleEnded(TInt aBottom, TInt aTop)=0;virtual TInt CheckAccess()=0;virtual TInt Commit(TInt aOffset, TInt aSize, TCommitType aCommitType=DChunk::ECommitDiscontiguous, TUint32* aExtraArg=0)=0;virtual TInt Allocate(TInt aSize, TInt aGuard=0, TInt aAlign=0)=0;virtual TInt Decommit(TInt aOffset, TInt aSize)=0;virtual TInt Address(TInt aOffset, TInt aSize,TLinAddr& aKernelAddress)=0;virtual TInt PhysicalAddress(TInt aOffset, TInt aSize,TLinAddr& aKernelAddress,TUint32& aPhysicalAddress,TUint32* aPhysicalPageList=NULL)=0;public:DProcess* iOwningProcess;TInt iSize;TInt iMaxSize;TUint8* iBase;TInt iAttributes;TInt iStartPos;TUint iControllingOwner;TUint iRestrictions;TUint iMapAttr;TDfc* iDestroyedDfc;TChunkType iChunkType;};In the following table, I describe the meanings of some of DChunk’skey member data:Summary of fields in DChunk:FieldDescriptioniOwningProcessIf the chunk is only ever mapped into a single process,this is the process control block for the process thatcreated and owns this chunk.

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

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

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

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