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

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

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

To isolate the kernel from differentmemory hardware designs, this interaction is encapsulated in a distinctarchitectural unit that we call the ‘‘memory model’’. As I describe thedifferent memory models provided with EKA2 you will find out how theyuse the memory address space (the memory map) and their contributionto overall system behavior.7.1 The memory modelAt the application level – and to a large extent when writing kernelside software – the main use of memory is for allocation from the freestore using operator new or malloc. However, there are some morefundamental memory services that are used to provide the foundationfrom which such memory allocators can be built.The kernel has the following responsibilities related to memory management:1.

Management of the physical memory resources: RAM, MMU andcaches2. Allocation of virtual and physical memory252MEMORY MODELS3.Per-process address space management4.Process isolation and kernel memory protection5.The memory aspects of the software loader.As well as providing these essential services, we wanted to ensure thatthe design of the memory model does not impose hard or low limits onthe operating system.

In particular:• The number of processes should be limited by physical resourcesrather than the memory model, and should certainly exceed 64• Each process should have a large dedicated address space of 1–2 GB• The amount of executable code that can be loaded by a processshould be limited only by available ROM/RAM.We found that the provision of efficient services to carry out theseresponsibilities is dependent on the memory architecture in the hardware.In particular, a design that is fast and small for some hardware may proveto be too slow or require too much memory if used on another. Asone of the aims of EKA2 was to be readily portable to new hardware,including new MMU and memory architectures, we took all of the codethat implements the different memory designs out of the generic kerneland provided a common interface. The resulting block of code we callthe ‘‘memory model’’.

This is itself layered, as I have already brieflydescribed in Chapter 1, Introducing EKA2. I will repeat the key parts ofthe illustration I gave there as Figure 7.1.NKernNKernSymbian OS KernelIndependentMemory ModelPlatformMemory ModelModelMemory ModelFigure 7.1Symbian OS KernelCPUASSP DLLASPVariant DLLVariantMemory model layeringAt the highest level, we have to distinguish between a native implementation of EKA2 and an emulated one. In the former case, EKA2 isMMUs AND CACHES253the OS that owns the CPU, the memory and all the peripherals, andthe system boots from a ROM image.

In the latter case another ‘‘host’’OS provides basic services to EKA2, including memory allocation andsoftware loading. This layer is referred to as the ‘‘platform’’.As I mentioned in Chapter 1, Introducing EKA2, there are several waysto design an MMU and cache. We want to provide the best use ofmemory and performance for Symbian OS and so the different hardwarearchitectures result in different memory model designs. The basic choicesare as follows:No MMUDirect memory modelVirtually tagged cacheMoving memory modelPhysically tagged cacheMultiple memory modelEmulatorEmulator memory modelI describe these different memory models in detail later in the chapter.Even for identical memory architectures, different CPUs have differentways of controlling the MMU and cache and the final layer in the memorymodel, the ‘‘CPU’’ layer, supplies the specific code to control the memoryin individual CPUs.7.2 MMUs and caches7.2.1 MMUBefore describing how EKA2 uses the RAM in the device to provide thememory services to the operating system and applications, it is worthexplaining how the hardware presents the memory to the software.EKA2 is a 32-bit operating system, which means that it assumes thatall memory addresses can be represented in a 32-bit register.

This limitsthe amount of simultaneously addressable memory to 4 GB. In practicethere is far less physical memory than this, typically between 16 MB and32 MB in the mobile phones available at the time of writing.One of the important aspects of nearly all Symbian devices is that theyare ‘‘open’’ – they allow the user to install third-party native applicationsand services. This is very different from a mobile handset based on anembedded OS, and is very significant for the way the OS must managememory. It has several consequences:1. In an embedded OS, one can determine the maximum memoryrequirement of each component.

Then, at compilation time, one can254MEMORY MODELSallocate exactly the memory that is needed to each component. Thismeans that the exact amount of RAM needed is known when buildingthe product. ‘‘Static allocation’’ of this kind is not viable with an openplatform2.There are certain types of application that ideally would use all available memory to provide maximum benefit to the user – for example,web browsers encountering complex web sites. Providing each suchapplication with dedicated RAM would prove very expensive, particularly considering that most of this memory would be unused mostof the time3.The built-in software can be tested as thoroughly as required by thedevice manufacturer.

However, third-party software added later canthreaten the stability and integrity of the device. A poorly writtenor malicious program can be harmful if this software is allowed todirectly interfere with the memory of the OS.These issues make it important to make use of a piece of hardwarefound in higher-end devices: a memory management unit (MMU). This isresponsible for the memory interface between the CPU and the memoryhardware, which is typically a memory controller and one or morememory chips.The rest of this section explores the various key features of a MMU andhow EKA2 makes use of them.7.2.1.1 Virtual addresses and address translationOne of the key services of an MMU is an abstraction between what thesoftware considers to be a memory address and the real physical addressof the RAM.

