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

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

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

Of course, even when no longerdemanded by the underlying memory hardware, the chunk will alwaysform part of the user-mode interface for memory management.7.4.2.4 AlgorithmsI will describe the same operations for the multiple memory model as Idid for the moving model to illustrate the design.THE MEMORY MODELS295c1400000page directories (up to 256 * 16KB)c1000000c0100000page table infoc0080000c0040000c0000000ASID info (256 ASIDs)super page/CPU pageFigure 7.18 Memory management detail for the multiple memory modelProcess context switchThe design of ARMv6 ensures that the address space switch is now asimple operation. It is fast enough that it can be executed with preemptiondisabled, making a process switch only marginally slower than a simplethread switch.The process context switch involves modifying two MMU registers:• TTBR0 is set to the page directory for the new process• CONTEXTID is set to the ASID for the new process.The only extra work occurs if the new process contains user-mode ‘‘selfmodifying’’ code chunks, and was not the last such process to run, inwhich case this function invalidates the dynamic branch prediction tablebefore returning.Thread request completeIn contrast, this is now a more complex operation than the equivalentin the moving memory model.

This is because the memory to which weneed to write is not visible in the current address space,This function can afford to use a different, faster, technique for writinginto another address space when compared with a general IPC datacopy, because it doesn’t need to simultaneously map both the signaling296MEMORY MODELSand requesting process memory. Instead, the current nanokernel threadchanges its address space, effectively executing briefly within the memorycontext of the target thread.The memory model manages this sleight of hand by changing theTTBR0 and CONTEXTID registers to the values for the target thread withinterrupts disabled.

At the same time, it updates the current thread’siAddressSpace member to ensure that the right memory context isrestored if the next operation is preempted. Now that the current threadhas ‘‘jumped’’ into the target process address space, it can just writethe result code before restoring the MMU state to return to the originaladdress context.Some care must be taken when writing to the request status to catchthe use of an invalid memory address. The system lock is held andso RequestComplete() traps any exception and then processes thefailure once the address space has been restored.7.4.3 The direct modelThis memory model disables the MMU and the OS assumes a directmapping from virtual address to physical address.

Although this enablesSymbian OS to run on hardware that has no MMU, Symbian OS does notsupport this option in products as the lack of an MMU presents too manylimitations for the OS as a whole:• The manufacturer must divide the physical memory at build timebetween all the running processes in the OS, as memory chunkscannot be grown and shrunk without an MMU. This makes it difficultto support a variety of different memory-hungry use cases in a singledevice without supplying an excessive amount of RAM• There is no memory protection between different user-mode processes or between user and kernel software – making the systemsignificantly less robust.

It would certainly be unwise to considerallowing such a device to support installation of additional softwareafter production.However, there are times when it is useful to be able to run part ofSymbian OS – in particular the kernel and file server – with the MMUdisabled, such as when porting EKA2 to a new CPU or a new CPU family.Such porting tasks are easier if the MMU is initially disabled to stabilizethe essential parts of the board support package without debugging newmemory hardware at the same time.

Once EKA2 is running on thehardware, the porting team can enable the MMU and tackle any memoryrelated problems independently.THE MEMORY MODELS2977.4.4 The emulator modelAs one might expect, we developed this memory model specificallyto support the emulator hosted by the Windows operating system. Toachieve the objectives set for the emulator regarding development anddemonstration, we made some compromises regarding true emulation ofthe behavior of the hardware memory models.It is here in the memory model that we find the most significantdifferences between target and emulator kernels.The emulator does not run on the ‘‘bare metal’’ of the PC hardware,but is hosted as a process within the Windows operating system.

As aresult, the low-level memory support in the emulator memory model usesstandard Windows APIs for basic memory allocation.7.4.4.1 Virtual address mappingThe emulator runs as a single Win32 process, with the consequencethat it only has a 2 GB virtual address range for all memory allocation.Compare this with a real device, where each application within theOS typically has approximately 1 GB of virtual address space for itsown use.To provide the programming model of the chunk, the emulator uses thelow-level VirtualAlloc() Windows API, which can reserve, commitand release pages of the process address space.

This also enables anemulation of the page-wise allocation of RAM to a chunk, and allowssome approximation to be made of the amount of RAM being used bythe OS at any time. However, the emulator does not allocate all memoryin this way.The emulator utilizes the Windows DLL format and the Windowsloader – LoadLibrary() and friends – to enable standard WindowsIDEs to be used for debugging of Symbian OS code in the emulator.As a result, Windows allocates and manages the memory used for codesegments and the static data associated with DLLs and EXEs.The emulator uses native Windows threads to provide Symbian OSthreads, again enabling standard development tools to debug multithreaded Symbian code.

