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

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

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

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

The kiobuf interface is intended to hide much of the complexity of the virtual memory system from device drivers (and other parts of thesystem that do I/O). Many features are planned for kiobufs, but their primary usein the 2.4 kernel is to facilitate the mapping of user-space buffers into the kernel.The kiobuf StructureAny code that works with kiobufs must include <linux/iobuf.h>. This filedefines struct kiobuf, which is the heart of the kiobuf interface. This structuredescribes an array of pages that make up an I/O operation; its fields include thefollowing:int nr_pages;The number of pages in this kiobufint length;The number of bytes of data in the bufferint offset;The offset to the first valid byte in the bufferstruct page **maplist;An array of page structures, one for each page of data in the kiobufThe key to the kiobuf interface is the maplist array. Functions that operate onpages stored in a kiobuf deal directly with the page structures—all of the virtualmemory system overhead has been moved out of the way.

This implementationallows drivers to function independent of the complexities of memory management, and in general simplifies life greatly.Prior to use, a kiobuf must be initialized. It is rare to initialize a single kiobuf inisolation, but, if need be, this initialization can be performed with kiobuf_init:void kiobuf_init(struct kiobuf *iobuf);Usually kiobufs are allocated in groups as part of a ker nel I/O vector, or kiovec. Akiovec can be allocated and initialized in one step with a call to alloc_kiovec:int alloc_kiovec(int nr, struct kiobuf **iovec);The return value is 0 or an error code, as usual.

When your code has finished withthe kiovec structure, it should, of course, return it to the system:void free_kiovec(int nr, struct kiobuf **);The kernel provides a pair of functions for locking and unlocking the pagesmapped in a kiovec:39622 June 2001 16:42http://openlib.org.uaThe kiobuf Interfaceint lock_kiovec(int nr, struct kiobuf *iovec[], int wait);int unlock_kiovec(int nr, struct kiobuf *iovec[]);Locking a kiovec in this manner is unnecessary, however, for most applications ofkiobufs seen in device drivers.Mapping User-Space Buffers and Raw I/OUnix systems have long provided a ‘‘raw’’ interface to some devices—blockdevices in particular—which performs I/O directly from a user-space buffer andavoids copying data through the kernel.

In some cases much improved performance can be had in this manner, especially if the data being transferred will notbe used again in the near future. For example, disk backups typically read a greatdeal of data from the disk exactly once, then forget about it. Running the backupvia a raw interface will avoid filling the system buffer cache with useless data.The Linux kernel has traditionally not provided a raw interface, for a number ofreasons. As the system gains in popularity, however, more applications that expectto be able to do raw I/O (such as large database management systems) are beingported.

So the 2.3 development series finally added raw I/O; the driving forcebehind the kiobuf interface was the need to provide this capability.Raw I/O is not always the great performance boost that some people think itshould be, and driver writers should not rush out to add the capability justbecause they can. The overhead of setting up a raw transfer can be significant,and the advantages of buffering data in the kernel are lost. For example, note thatraw I/O operations almost always must be synchronous — the write system callcannot return until the operation is complete.

Linux currently lacks the mechanisms that user programs need to be able to safely perform asynchronous raw I/Oon a user buffer.In this section, we add a raw I/O capability to the sbull sample block driver. Whenkiobufs are available, sbull actually registers two devices. The block sbull devicewas examined in detail in Chapter 12. What we didn’t see in that chapter was asecond, char device (called sbullr), which provides raw access to the RAM-diskdevice. Thus, /dev/sbull0 and /dev/sbullr0 access the same memory; the formerusing the traditional, buffered mode and the second providing raw access via thekiobuf mechanism.It is worth noting that in Linux systems, there is no need for block drivers to provide this sort of interface.

The raw device, in drivers/char/raw.c, provides thiscapability in an elegant, general way for all block devices. The block drivers neednot even know they are doing raw I/O. The raw I/O code in sbull is essentially asimplification of the raw device code for demonstration purposes.39722 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMARaw I/O to a block device must always be sector aligned, and its length must be amultiple of the sector size.

Other kinds of devices, such as tape drives, may nothave the same constraints. sbullr behaves like a block device and enforces thealignment and length requirements. To that end, it defines a few symbols:###define SBULLR_SECTOR 512 /* insist on this */define SBULLR_SECTOR_MASK (SBULLR_SECTOR - 1)define SBULLR_SECTOR_SHIFT 9The sbullr raw device will be registered only if the hard-sector size is equal toSBULLR_SECTOR. There is no real reason why a larger hard-sector size could notbe supported, but it would complicate the sample code unnecessarily.The sbullr implementation adds little to the existing sbull code.

