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

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

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

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

Actually, it does notify the driver if the size of the area is reducedvia the unmap method, but no callback is issued if the area increases in size.The basic idea behind notifying the driver of a reduction is that the driver (or thefilesystem mapping a regular file to memory) needs to know when a region isunmapped in order to take the proper action, such as flushing pages to disk.Growth of the mapped region, on the other hand, isn’t really meaningful for thedriver until the program invoking mr emap accesses the new virtual addresses.

Inreal life, it’s quite common to map regions that are never used (unused sections ofprogram code, for example). The Linux kernel, therefore, doesn’t notify the driverif the mapped region grows, because the nopage method will take care of pagesone at a time as they are actually accessed.In other words, the driver isn’t notified when a mapping grows because nopagewill do it later, without having to use memory before it is actually needed.

Thisoptimization is mostly aimed at regular files, whose mapping uses real RAM.The nopage method, therefore, must be implemented if you want to support themr emap system call. But once you have nopage, you can choose to use it extensively, with some limitations (described later). This method is shown in the nextcode fragment. In this implementation of mmap, the device method only replacesvma->vm_ops. The nopage method takes care of ‘‘remapping’’ one page at a timeand returning the address of its struct page structure. Because we are justimplementing a window onto physical memory here, the remapping step is simple — we need only locate and return a pointer to the struct page for thedesired address.An implementation of /dev/mem using nopage looks like the following:struct page *simple_vma_nopage(struct vm_area_struct *vma,unsigned long address, int write_access){struct page *pageptr;unsigned long physaddr = address - vma->vm_start + VMA_OFFSET(vma);pageptr = virt_to_page(_ _va(physaddr));get_page(pageptr);return pageptr;}int simple_nopage_mmap(struct file *filp, struct vm_area_struct *vma){unsigned long offset = VMA_OFFSET(vma);38822 June 2001 16:42http://openlib.org.uaThe mmap Device Operationif (offset >= _ _pa(high_memory) || (filp->f_flags & O_SYNC))vma->vm_flags |= VM_IO;vma->vm_flags |= VM_RESERVED;vma->vm_ops = &simple_nopage_vm_ops;simple_vma_open(vma);return 0;}Since, once again, we are simply mapping main memory here, the nopage function need only find the correct struct page for the faulting address and increment its reference count.

The required sequence of events is thus to calculate thedesired physical address, turn it into a logical address with _ _va, and then finallyto turn it into a struct page with virt_to_ page. It would be possible, in general,to go directly from the physical address to the struct page, but such codewould be difficult to make portable across architectures. Such code might be necessary, however, if one were trying to map high memory, which, remember, hasno logical addresses. simple, being simple, does not worry about that (rare) case.If the nopage method is left NULL, kernel code that handles page faults maps thezero page to the faulting virtual address. The zero page is a copy-on-write pagethat reads as zero and that is used, for example, to map the BSS segment.

Therefore, if a process extends a mapped region by calling mr emap, and the driverhasn’t implemented nopage, it will end up with zero pages instead of a segmentation fault.The nopage method normally returns a pointer to a struct page. If, for somereason, a normal page cannot be returned (e.g., the requested address is beyondthe device’s memory region), NOPAGE_SIGBUS can be returned to signal theerror. nopage can also return NOPAGE_OOM to indicate failures caused by resourcelimitations.Note that this implementation will work for ISA memory regions but not for thoseon the PCI bus. PCI memory is mapped above the highest system memory, andthere are no entries in the system memory map for those addresses.

Because thereis thus no struct page to return a pointer to, nopage cannot be used in thesesituations; you must, instead, use remap_ page_range.Remapping Specific I/O RegionsAll the examples we’ve seen so far are reimplementations of /dev/mem; theyremap physical addresses into user space. The typical driver, however, wants tomap only the small address range that applies to its peripheral device, not all ofmemory.

In order to map to user space only a subset of the whole memory range,the driver needs only to play with the offsets. The following lines will do the trickfor a driver mapping a region of simple_region_size bytes, beginning atphysical address simple_region_start (which should be page aligned).38922 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAunsignedunsignedunsignedunsignedlonglonglonglongoff = vma->vm_pgoff << PAGE_SHIFT;physical = simple_region_start + off;vsize = vma->vm_end - vma->vm_start;psize = simple_region_size - off;if (vsize > psize)return -EINVAL; /* spans too high */remap_page_range(vma_>vm_start, physical, vsize, vma->vm_page_prot);In addition to calculating the offsets, this code introduces a check that reports anerror when the program tries to map more memory than is available in the I/Oregion of the target device.

In this code, psize is the physical I/O size that is leftafter the offset has been specified, and vsize is the requested size of virtualmemory; the function refuses to map addresses that extend beyond the allowedmemory range.Note that the user process can always use mr emap to extend its mapping, possiblypast the end of the physical device area. If your driver has no nopage method, itwill never be notified of this extension, and the additional area will map to thezero page. As a driver writer, you may well want to prevent this sort of behavior;mapping the zero page onto the end of your region is not an explicitly bad thingto do, but it is highly unlikely that the programmer wanted that to happen.The simplest way to prevent extension of the mapping is to implement a simplenopage method that always causes a bus signal to be sent to the faulting process.Such a method would look like this:struct page *simple_nopage(struct vm_area_struct *vma,unsigned long address, int write_access);{ return NOPAGE_SIGBUS; /* send a SIGBUS */}Remapping RAMOf course, a more thorough implementation could check to see if the faultingaddress is within the device area, and perform the remapping if that is the case.Once again, however, nopage will not work with PCI memory areas, so extensionof PCI mappings is not possible.

In Linux, a page of physical addresses is markedas ‘‘reserved’’ in the memory map to indicate that it is not available for memorymanagement. On the PC, for example, the range between 640 KB and 1 MB ismarked as reserved, as are the pages that host the kernel code itself.An interesting limitation of remap_ page_range is that it gives access only toreserved pages and physical addresses above the top of physical memory.Reserved pages are locked in memory and are the only ones that can be safelymapped to user space; this limitation is a basic requirement for system stability.39022 June 2001 16:42http://openlib.org.uaThe mmap Device OperationTherefore, remap_ page_range won’t allow you to remap conventionaladdresses—which include the ones you obtain by calling get_fr ee_page.

Instead, itwill map in the zero page. Nonetheless, the function does everything that mosthardware drivers need it to, because it can remap high PCI buffers and ISA memory.The limitations of remap_ page_range can be seen by running mapper, one of thesample programs in misc-pr ogs in the files provided on the O’Reilly FTP site. mapper is a simple tool that can be used to quickly test the mmap system call; it mapsread-only parts of a file based on the command-line options and dumps themapped region to standard output.

The following session, for instance, shows that/dev/mem doesn’t map the physical page located at address 64 KB—instead wesee a page full of zeros (the host computer in this examples is a PC, but the resultwould be the same on other platforms):morgana.root# ./mapper /dev/mem 0x10000 0x1000 | od -Ax -t x1mapped "/dev/mem" from 65536 to 69632000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00*001000The inability of remap_ page_range to deal with RAM suggests that a device likescullp can’t easily implement mmap, because its device memory is conventionalRAM, not I/O memory.

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

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

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

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