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

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

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

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

That is a perfectly valid implementation, but, if there are no other eventsof interest to your driver, delays can be achieved in a more straightforward mannerwith schedule_timeout:set_current_state(TASK_INTERRUPTIBLE);schedule_timeout (jit_delay*HZ);The previous line (for /pr oc/jitself ) causes the process to sleep until the given timehas passed. schedule_timeout, too, expects a time offset, not an absolute numberof jiffies. Once again, it is worth noting that an extra time interval could passbetween the expiration of the timeout and when your process is actually scheduled to execute.Short DelaysSometimes a real driver needs to calculate very short delays in order to synchronize with the hardware. In this case, using the jiffies value is definitely not thesolution.The kernel functions udelay and mdelay serve this purpose.* Their prototypes are#include <linux/delay.h>void udelay(unsigned long usecs);void mdelay(unsigned long msecs);The functions are compiled inline on most supported architectures.

The formeruses a software loop to delay execution for the required number of microseconds,and the latter is a loop around udelay, provided for the convenience of the programmer. The udelay function is where the BogoMips value is used: its loop isbased on the integer value loops_per_second, which in turn is the result of theBogoMips calculation performed at boot time.The udelay call should be called only for short time lapses because the precisionof loops_per_second is only eight bits, and noticeable errors accumulate when* The u in udelay represents the Greek letter mu and stands for micro.18822 June 2001 16:37http://openlib.org.uaTask Queuescalculating long delays.

Even though the maximum allowable delay is nearly onesecond (since calculations overflow for longer delays), the suggested maximumvalue for udelay is 1000 microseconds (one millisecond). The function mdelayhelps in cases where the delay must be longer than one millisecond.It’s also important to remember that udelay is a busy-waiting function (and thusmdelay is too); other tasks can’t be run during the time lapse.

You must thereforebe very careful, especially with mdelay, and avoid using it unless there’s no otherway to meet your goal.Currently, support for delays longer than a few microseconds and shorter than atimer tick is very inefficient. This is not usually an issue, because delays need tobe just long enough to be noticed by humans or by the hardware. One hundredthof a second is a suitable precision for human-related time intervals, while one millisecond is a long enough delay for hardware activities.Although mdelay is not available in Linux 2.0, sysdep.h fills the gap.Task QueuesOne feature many drivers need is the ability to schedule execution of some tasksat a later time without resorting to interrupts.

Linux offers three different interfacesfor this purpose: task queues, tasklets (as of kernel 2.3.43), and kernel timers. Taskqueues and tasklets provide a flexible utility for scheduling execution at a latertime, with various meanings for ‘‘later’’; they are most useful when writing interrupt handlers, and we’ll see them again in “Tasklets and Bottom-Half Processing,”in Chapter 9. Kernel timers are used to schedule a task to run at a specific time inthe future and are dealt with in “Kernel Timers,” later in this chapter.A typical situation in which you might use task queues or tasklets is to managehardware that cannot generate interrupts but still allows blocking read.

You needto poll the device, while taking care not to burden the CPU with unnecessaryoperations. Waking the reading process at fixed time intervals (for example, usingcurrent->timeout) isn’t a suitable approach, because each poll would requiretwo context switches (one to run the polling code in the reading process, and oneto return to a process that has real work to do), and often a suitable polling mechanism can be implemented only outside of a process’s context.A similar problem is giving timely input to a simple hardware device.

For example,you might need to feed steps to a stepper motor that is directly connected to theparallel port—the motor needs to be moved by single steps on a timely basis. Inthis case, the controlling process talks to your device driver to dispatch a movement, but the actual movement should be performed step by step at regular intervals after returning from write.18922 June 2001 16:37http://openlib.org.uaChapter 6: Flow of TimeThe preferred way to perform such floating operations quickly is to register a taskfor later execution.

The kernel supports task queues, where tasks accumulate to be‘‘consumed’’ when the queue is run. You can declare your own task queue andtrigger it at will, or you can register your tasks in predefined queues, which arerun (triggered) by the kernel itself.This section first describes task queues, then introduces predefined task queues,which provide a good start for some interesting tests (and hang the computer ifsomething goes wrong), and finally introduces how to run your own task queues.Following that, we look at the new tasklet interface, which supersedes task queuesin many situations in the 2.4 kernel.The Nature of Task QueuesA task queue is a list of tasks, each task being represented by a function pointerand an argument.

When a task is run, it receives a single void * argument andreturns void. The pointer argument can be used to pass along a data structure tothe routine, or it can be ignored. The queue itself is a list of structures (the tasks)that are owned by the kernel module declaring and queueing them. The module iscompletely responsible for allocating and deallocating the structures, and staticstructures are commonly used for this purpose.A queue element is described by the following structure, copied directly from<linux/tqueue.h>:struct tq_struct {struct tq_struct *next;int sync;void (*routine)(void *);void *data;};/*/*/*/*linked list of active bh’s */must be initialized to zero */function to call */argument to function */The ‘‘bh’’ in the first comment means bottom half.

A bottom half is ‘‘half of aninterrupt handler’’; we’ll discuss this topic thoroughly when we deal with interrupts in “Tasklets and Bottom-Half Processing,” in Chapter 9. For now, suffice it tosay that a bottom half is a mechanism provided by a device driver to handle asynchronous tasks which, usually, are too large to be done while handling a hardwareinterrupt.

This chapter should make sense without an understanding of bottomhalves, but we will, by necessity, refer to them occasionally.The most important fields in the data structure just shown are routine anddata. To queue a task for later execution, you need to set both these fields beforequeueing the structure, while next and sync should be cleared. The sync flagin the structure is used by the kernel to prevent queueing the same task more thanonce, because this would corrupt the next pointer. Once the task has beenqueued, the structure is considered ‘‘owned’’ by the kernel and shouldn’t bemodified until the task is run.19022 June 2001 16:37http://openlib.org.uaTask QueuesThe other data structure involved in task queues is task_queue, which is currently just a pointer to struct tq_struct; the decision to typedef thispointer to another symbol permits the extension of task_queue in the future,should the need arise.

task_queue pointers should be initialized to NULL beforeuse.The following list summarizes the operations that can be performed on taskqueues and struct tq_structs.DECLARE_TASK_QUEUE(name);This macro declares a task queue with the given name, and initializes it to theempty state.int queue_task(struct tq_struct *task, task_queue *list);As its name suggests, this function queues a task. The return value is 0 if thetask was already present on the given queue, nonzero otherwise.void run_task_queue(task_queue *list);This function is used to consume a queue of accumulated tasks. You won’tneed to call it yourself unless you declare and maintain your own queue.Before getting into the details of using task queues, we need to pause for amoment to look at how they work inside the kernel.How Task Queues Are RunA task queue, as we have already seen, is in practice a linked list of functions tocall.

When run_task_queue is asked to run a given queue, each entry in the list isexecuted. When you are writing functions that work with task queues, you have tokeep in mind when the kernel will call run_task_queue; the exact context imposessome constraints on what you can do. You should also not make any assumptionsregarding the order in which enqueued tasks are run; each of them must do itstask independently of the other ones.And when are task queues run? If you are using one of the predefined task queuesdiscussed in the next section, the answer is ‘‘when the kernel gets around to it.’’Different queues are run at different times, but they are always run when the kernel has no other pressing work to do.Most important, they almost certainly are not run when the process that queuedthe task is executing. They are, instead, run asynchronously. Until now, everythingwe have done in our sample drivers has run in the context of a process executingsystem calls.

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

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

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

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