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

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

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

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

Fortunately, a relatively easy workaround is available toany driver that needs to map RAM into user space; it uses the nopage method thatwe have seen earlier.Remapping RAM with the nopage methodThe way to map real RAM to user space is to use vm_ops->nopage to deal withpage faults one at a time. A sample implementation is part of the scullp module,introduced in Chapter 7.scullp is the page oriented char device.

Because it is page oriented, it can implement mmap on its memory. The code implementing memory mapping uses someof the concepts introduced earlier in ‘‘Memory Management in Linux.’’Before examining the code, let’s look at the design choices that affect the mmapimplementation in scullp.•scullp doesn’t release device memory as long as the device is mapped.

This isa matter of policy rather than a requirement, and it is different from the behavior of scull and similar devices, which are truncated to a length of zero whenopened for writing. Refusing to free a mapped scullp device allows a processto overwrite regions actively mapped by another process, so you can test andsee how processes and device memory interact. To avoid releasing a mappeddevice, the driver must keep a count of active mappings; the vmas field in thedevice structure is used for this purpose.39122 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMA•Memory mapping is performed only when the scullp order parameter is 0.The parameter controls how get_fr ee_pages is invoked (see Chapter 7,“get_free_page and Friends”).

This choice is dictated by the internals ofget_fr ee_pages, the allocation engine exploited by scullp. To maximize allocation performance, the Linux kernel maintains a list of free pages for each allocation order, and only the page count of the first page in a cluster is incremented by get_fr ee_pages and decremented by fr ee_pages. The mmap methodis disabled for a scullp device if the allocation order is greater than zero,because nopage deals with single pages rather than clusters of pages.

(Returnto “A scull Using Whole Pages: scullp” in Chapter 7 if you need a refresher onscullp and the memory allocation order value.)The last choice is mostly intended to keep the code simple. It is possible to correctly implement mmap for multipage allocations by playing with the usage countof the pages, but it would only add to the complexity of the example withoutintroducing any interesting information.Code that is intended to map RAM according to the rules just outlined needs toimplement open, close, and nopage; it also needs to access the memory map toadjust the page usage counts.This implementation of scullp_mmap is very short, because it relies on the nopagefunction to do all the interesting work:int scullp_mmap(struct file *filp, struct vm_area_struct *vma){struct inode *inode = INODE_FROM_F(filp);/* refuse to map if order is not 0 */if (scullp_devices[MINOR(inode->i_rdev)].order)return -ENODEV;/* don’t do anything here: "nopage" will fill the holes */vma->vm_ops = &scullp_vm_ops;vma->vm_flags |= VM_RESERVED;vma->vm_private_data = scullp_devices + MINOR(inode->i_rdev);scullp_vma_open(vma);return 0;}The purpose of the leading conditional is to avoid mapping devices whose allocation order is not 0.

scullp’s operations are stored in the vm_ops field, and apointer to the device structure is stashed in the vm_private_data field. At theend, vm_ops->open is called to update the usage count for the module and thecount of active mappings for the device.open and close simply keep track of these counts and are defined as follows:39222 June 2001 16:42http://openlib.org.uaThe mmap Device Operationvoid scullp_vma_open(struct vm_area_struct *vma){ScullP_Dev *dev = scullp_vma_to_dev(vma);dev->vmas++;MOD_INC_USE_COUNT;}void scullp_vma_close(struct vm_area_struct *vma){ScullP_Dev *dev = scullp_vma_to_dev(vma);dev->vmas--;MOD_DEC_USE_COUNT;}The function sculls_vma_to_dev simply returns the contents of the vm_private_data field. It exists as a separate function because kernel versions prior to2.4 lacked that field, requiring that other means be used to get that pointer.

See“Backward Compatibility” at the end of this chapter for details.Most of the work is then performed by nopage. In the scullp implementation, theaddress parameter to nopage is used to calculate an offset into the device; theoffset is then used to look up the correct page in the scullp memory tree.struct page *scullp_vma_nopage(struct vm_area_struct *vma,unsigned long address, int write){unsigned long offset;ScullP_Dev *ptr, *dev = scullp_vma_to_dev(vma);struct page *page = NOPAGE_SIGBUS;void *pageptr = NULL; /* default to "missing" */down(&dev->sem);offset = (address - vma->vm_start) + VMA_OFFSET(vma);if (offset >= dev->size) goto out; /* out of range *//** Now retrieve the scullp device from the list, then the page.* If the device has holes, the process receives a SIGBUS when* accessing the hole.*/offset >>= PAGE_SHIFT; /* offset is a number of pages */for (ptr = dev; ptr && offset >= dev->qset;) {ptr = ptr->next;offset -= dev->qset;}if (ptr && ptr->data) pageptr = ptr->data[offset];if (!pageptr) goto out; /* hole or end-of-file */page = virt_to_page(pageptr);/* got it, now increment the count */39322 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAget_page(page);out:up(&dev->sem);return page;}scullp uses memory obtained with get_fr ee_pages.

