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

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

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

On acontext switch we remove this page directory entry and create a new onein the seventh position, this time setting the domain to 1 (with the DACRset to check-permissions for domain 1). After clearing the TLB entry forthe old address range we can no longer use address 0x00100000 toaccess the memory. However, we can now use 0x00600000, but onlyfrom supervisor mode as the permission bits are now being checked.Figure 7.11 shows the effect of making these simple changes to thepage directory.This is the essential idea that we use to provide each process withidentical virtual address spaces, but distinct and protected memory pages.During a context switch, we first move the old process’s memory outof the common execution address, making it inaccessible to user modeat the same time, and then we move the new process’s memory to thecommon execution address and make it accessible.This is also one of the motivations behind the concept and implementation of the chunk, described in Section 7.3.1, which is the unit of‘‘moving memory’’ within the higher layers of this memory model.Unfortunately, as with many good ideas, this one is not without itsdrawbacks.

If you remember, I earlier described the problem that can becaused by mapping memory at different virtual memory addresses, evenwhen spread out in time – and that the solution is to flush the cache.This means that all modified data is copied back to main memory andall cached data is discarded and must be reloaded from main memorywhen required. As a result, a process context switch with this memorymodel is dominated by the time spent flushing the cache, and is typically100 times slower than a thread context switch (within the same process).There is little hope that in future cache flushing will be made faster byTHE MEMORY MODELS0010000000600000Page table 1Domain 0:Full access<empty>Page Directory00100000279contextswichPage Table<empty>Domain 1:Restricted00600000Page table 1Figure 7.11 Remapping memory by modifying the page directorynew processors and memory, as performance gained there is lost flushingever larger caches.The moving memory model employs some of the other ARMv5 features, such as domains and split caches, to reduce the requirement forcache flushing.

However, it cannot be entirely removed and still constitutes a measurable proportion of the execution time for Symbian OS.It is interesting to note that ARMv5 provides an alternative to multiple page directories or moving page tables – the Fast Context SwitchExtensions.

In this mode, the MMU translates the virtual address beforedoing regular address translation using the page tables, and can eliminatethe expensive cache flush on a context switch. In this mode, the MMUwill replace the highest 7 bits of the virtual address with the value inthe FCSE PID register, if these bits were all zero. This means that virtualaddresses in the range 0x00000000 to 0x02000000 will be mapped tosome other 32 MB range before the page tables are walked. On a processcontext switch all that is needed is to change the FCSE PID. Althoughpopular with other open operating systems using ARMv5, this limits thesystem to 127 processes (the number of distinct, non-zero FCSE PIDvalues) and each process to a virtual address space of 32 MB includingcode.

The need for the kernel to use some of the memory map for otherpurposes can reduce these limits significantly. These limitations were notacceptable for Symbian OS.280MEMORY MODELS7.4.1.3 DesignAs I have already described, the moving memory model maintains asingle page directory for the whole OS. The rest of this section providesa high-level view of the moving memory model design.Address spacesAllocated memory is always owned by a single-page table, and the pagetable will be owned by a single chunk. Thus a chunk is always responsiblefor a whole number of megabytes of virtual address space, and the baseaddress is always aligned on a megabyte boundary.Each chunk is always present in exactly one place in the memorymap, and so all of the page tables that it owns will be referenced fromconsecutive page directory entries.

One consequence of this is that therecan never be more than 4096 distinct page tables at any one time.The previous rule is not directly obvious from the requirements.Memory that is not accessible to the currently executing process does notalways need to be in the memory map. However, much of Symbian OSexecution involves inter-process activity and the implementations of theclient/server system and thread I/O requests rely on having access to thememory of a non-current process.

If we ensure that this memory is directlyaccessible to the kernel, we can simplify these algorithms considerably.By default, the data chunks for a process are moving chunks and thesehave two address ranges allocated for them. The first is the data sectionaddress (or run address) which is the virtual address used by the processthat creates the chunk and the range is as large as the maximum sizefor the chunk. The latter is necessary because the virtual address of thechunk is specified to never change as the chunk grows or shrinks. When amoving chunk is mapped into a second process, the memory model doesnot guarantee that the virtual address in the second process matches thatin the first one. Thus the data section address is specific to each processthat has access to the chunk.The second address is the kernel section address (or home address)which is the virtual address occupied by the chunk when it is bothinaccessible to the currently running process and the current process isnot fixed – see the following optimizations section for an explanation offixed processes.