In particular, theopen and close methods from sbull are used without modification. Since sbullr is achar device, however, it needs read and write methods. Both are defined to use asingle transfer function as follows:ssize_t sbullr_read(struct file *filp, char *buf, size_t size,loff_t *off){Sbull_Dev *dev = sbull_devices +MINOR(filp->f_dentry->d_inode->i_rdev);return sbullr_transfer(dev, buf, size, off, READ);}ssize_t sbullr_write(struct file *filp, const char *buf, size_t size,loff_t *off){Sbull_Dev *dev = sbull_devices +MINOR(filp->f_dentry->d_inode->i_rdev);return sbullr_transfer(dev, (char *) buf, size, off, WRITE);}The sbullr_transfer function handles all of the setup and teardown work, whilepassing off the actual transfer of data to yet another function.

It is written as follows:static int sbullr_transfer (Sbull_Dev *dev, char *buf, size_t count,loff_t *offset, int rw){struct kiobuf *iobuf;int result;/* Only block alignment and size allowed */if ((*offset & SBULLR_SECTOR_MASK) || (count & SBULLR_SECTOR_MASK))return -EINVAL;if ((unsigned long) buf & SBULLR_SECTOR_MASK)return -EINVAL;/* Allocate an I/O vector */result = alloc_kiovec(1, &iobuf);39822 June 2001 16:42http://openlib.org.uaThe kiobuf Interfaceif (result)return result;/* Map the user I/O buffer and do the I/O. */result = map_user_kiobuf(rw, iobuf, (unsigned long) buf, count);if (result) {free_kiovec(1, &iobuf);return result;}spin_lock(&dev->lock);result = sbullr_rw_iovec(dev, iobuf, rw,*offset >> SBULLR_SECTOR_SHIFT,count >> SBULLR_SECTOR_SHIFT);spin_unlock(&dev->lock);/* Clean up and return.

*/unmap_kiobuf(iobuf);free_kiovec(1, &iobuf);if (result > 0)*offset += result << SBULLR_SECTOR_SHIFT;return result << SBULLR_SECTOR_SHIFT;}After doing a couple of sanity checks, the code creates a kiovec (containing a single kiobuf) with alloc_kiovec.

It then uses that kiovec to map in the user buffer bycalling map_user_kiobuf:int map_user_kiobuf(int rw, struct kiobuf *iobuf,unsigned long address, size_t len);The result of this call, if all goes well, is that the buffer at the given (user virtual)address with length len is mapped into the given iobuf. This operation cansleep, since it is possible that part of the user buffer will need to be faulted intomemory.A kiobuf that has been mapped in this manner must eventually be unmapped, ofcourse, to keep the reference counts on the pages straight. This unmapping isaccomplished, as can be seen in the code, by passing the kiobuf tounmap_kiobuf.So far, we have seen how to prepare a kiobuf for I/O, but not how to actually perform that I/O.

The last step involves going through each page in the kiobuf anddoing the required transfers; in sbullr, this task is handled by sbullr_rw_iovec.Essentially, this function passes through each page, breaks it up into sector-sizedpieces, and passes them to sbull_transfer via a fake request structure:static int sbullr_rw_iovec(Sbull_Dev *dev, struct kiobuf *iobuf, int rw,int sector, int nsectors){struct request fakereq;struct page *page;int offset = iobuf->offset, ndone = 0, pageno, result;39922 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMA/* Perform I/O on each sector */fakereq.sector = sector;fakereq.current_nr_sectors = 1;fakereq.cmd = rw;for (pageno = 0; pageno < iobuf->nr_pages; pageno++) {page = iobuf->maplist[pageno];while (ndone < nsectors) {/* Fake up a request structure for the operation */fakereq.buffer = (void *) (kmap(page) + offset);result = sbull_transfer(dev, &fakereq);kunmap(page);if (result == 0)return ndone;/* Move on to the next one */ndone++;fakereq.sector++;offset += SBULLR_SECTOR;if (offset >= PAGE_SIZE) {offset = 0;break;}}}return ndone;}Here, the nr_pages member of the kiobuf structure tells us how many pagesneed to be transferred, and the maplist array gives us access to each page.

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

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

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

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