Главная » Просмотр файлов » Linux Device Drivers 2nd Edition

Linux Device Drivers 2nd Edition (779877), страница 88

Файл №779877 Linux Device Drivers 2nd Edition (Linux Device Drivers 2nd Edition) 88 страницаLinux Device Drivers 2nd Edition (779877) страница 882018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Since it requires a logicaladdress, it will not work with memory from vmalloc or high memory.void *page_address(struct page *page);Returns the kernel virtual address of this page, if such an address exists. Forhigh memory, that address exists only if the page has been mapped.#include <linux/highmem.h>void *kmap(struct page *page);void kunmap(struct page *page);kmap returns a kernel virtual address for any page in the system. For lowmemory pages, it just returns the logical address of the page; for high-memorypages, kmap creates a special mapping.

Mappings created with kmap shouldalways be freed with kunmap; a limited number of such mappings is available, so it is better not to hold on to them for too long. kmap calls are37422 June 2001 16:42http://openlib.org.uaMemory Management in Linuxadditive, so if two or more functions both call kmap on the same page theright thing happens. Note also that kmap can sleep if no mappings are available.We will see some uses of these functions when we get into the example code laterin this chapter.Page TablesWhen a program looks up a virtual address, the CPU must convert the address to aphysical address in order to access physical memory.

The step is usually performed by splitting the address into bitfields. Each bitfield is used as an index intoan array, called a page table, to retrieve either the address of the next table or theaddress of the physical page that holds the virtual address.The Linux kernel manages three levels of page tables in order to map virtualaddresses to physical addresses. The multiple levels allow the memory range to besparsely populated; modern systems will spread a process out across a large rangeof virtual memory.

It makes sense to do things that way; it allows for runtime flexibility in how things are laid out.Note that Linux uses a three-level system even on hardware that only supports twolevels of page tables or hardware that uses a different way to map virtualaddresses to physical ones. The use of three levels in a processor-independentimplementation allows Linux to support both two-level and three-level processorswithout clobbering the code with a lot of #ifdef statements.

This kind of conservative coding doesn’t lead to additional overhead when the kernel runs on twolevel processors, because the compiler actually optimizes out the unused level.It is time to take a look at the data structures used to implement the paging system. The following list summarizes the implementation of the three levels in Linux,and Figure 13-2 depicts them.Page Directory (PGD)The top-level page table. The PGD is an array of pgd_t items, each of whichpoints to a second-level page table. Each process has its own page directory,and there is one for kernel space as well.

You can think of the page directoryas a page-aligned array of pgd_ts.Page mid-level Directory (PMD)The second-level table. The PMD is a page-aligned array of pmd_t items. Apmd_t is a pointer to the third-level page table. Two-level processors have nophysical PMD; they declare their PMD as an array with a single element,whose value is the PMD itself—we’ll see in a while how this is handled in Cand how the compiler optimizes this level away.37522 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAVirtual Address (addr)struct mm_struct00111010110110011001101110110101111pgd partpmd partpte partoffsetPGDpgd_tpgd_tpgd_tpgd_tpgd_tpgd_tpgd_tpgd_tpgd_tpgd_tpgd_tpgd_tPMDpmd_tpmd_tpmd_tpmd_tpmd_tpmd_tpmd_tpmd_tpmd_tpmd_tpmd_tpmd_tPTEpte_tpte_tpte_tpte_tpte_tpte_tpte_tpte_tpte_tpte_tpte_tpte_tSoftware relationshipspgd_offset(mm_struct, addr);pmd_offset(pgd_t, addr);pte_offset(pmd_t, addr);pte_page(pte_t);page.virtualstruct pagephysical pageHardware relationshipspgd_val(pgd);pmd_val(pmd);pte_val(pte);Figur e 13-2.

The thr ee levels of Linux page tablesPage TableA page-aligned array of items, each of which is called a Page Table Entry. Thekernel uses the pte_t type for the items. A pte_t contains the physicaladdress of the data page.The types introduced in this list are defined in <asm/page.h>, which must beincluded by every source file that plays with paging.The kernel doesn’t need to worry about doing page-table lookups during normalprogram execution, because they are done by the hardware. Nonetheless, the kernel must arrange things so that the hardware can do its work.

It must build thepage tables and look them up whenever the processor reports a page fault, that is,37622 June 2001 16:42http://openlib.org.uaMemory Management in Linuxwhenever the page associated with a virtual address needed by the processor isnot present in memory. Device drivers, too, must be able to build page tables andhandle faults when implementing mmap.It’s interesting to note how software memory management exploits the same pagetables that are used by the CPU itself.

