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

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

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

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

When a task queue runs, however, that process could be asleep, executing on a different processor, or could conceivably have exited altogether.This asynchronous execution resembles what happens when a hardware interrupthappens (which is discussed in detail in Chapter 9). In fact, task queues are often19122 June 2001 16:37http://openlib.org.uaChapter 6: Flow of Timerun as the result of a ‘‘software interrupt.’’ When running in interrupt mode (orinterrupt time) in this way, your code is subject to a number of constraints. Wewill introduce these constraints now; they will be seen again in several places inthis book. Repetition is called for in this case; the rules for interrupt mode must befollowed or the system will find itself in deep trouble.A number of actions require the context of a process in order to be executed.When you are outside of process context (i.e., in interrupt mode), you mustobserve the following rules:•No access to user space is allowed.

Because there is no process context, thereis no path to the user space associated with any particular process.•The current pointer is not valid in interrupt mode, and cannot be used.•No sleeping or scheduling may be performed. Interrupt-mode code may notcall schedule or sleep_on; it also may not call any other function that maysleep. For example, calling kmalloc( . .

. , GFP_KERNEL) is against therules. Semaphores also may not be used since they can sleep.Kernel code can tell if it is running in interrupt mode by calling the functionin_interrupt( ), which takes no parameters and returns nonzero if the processor isrunning in interrupt time.One other feature of the current implementation of task queues is that a task canrequeue itself in the same queue from which it was run. For instance, a task beingrun from the timer tick can reschedule itself to be run on the next tick by callingqueue_task to put itself on the queue again.

Rescheduling is possible because thehead of the queue is replaced with a NULL pointer before consuming queuedtasks; as a result, a new queue is built once the old one starts executing.Although rescheduling the same task over and over might appear to be a pointlessoperation, it is sometimes useful. For example, consider a driver that moves a pairof stepper motors one step at a time by rescheduling itself on the timer queueuntil the target has been reached. Another example is the jiq module, where theprinting function reschedules itself to produce its output—the result is several iterations through the timer queue.Predefined Task QueuesThe easiest way to perform deferred execution is to use the queues that arealready maintained by the kernel.

There are a few of these queues, but your drivercan use only three of them, described in the following list. The queues aredeclared in <linux/tqueue.h>, which you should include in your source.The scheduler queueThe scheduler queue is unique among the predefined task queues in that itruns in process context, implying that the tasks it runs have a bit more freedom in what they can do. In Linux 2.4, this queue runs out of a dedicated19222 June 2001 16:37http://openlib.org.uaTask Queueskernel thread called keventd and is accessed via a function called schedule_task.

In older versions of the kernel, keventd was not used, and the queue(tq_scheduler) was manipulated directly.tq_timerThis queue is run by the timer tick. Because the tick (the function do_timer)runs at interrupt time, any task within this queue runs at interrupt time as well.tq_immediateThe immediate queue is run as soon as possible, either on return from a system call or when the scheduler is run, whichever comes first. The queue isconsumed at interrupt time.Other predefined task queues exist as well, but they are not generally of interest todriver writers.The timeline of a driver using a task queue is represented in Figure 6-1. The figureshows a driver that queues a function in tq_immediate from an interrupt handler.How the examples workExamples of deferred computation are available in the jiq (“Just In Queue”) module, from which the source in this section has been extracted.

This module creates/pr oc files that can be read using dd or other tools; this is similar to jit.The process reading a jiq file is put to sleep until the buffer is full.* This sleepingis handled with a simple wait queue, declared asDECLARE_WAIT_QUEUE_HEAD (jiq_wait);The buffer is filled by successive runs of a task queue.