This results in Windows allocating and managing the software execution stack for the thread. As is typical forWindows threads, these stacks grow dynamically and can becomevery large – unlike the fixed size, fully committed stacks on targethardware.7.4.4.2 ProtectionThe emulator runs within a single Windows process and thus within asingle Windows address space. All memory committed to the emulator298MEMORY MODELSis accessible by any Symbian OS process within the emulator. As aresult, the emulator provides no memory protection between SymbianOS processes, or between Symbian ‘‘user’’ and ‘‘kernel’’ memory.Technically, it would be possible to make use of another Windows API,VirtualProtect(), which allows a program to change the access permissions for a region of committed memory, to, for example, temporarilymake some memory inaccessible.

The emulator could use this functionto allow the current emulated Symbian OS process to only access its ownmemory chunks, and so provide some level of memory isolation betweenSymbian OS processes within the emulator. However, this would resultin a poor multi-threaded debug experience as the memory for much ofthe OS would be unreadable by the debugger.7.5 Programmer APIsIn Sections 7.2, MMUs and caches, and 7.3, The memory model interface,we looked at the very fundamental blocks of memory: the page and theobjects used in the interface between the generic kernel and the memorymodel. Symbian OS provides a number of higher-level memory conceptsand objects to provide user-mode and kernel-mode programmers withthe right level of abstraction and control when allocating and usingmemory:• The chunk forms the basic API for almost all memory allocation andownership both inside the kernel and within user-mode processes• One of the main consumers of chunks is the RHeap allocator class,which provides a free store allocator on top of a chunk.

There areversions for both user- and kernel-side software. The standard C++and C allocation functions use this allocator by default• Kernel-mode software also has lower-level APIs designed for allocating memory, which are suitable for direct device or DMA access.These include physically contiguous RAM, shared I/O buffers andshared chunks.7.5.1 ChunksIn Section 7.3.1, we looked at the principles of chunks, and how thememory model provides support for them.

In this section we look at theprogramming interface for chunks.Outside of the kernel executable, EKERN.EXE, kernel-mode softwareonly uses chunks directly for allocation when creating shared chunks,and I will discuss these later in this section. The user-mode API for chunksis the RChunk class:PROGRAMMER APIs299class RChunk : public RHandleBase{public:enum TRestrictions{EPreventAdjust = 0x01};public:inline TInt Open(...);IMPORT_C TInt CreateLocal(...);IMPORT_C TInt CreateLocalCode(...);IMPORT_C TInt CreateGlobal(...);IMPORT_C TInt CreateDoubleEndedLocal(...);IMPORT_C TInt CreateDoubleEndedGlobal(...);IMPORT_C TInt CreateDisconnectedLocal(...);IMPORT_C TInt CreateDisconnectedGlobal(...);IMPORT_C TInt Create(...);IMPORT_C TInt SetRestrictions(TUint aFlags);IMPORT_C TInt OpenGlobal(...);IMPORT_C TInt Open(RMessagePtr2,...);IMPORT_C TInt Open(TInt);IMPORT_C TInt Adjust(TInt aNewSize) const;IMPORT_C TInt AdjustDoubleEnded(TInt aBottom, TInt aTop) const;IMPORT_C TInt Commit(TInt anOffset, TInt aSize) const;IMPORT_C TInt Allocate(TInt aSize) const;IMPORT_C TInt Decommit(TInt anOffset, TInt aSize) const;IMPORT_C TUint8* Base() const;IMPORT_C TInt Size() const;IMPORT_C TInt Bottom() const;IMPORT_C TInt Top() const;IMPORT_C TInt MaxSize() const;inline TBool IsReadable() const;inline TBool IsWritable() const;};This follows the standard handle pattern found with all kernel resources.It is a fairly simple API with approximately half of the members beingways to initialize the handle, either as a result of creating a new chunkor by gaining access to an already existing one.

The different versionsare used to create the different types of chunk and specify the visibilityof the chunk. The other half of the class members either provide accessto chunk attributes such as the base address (within the calling processaddress space), or provide the user-mode API to the various chunk adjustmethods as already described in Section 7.3.1.Aside from the use of global chunks to share memory between processes, programmers only rarely use a chunk directly to allocate memory.More often they utilize them as the underlying memory management forsome form of allocator.7.5.2 Free store allocators and heapsAn allocator is an object that services requests to acquire and releasememory for a program.

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

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

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

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