That memory is addressed usinglogical addresses, so all scullp_nopage has to do to get a struct page pointer isto call virt_to_ page.The scullp device now works as expected, as you can see in this sample outputfrom the mapper utility. Here we send a directory listing of /dev (which is long) tothe scullp device, and then use the mapper utility to look at pieces of that listingwith mmap.morgana% ls -l /dev > /dev/scullpmorgana% ./mapper /dev/scullp 0 140mapped "/dev/scullp" from 0 to 140total 77-rwxr-xr-x1 rootroot26689 Mar 2 2000 MAKEDEVcrw-rw-rw1 rootroot14, 14 Aug 10 20:55 admmidi0morgana% ./mapper /dev/scullp 8192 200mapped "/dev/scullp" from 8192 to 83920crw — — —1 rootroot113,1 Mar 26 1999 cum1crw — — —1 rootroot113,2 Mar 26 1999 cum2crw — — —1 rootroot113,3 Mar 26 1999 cum3Remapping Virtual AddressesAlthough it’s rarely necessary, it’s interesting to see how a driver can map a virtualaddress to user space using mmap.

A true virtual address, remember, is an addressreturned by a function like vmalloc or kmap—that is, a virtual address mapped inthe kernel page tables. The code in this section is taken from scullv, which is themodule that works like scullp but allocates its storage through vmalloc.Most of the scullv implementation is like the one we’ve just seen for scullp, exceptthat there is no need to check the order parameter that controls memory allocation.

The reason for this is that vmalloc allocates its pages one at a time, becausesingle-page allocations are far more likely to succeed than multipage allocations.Therefore, the allocation order problem doesn’t apply to vmalloced space.Most of the work of vmalloc is building page tables to access allocated pages as acontinuous address range. The nopage method, instead, must pull the page tablesback apart in order to return a struct page pointer to the caller. Therefore, thenopage implementation for scullv must scan the page tables to retrieve the pagemap entry associated with the page.39422 June 2001 16:42http://openlib.org.uaThe mmap Device OperationThe function is similar to the one we saw for scullp, except at the end. This codeexcerpt only includes the part of nopage that differs from scullp:pgd_t *pgd; pmd_t *pmd; pte_t *pte;unsigned long lpage;/** After scullv lookup, "page" is now the address of the page* needed by the current process.

Since it’s a vmalloc address,* first retrieve the unsigned long value to be looked up* in page tables.*/lpage = VMALLOC_VMADDR(pageptr);spin_lock(&init_mm.page_table_lock);pgd = pgd_offset(&init_mm, lpage);pmd = pmd_offset(pgd, lpage);pte = pte_offset(pmd, lpage);page = pte_page(*pte);spin_unlock(&init_mm.page_table_lock);/* got it, now increment the count */get_page(page);out:up(&dev->sem);return page;The page tables are looked up using the functions introduced at the beginning ofthis chapter.

The page directory used for this purpose is stored in the memorystructure for kernel space, init_mm. Note that scullv obtains thepage_table_lock prior to traversing the page tables. If that lock were not held,another processor could make a change to the page table while scullv washalfway through the lookup process, leading to erroneous results.The macro VMALLOC_VMADDR(pageptr) returns the correct unsigned longvalue to be used in a page-table lookup from a vmalloc address.

A simple cast ofthe value wouldn’t work on the x86 with kernels older than 2.1, because of aglitch in memory management. Memory management for the x86 changed in version 2.1.1, and VMALLOC_VMADDR is now defined as the identity function, as ithas always been for the other platforms. Its use is still suggested, however, as away of writing portable code.Based on this discussion, you might also want to map addresses returned byior emap to user space.

This mapping is easily accomplished because you can useremap_ page_range directly, without implementing methods for virtual memoryareas. In other words, remap_ page_range is already usable for building new pagetables that map I/O memory to user space; there’s no need to look in the kernelpage tables built by vr emap as we did in scullv.39522 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAThe kiobuf InterfaceAs of version 2.3.12, the Linux kernel supports an I/O abstraction called the ker nelI/O buffer, or kiobuf.

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

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

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

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