The former is called the virtual address in this context andthe latter the physical address.This disconnection between the address in the software and thehardware address provides the mechanism to resolve the first two issuesassociated with an ‘‘open’’ OS. In particular, the OS can allocate a largerange of virtual addresses for an application but only allocate the physicalmemory as and when the application requires it.

Allocation of virtualaddresses is often referred to as reserving, allocation of physical memoryas committing.The MMU and OS must maintain a mapping from virtual addresses tophysical addresses in a form that allows the MMU to efficiently translatefrom the virtual to physical address whenever a memory access occurs.The most common structure used to hold this map is called a multi-levelpage directory, and the hardware supported by Symbian OS specificallysupports two-level page directories. Some high-end CPUs now use threeor more levels in the MMU, particularly 64-bit processors that supportMMUs AND CACHES255virtual address ranges with more than 32 bits. Figure 7.2 shows what amulti-level page directory might look like.Level 1Page DirectoryLevel 2Page TableFigure 7.2Main memoryPageA multi-level page directoryThe first level in a two-level directory is commonly referred to as thepage directory.

Conceptually there is just one of these directories usedto do the mapping, although this is not always literally true – and we’llexamine that in the next section. The directory is just a table of referencesto the items in the second level of the directory.In the second level there are page tables. Typically there will be tens tohundreds of these objects in the mapping.

Each page table itself containsa table of references to individual pieces of memory.The memory itself has to be divided up into a collection of memorypages or frames. MMUs often support a small range of different pagesizes: EKA2 prefers to use page sizes of 4 KB and 1 MB, but may alsomake use of others if available.Perhaps the best way to understand how a virtual address is translated into a physical address through this structure would be to workthrough an example. To illustrate how address translation works, I shallconcentrate on how an ARM MMU translates an address that refers tomemory in a 4 KB page – this translation process is also called pagetable walking.Let’s suppose that a program has a string, ‘‘Hello world’’, at address0x87654321 and issues an instruction to read the first character ofthis string.

Figure 7.3 illustrates the work done by the MMU to find thememory page containing the string.256MMUTTBRMEMORY MODELSLevel 1Page Directory1. Extract the addressof the page directoryfrom the MMU registerLevel 2Page TableMain memoryPage3. Extract the address ofthe page directory fromthe page directory entry5. Extract the address ofthe memory page fromthe page table entry2.

Calculate the offsetinto the page directoryusing the high 12 bitsof the virtual address"Hello world"4. Calculate the offsetinto the page tableusing the middle 8 bitsof the virtual address6. Calculate the offsetinto the page usingthe low 12 bits of thevirtual address1 0 0 0 0 1 1 1 0 1 1 0 0 1 0 1 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0 1Virtual address (32 bits)Figure 7.3 Algorithm for translating virtual addressesCurrently, ARM MMUs have a page directory which contains 212entries, each of which is 4 bytes – making the page directory 16 KB insize. Each entry is therefore responsible for 220 bytes of address space,that is, 1 MB.

When this entry refers to a page table containing 4 KBpages the page table will therefore have 28 entries. Again, each entry is 4bytes, making the page table 1 KB in size.First, the address provided by the program is broken up into threepieces. These provide three separate indexes into the different levels ofthe mapping.Next the MMU locates the address of the page directory by reading itsTranslation Table Base Register (TTBR). The topmost 12 bits of the virtualaddress, in this case 0x876, is used as an index into the page directory.The MMU reads the entry from the page directory and determines that itrefers to a page table for 4 KB pages.Then, using the next 8 bits of the address, 0x54, as an offset into thepage table, the MMU can read the page table entry.

This now providesthe physical address of the memory page.The final 12 bits of the address are now combined with the pageaddress to create the physical address of the string and this is used tofulfill the read request.It is worth noting that the addresses in the TTBR, page directory entriesand page table entries are all physical addresses. Otherwise, the MMUMMUs AND CACHES257would have to use page table walking to do page table walking and thealgorithm would never terminate!Translation look-aside buffersThe algorithm described for translating addresses is quite simple, but ifyou consider that it requires two additional external memory accesses foreach load or store operation it is easy to see that it is slow and inefficient.To overcome this problem, MMUs provide a cache of the most recentsuccessful address translations, and this is called the Translation Lookaside Buffer (TLB). This often stores the most recent 32 or 64 pages thatwere accessed, and allows the MMU to very quickly translate virtualaddresses that correspond to one of those pages.As with all caches, the kernel must manage the TLB to ensure thatwhen the kernel makes changes to the underlying page tables it alsomodifies or discards any affected entries in the TLB.TLBs are so effective that some MMUs do not provide the page-tablewalking algorithm in hardware at all.

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

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

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

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