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

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

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

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

This complication is meant to avoid putting too low a limit (dictated by thepage size) on the maximum number of file descriptors involved in a poll or selectsystem call.We tried to show the data structures involved in polling in Figure 5-2; the figure isa simplified representation of the real data structures because it ignores the multipage nature of a poll table and disregards the file pointer that is part of eachpoll_table_entry.

The reader interested in the actual implementation is urgedto look in <linux/poll.h> and fs/select.c.Asynchronous NotificationThough the combination of blocking and nonblocking operations and the selectmethod are sufficient for querying the device most of the time, some situationsaren’t efficiently managed by the techniques we’ve seen so far.Let’s imagine, for example, a process that executes a long computational loop atlow priority, but needs to process incoming data as soon as possible.

If the inputchannel is the keyboard, you are allowed to send a signal to the application (usingthe ‘INTR’ character, usually CTRL-C), but this signaling ability is part of the ttyabstraction, a software layer that isn’t used for general char devices. What we needfor asynchronous notification is something different. Furthermore, any input datashould generate an interrupt, not just CTRL-C.User programs have to execute two steps to enable asynchronous notification froman input file. First, they specify a process as the ‘‘owner’’ of the file. When a process invokes the F_SETOWN command using the fcntl system call, the process IDof the owner process is saved in filp->f_owner for later use.

This step is necessary for the kernel to know just who to notify. In order to actually enable15922 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver OperationsThe data structures behind pollThe struct poll_table_structA process calls poll for one device onlyint error;struct poll_table_page *tables;The struct poll_table_entrywait_queue_t wait;wait_queue_head_t *wait_address;A generic device structurewith itswait_queue_head_tA process is calling poll (or select) on two devicesA process with an activepoll ()The structpoll_table_structPoll table entriesFigur e 5-2. The data structures of pollasynchronous notification, the user programs must set the FASYNC flag in thedevice by means of the F_SETFL fcntl command.After these two calls have been executed, the input file can request delivery of aSIGIO signal whenever new data arrives.

The signal is sent to the process (or process group, if the value is negative) stored in filp->f_owner.For example, the following lines of code in a user program enable asynchronousnotification to the current process for the stdin input file:signal(SIGIO, &input_handler); /* dummy sample; sigaction() is better */fcntl(STDIN_FILENO, F_SETOWN, getpid());oflags = fcntl(STDIN_FILENO, F_GETFL);fcntl(STDIN_FILENO, F_SETFL, oflags | FASYNC);The program named asynctest in the sources is a simple program that reads16022 June 2001 16:36http://openlib.org.uaAsynchronous Notificationstdin as shown. It can be used to test the asynchronous capabilities of scullpipe.The program is similar to cat, but doesn’t terminate on end-of-file; it responds onlyto input, not to the absence of input.Note, however, that not all the devices support asynchronous notification, and youcan choose not to offer it.

Applications usually assume that the asynchronouscapability is available only for sockets and ttys. For example, pipes and FIFOsdon’t support it, at least in the current kernels. Mice offer asynchronous notification because some programs expect a mouse to be able to send SIGIO like a ttydoes.There is one remaining problem with input notification.

When a process receives aSIGIO, it doesn’t know which input file has new input to offer. If more than onefile is enabled to asynchronously notify the process of pending input, the application must still resort to poll or select to find out what happened.The Driver’s Point of ViewA more relevant topic for us is how the device driver can implement asynchronoussignaling. The following list details the sequence of operations from the kernel’spoint of view:1.When F_SETOWN is invoked, nothing happens, except that a value is assignedto filp->f_owner.2.When F_SETFL is executed to turn on FASYNC, the driver’s fasync method iscalled.

This method is called whenever the value of FASYNC is changed infilp->f_flags, to notify the driver of the change so it can respond properly. The flag is cleared by default when the file is opened. We’ll look at thestandard implementation of the driver method soon.3.When data arrives, all the processes registered for asynchronous notificationmust be sent a SIGIO signal.While implementing the first step is trivial—there’s nothing to do on the driver’spart — the other steps involve maintaining a dynamic data structure to keep trackof the different asynchronous readers; there might be several of these readers.