Each pass through thequeue appends a text string to the buffer being filled; each string reports the current time (in jiffies), the process that is current during this pass, and the returnvalue of in_interrupt.The code for filling the buffer is confined to the jiq_ print_tq function, which executes at each run through the queue being used. The printing function is not interesting and is not worth showing here; instead, let’s look at the initialization of thetask to be inserted in a queue:struct tq_struct jiq_task; /* global: initialized to zero *//* these lines are in jiq_init() */jiq_task.routine = jiq_print_tq;jiq_task.data = (void *)&jiq_data;* The buffer of a /pr oc file is a page of memory, 4 KB, or whatever is appropriate for theplatform you use.19322 June 2001 16:37http://openlib.org.uaChapter 6: Flow of TimeCode Being Executedblah();blah();Datatq_immediateInterrupttask0do_sth();queue_task (task,tq);do_sth_else();return;tq_immediatetask1ReturnfrominterruptOther tasks may be queuedblah();blah();1As soon as possible,at a safe time1run_task_queue(tq_immediate);tq_immediatedo_the_task();return;blah();blah();task0KEY“sync” bitProcess codeKernel codeDriver codetq_immediate(and pointer to task)Xstruct task_struct(and pointer to next)Figur e 6-1.

Timeline of task-queue usageThere’s no need to clear the sync and next fields of jiq_task because staticvariables are initialized to 0 by the compiler.The scheduler queueThe scheduler queue is, in some ways, the easiest to use. Because tasks executed19422 June 2001 16:37http://openlib.org.uaTask Queuesfrom this queue do not run in interrupt mode, they can do more things; in particular, they can sleep. Many parts of the kernel use this queue to accomplish a widevariety of tasks.As of kernel 2.4.0-test11, the actual task queue implementing the scheduler queueis hidden from the rest of the kernel. Rather than use queue_task directly, codeusing this queue must call schedule_task to put a task on the queue:int schedule_task(struct tq_struct *task);task, of course, is the task to be scheduled.

The return value is directly fromqueue_task: nonzero if the task was not already on the queue.Again, as of 2.4.0-test11, the kernel runs a special process, called keventd, whosesole job is running tasks from the scheduler queue. keventd provides a predictableprocess context for the tasks it runs (unlike the previous implementation, whichwould run tasks under an essentially random process’s context).There are a couple of implications to the keventd implementation that are worthkeeping in mind.

The first is that tasks in this queue can sleep, and some kernelcode takes advantage of that freedom. Well-behaved code, however, should takecare to sleep only for very short periods of time, since no other tasks will be runfrom the scheduler queue while keventd is sleeping. It is also a good idea to keepin mind that your task shares the scheduler queue with others, which can alsosleep.

In normal situations, tasks placed in the scheduler queue will run veryquickly (perhaps even before schedule_task returns). If some other task sleeps,though, the time that elapses before your tasks execute could be significant. Tasksthat absolutely have to run within a narrow time window should use one of theother queues./pr oc/jiqsched is a sample file that uses the scheduler queue. The read function forthe file dispatches everything to the task queue in the following way:int jiq_read_sched(char *buf, char **start, off_t offset,int len, int *eof, void *data){jiq_data.len = 0;jiq_data.buf = buf;jiq_data.jiffies = jiffies;/* nothing printed, yet *//* print in this place *//* initial time *//* jiq_print will queue_task() again in jiq_data.queue */jiq_data.queue = SCHEDULER_QUEUE;schedule_task(&jiq_task);interruptible_sleep_on(&jiq_wait);/* ready to run *//* sleep till completion */*eof = 1;return jiq_data.len;}19522 June 2001 16:37http://openlib.org.uaChapter 6: Flow of TimeReading /pr oc/jiqsched produces output like the following:time delta interrupt601687006016870060168700601687006016870060168700601687006016870060168700pid cpu command21 keventd21 keventd21 keventd21 keventd21 keventd21 keventd21 keventd21 keventd21 keventdIn this output, the time field is the value of jiffies when the task is run,delta is the change in jiffies since the last time the task ran, interrupt isthe output of the in_interrupt function, pid is the ID of the running process, cpuis the number of the CPU being used (always 0 on uniprocessor systems), andcommand is the command being run by the current process.In this case, we see that the task is always running under the keventd process.

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

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

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

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