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

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

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

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

Consider the scullpipe implementation of the poll method:unsigned int scull_p_poll(struct file *filp, poll_table *wait){Scull_Pipe *dev = filp->private_data;unsigned int mask = 0;/** The buffer is circular; it is considered full* if "wp" is right behind "rp". "left" is 0 if the* buffer is empty, and it is "1" if it is completely full.*/int left = (dev->rp + dev->buffersize - dev->wp) % dev->buffersize;poll_wait(filp, &dev->inq, wait);poll_wait(filp, &dev->outq, wait);if (dev->rp != dev->wp) mask |= POLLIN | POLLRDNORM; /* readable */if (left != 1)mask |= POLLOUT | POLLWRNORM; /* writable */return mask;}This code simply adds the two scullpipe wait queues to the poll_table, thensets the appropriate mask bits depending on whether data can be read or written.The poll code as shown is missing end-of-file support.

The poll method shouldreturn POLLHUP when the device is at the end of the file. If the caller used theselect system call, the file will be reported as readable; in both cases the application will know that it can actually issue the read without waiting forever, and theread method will return 0 to signal end-of-file.With real FIFOs, for example, the reader sees an end-of-file when all the writersclose the file, whereas in scullpipe the reader never sees end-of-file. The behavioris different because a FIFO is intended to be a communication channel betweentwo processes, while scullpipe is a trashcan where everyone can put data as longas there’s at least one reader.

Moreover, it makes no sense to reimplement what isalready available in the kernel.Implementing end-of-file in the same way as FIFOs do would mean checkingdev->nwriters, both in read and in poll, and reporting end-of-file (as justdescribed) if no process has the device opened for writing. Unfortunately, though,if a reader opened the scullpipe device before the writer, it would see end-of-filewithout having a chance to wait for data. The best way to fix this problem wouldbe to implement blocking within open; this task is left as an exercise for thereader.15622 June 2001 16:36http://openlib.org.uapoll and selectInteraction with read and writeThe purpose of the poll and select calls is to determine in advance if an I/O operation will block.

In that respect, they complement read and write. More important,poll and select are useful because they let the application wait simultaneously forseveral data streams, although we are not exploiting this feature in the scull examples.A correct implementation of the three calls is essential to make applications workcorrectly. Though the following rules have more or less already been stated, we’llsummarize them here.Reading data from the device•If there is data in the input buffer, the read call should return immediately,with no noticeable delay, even if less data is available than the applicationrequested and the driver is sure the remaining data will arrive soon. You canalways return less data than you’re asked for if this is convenient for any reason (we did it in scull), provided you return at least one byte.•If there is no data in the input buffer, by default read must block until at leastone byte is there.

If O_NONBLOCK is set, on the other hand, read returnsimmediately with a return value of -EAGAIN (although some old versions ofSystem V return 0 in this case). In these cases poll must report that the deviceis unreadable until at least one byte arrives. As soon as there is some data inthe buffer, we fall back to the previous case.•If we are at end-of-file, read should return immediately with a return value of0, independent of O_NONBLOCK. poll should report POLLHUP in this case.Writing to the device•If there is space in the output buffer, write should return without delay.

It canaccept less data than the call requested, but it must accept at least one byte. Inthis case, poll reports that the device is writable.•If the output buffer is full, by default write blocks until some space is freed. IfO_NONBLOCK is set, write returns immediately with a return value of-EAGAIN (older System V Unices returned 0). In these cases poll shouldreport that the file is not writable.

If, on the other hand, the device is not ableto accept any more data, write returns -ENOSPC (‘‘No space left on device’’),independently of the setting of O_NONBLOCK.•Never make a write call wait for data transmission before returning, even ifO_NONBLOCK is clear. This is because many applications use select to find outwhether a write will block. If the device is reported as writable, the call must15722 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver Operationsconsistently not block.

If the program using the device wants to ensure thatthe data it enqueues in the output buffer is actually transmitted, the drivermust provide an fsync method. For instance, a removable device should havean fsync entry point.Although these are a good set of general rules, one should also recognize thateach device is unique and that sometimes the rules must be bent slightly. Forexample, record-oriented devices (such as tape drives) cannot execute partialwrites.Flushing pending outputWe’ve seen how the write method by itself doesn’t account for all data outputneeds. The fsync function, invoked by the system call of the same name, fills thegap.

This method’s prototype isint (*fsync) (struct file *file, struct dentry *dentry, int datasync);If some application will ever need to be assured that data has been sent to thedevice, the fsync method must be implemented. A call to fsync should return onlywhen the device has been completely flushed (i.e., the output buffer is empty),even if that takes some time, regardless of whether O_NONBLOCK is set.

Thedatasync argument, present only in the 2.4 kernel, is used to distinguishbetween the fsync and fdatasync system calls; as such, it is only of interest tofilesystem code and can be ignored by drivers.The fsync method has no unusual features. The call isn’t time critical, so everydevice driver can implement it to the author’s taste. Most of the time, char driversjust have a NULL pointer in their fops. Block devices, on the other hand, alwaysimplement the method with the general-purpose block_fsync, which in turnflushes all the blocks of the device, waiting for I/O to complete.The Underlying Data StructureThe actual implementation of the poll and select system calls is reasonably simple,for those who are interested in how it works. Whenever a user application callseither function, the kernel invokes the poll method of all files referenced by thesystem call, passing the same poll_table to each of them.

The structure is, forall practical purposes, an array of poll_table_entry structures allocated for aspecific poll or select call. Each poll_table_entry contains the struct filepointer for the open device, a wait_queue_head_t pointer, and await_queue_t entry. When a driver calls poll_wait, one of these entries getsfilled in with the information provided by the driver, and the wait queue entry getsput onto the driver’s queue.

The pointer to wait_queue_head_t is used to trackthe wait queue where the current poll table entry is registered, in order forfr ee_wait to be able to dequeue the entry before the wait queue is awakened.15822 June 2001 16:36http://openlib.org.uaAsynchronous NotificationIf none of the drivers being polled indicates that I/O can occur without blocking,the poll call simply sleeps until one of the (perhaps many) wait queues it is onwakes it up.What’s interesting in the implementation of poll is that the file operation may becalled with a NULL pointer as poll_table argument.

This situation can comeabout for a couple of reasons. If the application calling poll has provided a timeoutvalue of 0 (indicating that no wait should be done), there is no reason to accumulate wait queues, and the system simply does not do it. The poll_table pointeris also set to NULL immediately after any driver being polled indicates that I/O ispossible. Since the kernel knows at that point that no wait will occur, it does notbuild up a list of wait queues.When the poll call completes, the poll_table structure is deallocated, and allwait queue entries previously added to the poll table (if any) are removed fromthe table and their wait queues.Actually, things are somewhat more complex than depicted here, because the polltable is not a simple array but rather a set of one or more pages, each hosting anarray.

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

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

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

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