Whenever a CPU doesn’t implement pagetables, the difference is only hidden in the lowest levels of architecture-specificcode. In Linux memory management, therefore, you always talk about three-levelpage tables irrespective of whether they are known to the hardware or not. Anexample of a CPU family that doesn’t use page tables is the PowerPC. PowerPCdesigners implemented a hash algorithm that maps virtual addresses into a onelevel page table. When accessing a page that is already in memory but whosephysical address has expired from the CPU caches, the CPU needs to read memoryonly once, as opposed to the two or three accesses required by a multilevel pagetable approach. The hash algorithm, like multilevel tables, makes it possible toreduce use of memory in mapping virtual addresses to physical ones.Irrespective of the mechanisms used by the CPU, the Linux software implementation is based on three-level page tables, and the following symbols are used toaccess them.

Both <asm/page.h> and <asm/pgtable.h> must be included forall of them to be accessible.PTRS_PER_PGDPTRS_PER_PMDPTRS_PER_PTEThe size of each table. Two-level processors set PTRS_PER_PMD to 1, toavoid dealing with the middle level.unsigned pgd_val(pgd_t pgd)unsigned pmd_val(pmd_t pmd)unsigned pte_val(pte_t pte)These three macros are used to retrieve the unsigned value from the typeddata item. The actual type used varies depending on the underlying architecture and kernel configuration options; it is usually either unsigned long or,on 32-bit processors supporting high memory, unsigned long long.SPARC64 processors use unsigned int. The macros help in using strict datatyping in source code without introducing computational overhead.pgd_t * pgd_offset(struct mm_struct * mm, unsigned longaddress)pmd_t * pmd_offset(pgd_t * dir, unsigned long address)pte_t * pte_offset(pmd_t * dir, unsigned long address)These inline functions* are used to retrieve the pgd, pmd, and pte entries* On 32-bit SPARC processors, the functions are not inline but rather real extern functions, which are not exported to modularized code.

Therefore you won’t be able to usethese functions in a module running on the SPARC, but you won’t usually need to.37722 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAassociated with address. Page-table lookup begins with a pointer to structmm_struct. The pointer associated with the memory map of the current process is current->mm, while the pointer to kernel space is described by&init_mm. Two-level processors define pmd_offset(dir,add) as(pmd_t *)dir, thus folding the pmd over the pgd. Functions that scan pagetables are always declared as inline, and the compiler optimizes out anypmd lookup.struct page *pte_page(pte_t pte)This function returns a pointer to the struct page entry for the page in thispage-table entry.

Code that deals with page-tables will generally want to usepte_ page rather than pte_val, since pte_ page deals with the processor-dependent format of the page-table entry and returns the struct page pointer,which is usually what’s needed.pte_present(pte_t pte)This macro returns a boolean value that indicates whether the data page iscurrently in memory. This is the most used of several functions that access thelow bits in the pte—the bits that are discarded by pte_ page. Pages may beabsent, of course, if the kernel has swapped them to disk (or if they havenever been loaded).

The page tables themselves, however, are always presentin the current Linux implementation. Keeping page tables in memory simplifies the kernel code because pgd_offset and friends never fail; on the otherhand, even a process with a ‘‘resident storage size’’ of zero keeps its pagetables in real RAM, wasting some memory that might be better used elsewhere.Each process in the system has a struct mm_struct structure, which containsits page tables and a great many other things. It also contains a spinlock calledpage_table_lock, which should be held while traversing or modifying thepage tables.Just seeing the list of these functions is not enough for you to be proficient in theLinux memory management algorithms; real memory management is much morecomplex and must deal with other complications, like cache coherence.

The previous list should nonetheless be sufficient to give you a feel for how page management is implemented; it is also about all that you will need to know, as a devicedriver writer, to work occasionally with page tables. You can get more informationfrom the include/asm and mm subtrees of the kernel source.Virtual Memory AreasAlthough paging sits at the lowest level of memory management, something moreis necessary before you can use the computer’s resources efficiently.

The kernelneeds a higher-level mechanism to handle the way a process sees its memory.This mechanism is implemented in Linux by means of virtual memory areas, whichare typically referred to as areas or VMAs.37822 June 2001 16:42http://openlib.org.uaMemory Management in LinuxAn area is a homogeneous region in the virtual memory of a process, a contiguousrange of addresses with the same permission flags. It corresponds loosely to theconcept of a ‘‘segment,’’ although it is better described as ‘‘a memory object withits own properties.’’ The memory map of a process is made up of the following:•An area for the program’s executable code (often called text).•One area each for data, including initialized data (that which has an explicitlyassigned value at the beginning of execution), uninitialized data (BSS),* andthe program stack.•One area for each active memory mapping.The memory areas of a process can be seen by looking in /pr oc/pid/maps (wherepid, of course, is replaced by a process ID).

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

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

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

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