Thisdynamic data structure, however, doesn’t depend on the particular deviceinvolved, and the kernel offers a suitable general-purpose implementation so thatyou don’t have to rewrite the same code in every driver.The general implementation offered by Linux is based on one data structure andtwo functions (which are called in the second and third steps described earlier).The header that declares related material is <linux/fs.h>—nothing newhere—and the data structure is called struct fasync_struct. As we did withwait queues, we need to insert a pointer to the structure in the device-specific datastructure. Actually, we’ve already seen such a field in the section “A Sample Implementation: scullpipe.”16122 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver OperationsThe two functions that the driver calls correspond to the following prototypes:int fasync_helper(int fd, struct file *filp,int mode, struct fasync_struct **fa);void kill_fasync(struct fasync_struct **fa, int sig, int band);fasync_helper is invoked to add files to or remove files from the list of interested processes when the FASYNC flag changes for an open file.

All of its arguments except the last are provided to the fasync method and can be passedthrough directly. kill_fasync is used to signal the interested processes whendata arrives. Its arguments are the signal to send (usually SIGIO) and the band,which is almost always POLL_IN (but which may be used to send “urgent” or outof-band data in the networking code).Here’s how scullpipe implements the fasync method:int scull_p_fasync(fasync_file fd, struct file *filp, int mode){Scull_Pipe *dev = filp->private_data;return fasync_helper(fd, filp, mode, &dev->async_queue);}It’s clear that all the work is performed by fasync_helper. It wouldn’t be possible,however, to implement the functionality without a method in the driver, becausethe helper function needs to access the correct pointer to structfasync_struct * (here &dev->async_queue), and only the driver can provide the information.When data arrives, then, the following statement must be executed to signal asynchronous readers.

Since new data for the scullpipe reader is generated by a process issuing a write, the statement appears in the write method of scullpipe.if (dev->async_queue)kill_fasync(&dev->async_queue, SIGIO, POLL_IN);It might appear that we’re done, but there’s still one thing missing. We mustinvoke our fasync method when the file is closed to remove the file from the listof active asynchronous readers. Although this call is required only iffilp->f_flags has FASYNC set, calling the function anyway doesn’t hurt and isthe usual implementation. The following lines, for example, are part of the closemethod for scullpipe:/* remove this filp from the asynchronously notified filp’s */scull_p_fasync(-1, filp, 0);The data structure underlying asynchronous notification is almost identical to thestructure struct wait_queue, because both situations involve waiting on anevent.

The difference is that struct file is used in place of structtask_struct. The struct file in the queue is then used to retrievef_owner, in order to signal the process.16222 June 2001 16:36http://openlib.org.uaSeeking a DeviceSeeking a DeviceThe difficult part of the chapter is over; now we’ll quickly detail the llseek method,which is useful and easy to implement.The llseek ImplementationThe llseek method implements the lseek and llseek system calls.

We have alreadystated that if the llseek method is missing from the device’s operations, the defaultimplementation in the kernel performs seeks from the beginning of the file andfrom the current position by modifying filp->f_pos, the current reading/writing position within the file. Please note that for the lseek system call to work correctly, the read and write methods must cooperate by updating the offset itemthey receive as argument (the argument is usually a pointer to filp->f_pos).You may need to provide your own llseek method if the seek operation corresponds to a physical operation on the device or if seeking from end-of-file, whichis not implemented by the default method, makes sense. A simple example can beseen in the scull driver:loff_t scull_llseek(struct file *filp, loff_t off, int whence){Scull_Dev *dev = filp->private_data;loff_t newpos;switch(whence) {case 0: /* SEEK_SET */newpos = off;break;case 1: /* SEEK_CUR */newpos = filp->f_pos + off;break;case 2: /* SEEK_END */newpos = dev->size + off;break;default: /* can’t happen */return -EINVAL;}if (newpos<0) return -EINVAL;filp->f_pos = newpos;return newpos;}The only device-specific operation here is retrieving the file length from thedevice.

In scull the read and write methods cooperate as needed, as shown in“read and write” in Chapter 3.16322 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver OperationsAlthough the implementation just shown makes sense for scull, which handles awell-defined data area, most devices offer a data flow rather than a data area (justthink about the serial ports or the keyboard), and seeking those devices does notmake sense. If this is the case, you can’t just refrain from declaring the llseek operation, because the default method allows seeking.

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

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

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

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