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

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

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

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

In addition, the implementation of ior emap found in Linux 2.0 won’teven consider remapping a physical address that doesn’t start at a page boundary.Newer kernels allow that by ‘‘rounding down’’ the address to be remapped and byreturning an offset into the first remapped page.One minor drawback of vmalloc is that it can’t be used at interrupt time becauseinternally it uses kmalloc(GFP_KERNEL) to acquire storage for the page tables,and thus could sleep. This shouldn’t be a problem — if the use of _ _get_fr ee_pageisn’t good enough for an interrupt handler, then the software design needs somecleaning up.A scull Using Virtual Addresses: scullvSample code using vmalloc is provided in the scullv module.

Like scullp, this module is a stripped-down version of scull that uses a different allocation function toobtain space for the device to store data.The module allocates memory 16 pages at a time. The allocation is done in largechunks to achieve better performance than scullp and to show something thattakes too long with other allocation techniques to be feasible. Allocating morethan one page with _ _get_fr ee_pages is failure prone, and even when it succeeds,it can be slow. As we saw earlier, vmalloc is faster than other functions in allocating several pages, but somewhat slower when retrieving a single page, because ofthe overhead of page-table building.

scullv is designed like scullp. order specifiesthe ‘‘order’’ of each allocation and defaults to 4. The only difference betweenscullv and scullp is in allocation management. These lines use vmalloc to obtainnew memory:/* Allocate a quantum using virtual addresses */if (!dptr->data[s_pos]) {dptr->data[s_pos] =(void *)vmalloc(PAGE_SIZE << dptr->order);21922 June 2001 16:38http://openlib.org.uaChapter 7: Getting Hold of Memoryif (!dptr->data[s_pos])goto nomem;memset(dptr->data[s_pos], 0, PAGE_SIZE << dptr->order);}And these lines release memory:/* Release the quantum set */for (i = 0; i < qset; i++)if (dptr->data[i])vfree(dptr->data[i]);If you compile both modules with debugging enabled, you can look at their dataallocation by reading the files they create in /pr oc.

The following snapshots weretaken on two different systems:salma% cat /tmp/bigfile > /dev/scullp0; head -5 /proc/scullpmemDevice 0: qset 500, order 0, sz 1048576item at e00000003e641b40, qset at e000000025c600000:e00000003007c0001:e000000024778000salma% cat /tmp/bigfile > /dev/scullv0; head -5 /proc/scullvmemDevice 0: qset 500, order 4, sz 1048576item at e0000000303699c0, qset at e000000025c870000:a0000000000340001:a000000000078000salma% uname -mia64rudo% cat /tmp/bigfile > /dev/scullp0; head -5 /proc/scullpmemDevice 0: qset 500, order 0, sz 1048576item at c4184780, qset at c71c48000:c262b0001:c2193000rudo% cat /tmp/bigfile > /dev/scullv0; head -5 /proc/scullvmemDevice 0: qset 500, order 4, sz 1048576item at c4184b80, qset at c71c40000:c881a0001:c882b000rudo% uname -mi686The values show two different behaviors.

On IA-64, physical addresses and virtualaddresses are mapped to completely different address ranges (0xE and 0xA),whereas on x86 computers vmalloc returns virtual addresses just above the mapping used for physical memory.22022 June 2001 16:38http://openlib.org.uaBoot-Time AllocationBoot-Time AllocationIf you really need a huge buffer of physically contiguous memory, you need toallocate it by requesting memory at boot time. This technique is inelegant andinflexible, but it is also the least prone to failure. Needless to say, a module can’tallocate memory at boot time; only drivers directly linked to the kernel can dothat.Allocation at boot time is the only way to retrieve consecutive memory pageswhile bypassing the limits imposed by get_fr ee_pages on the buffer size, both interms of maximum allowed size and limited choice of sizes.

Allocating memory atboot time is a ‘‘dirty’’ technique, because it bypasses all memory management policies by reserving a private memory pool.One noticeable problem with boot-time allocation is that it is not a feasible optionfor the average user: being only available for code linked in the kernel image, adevice driver using this kind of allocation can only be installed or replaced byrebuilding the kernel and rebooting the computer. Fortunately, there are a pair ofworkarounds to this problem, which we introduce soon.Even though we won’t suggest allocating memory at boot time, it’s somethingworth mentioning because it used to be the only way to allocate a DMA-capablebuffer in the first Linux versions, before _ _GFP_DMA was introduced.Acquiring a Dedicated Buffer at Boot TimeWhen the kernel is booted, it gains access to all the physical memory available inthe system.

It then initializes each of its subsystems by calling that subsystem’s initialization function, allowing initialization code to allocate a memory buffer for private use by reducing the amount of RAM left for normal system operation.With version 2.4 of the kernel, this kind of allocation is performed by calling oneof these functions:#include <linux/bootmem.h>void *alloc_bootmem(unsigned long size);void *alloc_bootmem_low(unsigned long size);void *alloc_bootmem_pages(unsigned long size);void *alloc_bootmem_low_pages(unsigned long size);The functions allocate either whole pages (if they end with _pages) or non-pagealigned memory areas.

They allocate either low or normal memory (see the discussion of memory zones earlier in this chapter). Normal allocation returns memoryaddresses that are above MAX_DMA_ADDRESS; low memory is at addresses lowerthan that value.22122 June 2001 16:38http://openlib.org.uaChapter 7: Getting Hold of MemoryThis interface was introduced in version 2.3.23 of the kernel. Earlier versions useda less refined interface, similar to the one described in Unix books.

Basically, theinitialization functions of several kernel subsystems received two unsignedlong arguments, which represented the current bounds of the free memory area.Each such function could steal part of this area, returning the new lower bound. Adriver allocating memory at boot time, therefore, was able to steal consecutivememory from the linear array of available RAM.The main problem with this older mechanism of managing boot-time allocationrequests was that not all initialization functions could modify the lower memorybound, so writing a driver needing such allocation usually implied providing userswith a kernel patch.

On the other hand, alloc_bootmem can be called by the initialization function of any kernel subsystem, provided it is performed at boot time.This way of allocating memory has several disadvantages, not the least being theinability to ever free the buffer. After a driver has taken some memory, it has noway of returning it to the pool of free pages; the pool is created after all the physical allocation has taken place, and we don’t recommend hacking the data structures internal to memory management. On the other hand, the advantage of thistechnique is that it makes available an area of consecutive physical memory that issuitable for DMA.

This is currently the only safe way in the standard kernel to allocate a buffer of more than 32 consecutive pages, because the maximum value oforder that is accepted by get_fr ee_pages is 5. If, however, you need many pagesand they don’t have to be physically contiguous, vmalloc is by far the best function to use.If you are going to resort to grabbing memory at boot time, you must modifyinit/main.c in the kernel sources. You’ll find more about main.c in Chapter 16.Note that this ‘‘allocation’’ can be performed only in multiples of the page size,though the number of pages doesn’t have to be a power of two.The bigphysarea PatchAnother approach that can be used to make large, contiguous memory regionsavailable to drivers is to apply the bigphysar ea patch.

This unofficial patch hasbeen floating around the Net for years; it is so renowned and useful that some distributions apply it to the kernel images they install by default. The patch basicallyallocates memory at boot time and makes it available to device drivers at runtime.You’ll need to pass a command-line option to the kernel to specify the amount ofmemory that must be reserved at boot time.The patch is currently maintained at http://www.polywar e.nl/˜middelink/En/hobv4l.html. It includes its own documentation that describes the allocation interfaceit offers to device drivers. The Zoran 36120 frame grabber driver, part of the 2.4kernel (in drivers/char/zr36120.c) uses the bigphysar ea extension if it is available,and is thus a good example of how the interface is used.22222 June 2001 16:38http://openlib.org.uaBackward CompatibilityReserving High RAM AddressesThe last option for allocating contiguous memory areas, and possibly the easiest, isreserving a memory area at the end of physical memory (whereas bigphysar eareserves it at the beginning of physical memory).

To this aim, you need to pass acommand-line option to the kernel to limit the amount of memory being managed.For example, one of your authors uses mem=126M to reserve 2 megabytes in asystem that actually has 128 megabytes of RAM. Later, at runtime, this memory canbe allocated and used by device drivers.The allocator module, part of the sample code released on the O’Reilly FTP site,offers an allocation interface to manage any high memory not used by the Linuxkernel.

The module is described in more detail in “Do-it-yourself allocation” inChapter 13.The advantage of allocator over the bigphysar ea patch is that there’s no need tomodify official kernel sources. The disadvantage is that you must change the command-line option to the kernel whenever you change the amount of RAM in thesystem. Another disadvantage, which makes allocator unsuitable in some situations is that high memory cannot be used for some tasks, such as DMA buffers forISA devices.Backward CompatibilityThe Linux memory management subsystem has changed dramatically since the 2.0kernel came out. Happily, however, the changes to its programming interface havebeen much smaller and easier to deal with.kmalloc and kfr ee have remained essentially constant between Linux 2.0 and 2.4.Access to high memory, and thus the _ _GFP_HIGHMEM flag, was added startingwith kernel 2.3.23; sysdep.h fills the gaps and allows for 2.4 semantics to be usedin 2.2 and 2.0.The lookaside cache functions were introduced in Linux 2.1.23, and were simplynot available in the 2.0 kernel.

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

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

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

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