Page directory entries are only reserved in the kernelsection for the currently committed memory in the chunk. If additionalpage tables are added to the chunk later, a new kernel section addresswill be allocated – this is not a problem as the kernel section address isonly ever used transiently for inter-process memory accesses.The memory model manages the chunks that are accessible to eachprocess by maintaining for each process an address ordered list of alldata chunks that are mapped by the process.

Each entry on this list alsocontains the data section address for that chunk in the process. The chunkTHE MEMORY MODELS281itself knows about its kernel section address, and whether it is currentlymapped in the kernel section, or if it is mapped in the data section.ProtectionUsing the memory moving technique shown in Figure 7.11, two domainsare used to provide protection between the currently running process andthe memory that should be inaccessible to the process, such as kernelmemory or that belonging to other processes.

Although it might be moreobvious for the memory model to just use page permissions to achievethis, modifying the page permissions during a context switch wouldrequire changing every entry of the affected page tables – the schemeusing domains only requires that the memory model modifies a handfulof page directory entries.Most chunks use page permissions that deny access from user mode,but allow read/write access from supervisor modes.

Chunks that arenot accessible to the current user process are allocated to domain 1,while those that are accessible to the current user process are allocatedto domain 0. The domain access control register is set to allow allaccess to domain 0 (ignoring the permission bits), but makes the MMUcheck permissions for access to domain 1. This has the desired effect ofallowing a process to access its own memory from user mode (chunksin the data section), but other memory is inaccessible except fromsupervisor modes.Some chunks have slightly different permissions to improve the robustness of Symbian OS:• Once loaded, all chunks containing code are marked as read-only, toprevent inadvertent or malicious modification of software• The mappings for the RAM drive are allocated to domain 3. Thisdomain is set to no-access by default, preventing even faulty kernelcode from damaging the disk contents.

The RAM disk media driver isgranted access to this domain temporarily when modifying the diskcontents.Figure 7.12 illustrates the effective access control provided by themoving memory model, compared with the ideal presented earlier inthe chapter. Note that the only compromise for user-mode softwareis the visibility of program code that has not been explicitly loadedby the program. However, this memory model does make all memorydirectly accessible from kernel mode. Kernel-mode software must alreadytake care to ensure that user processes cannot read or corrupt kernelmemory through the executive interface, so extending that care to guardagainst incorrect access to another process does not add any significantcomplexity to the OS.282MEMORY MODELSTheoryKernel StacksKernel HeapKernel dataI/O memoryMoving Memory ModelROMcodeKernel StacksKernel HeapKernel dataI/O memoryROMcodeProgram AstacksCommonbufferProgram BstacksProgram AstacksCommonbufferProgram BstacksProgram AheapProgram AbufferProgram BheapProgram AheapProgram AbufferProgram BheapProgram AcodeShared codeProgram BcodeProgram AcodeShared codeProgram BcodeProgram B thread in user modeKernel StacksKernel HeapKernel dataI/O memoryProgram B thread in user modeROMcodeKernel StacksKernel HeapKernel dataI/O memoryROMcodeProgram AstacksCommonbufferProgram BstacksProgram AstacksCommonbufferProgram BstacksProgram AheapProgram AbufferProgram BheapProgram AheapProgram AbufferProgram BheapProgram AcodeShared codeProgram BcodeProgram AcodeShared codeProgram BcodeProgram B thread in kernel modeProgram B thread in kernel modeFigure 7.12 Memory accessible to a thread in the moving memory modelOptimizationsEvery time an operation requires the moving of at least one chunk, thememory model must flush the relevant cache and TLB – therefore thememory model design attempts to reduce the number of chunks thatneed to be moved.• A global chunk is used to allocate code segments.

Thus code executesfrom the same address in all processes. Additionally, code loaded byone process is visible to the entire OS – although this is a compromisefor system robustness, it avoids a very expensive operation to adjust theaccess permissions for all RAM-loaded code, and flush TLBs. TogetherTHE MEMORY MODELS283this ensures that the memory model never needs to flush the I-cacheon a context switch, significantly improving system performance• Some chunks are fixed in memory, and their virtual address neverchanges. In these cases, we use domains to control access to thechunk by changing the DACR for the processes that are allowedaccess. This can reduce the number of chunks that need to be movedon a context switch• Important and heavily used server processes can be marked as fixedprocesses.

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

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

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

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