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

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

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

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

You register your function once, and the kernel callsit once when the timer expires. Such a functionality is used often within the kernelproper, but it is sometimes needed by the drivers as well, as in the example of thefloppy motor.The kernel timers are organized in a doubly linked list. This means that you cancreate as many timers as you want. A timer is characterized by its timeout value (injiffies) and the function to be called when the timer expires.

The timer handlerreceives an argument, which is stored in the data structure, together with a pointerto the handler itself.The data structure of a timer looks like the following, which is extracted from<linux/timer.h>):struct timer_list {struct timer_list *next;struct timer_list *prev;unsigned long expires;unsigned long data;void (*function)(unsigned long);volatile int running;};/*/*/*/*/*/*never touch this */never touch this */the timeout, in jiffies */argument to the handler */handler of the timeout */added in 2.4; don’t touch */The timeout of a timer is a value in jiffies. Thus, timer->function will runwhen jiffies is equal to or greater than timer->expires. The timeout is anabsolute value; it is usually generated by taking the current value of jiffies andadding the amount of the desired delay.Once a timer_list structure is initialized, add_timer inserts it into a sorted list,which is then polled more or less 100 times per second.

Even systems (such as theAlpha) that run with a higher clock interrupt frequency do not check the timer listmore often than that; the added timer resolution would not justify the cost of theextra passes through the list.These are the functions used to act on timers:void init_timer(struct timer_list *timer);This inline function is used to initialize the timer structure. Currently, it zerosthe prev and next pointers (and the running flag on SMP systems). Programmers are strongly urged to use this function to initialize a timer and tonever explicitly touch the pointers in the structure, in order to be forwardcompatible.20122 June 2001 16:37http://openlib.org.uaChapter 6: Flow of Timevoid add_timer(struct timer_list *timer);This function inserts a timer into the global list of active timers.int mod_timer(struct timer_list *timer, unsigned longexpires);Should you need to change the time at which a timer expires, mod_timer canbe used.

After the call, the new expires value will be used.int del_timer(struct timer_list *timer);If a timer needs to be removed from the list before it expires, del_timer shouldbe called. When a timer expires, on the other hand, it is automaticallyremoved from the list.int del_timer_sync(struct timer_list *timer);This function works like del_timer, but it also guarantees that, when it returns,the timer function is not running on any CPU. del_timer_sync is used to avoidrace conditions when a timer function is running at unexpected times; itshould be used in most situations. The caller of del_timer_sync must ensurethat the timer function will not use add_timer to add itself again.An example of timer usage can be seen in the jiq module. The file /pr oc/jitimeruses a timer to generate two data lines; it uses the same printing function as thetask queue examples do.

The first data line is generated from the read call(invoked by the user process looking at /pr oc/jitimer), while the second line isprinted by the timer function after one second has elapsed.The code for /pr oc/jitimer is as follows:struct timer_list jiq_timer;void jiq_timedout(unsigned long ptr){jiq_print((void *)ptr);wake_up_interruptible(&jiq_wait);}/* print a line *//* awaken the process */int jiq_read_run_timer(char *buf, char **start, off_t offset,int len, int *eof, void *data){jiq_data.len = 0;/* prepare the argument for jiq_print() */jiq_data.buf = buf;jiq_data.jiffies = jiffies;jiq_data.queue = NULL;/* don’t requeue */init_timer(&jiq_timer);/* init the timer structure */jiq_timer.function = jiq_timedout;jiq_timer.data = (unsigned long)&jiq_data;jiq_timer.expires = jiffies + HZ; /* one second */20222 June 2001 16:37http://openlib.org.uaKernel Timersjiq_print(&jiq_data);/* print and go to sleep */add_timer(&jiq_timer);interruptible_sleep_on(&jiq_wait);del_timer_sync(&jiq_timer); /* in case a signal woke us up */*eof = 1;return jiq_data.len;}Running head /proc/jitimer gives the following output:time delta interrupt pid cpu command455845820089200 head45584682 100101 swapperFrom the output you can see that the timer function, which printed the last linehere, was running in interrupt mode.What can appear strange when using timers is that the timer expires at just theright time, even if the processor is executing in a system call.

We suggested earlierthat when a process is running in kernel space, it won’t be scheduled away; theclock tick, however, is special, and it does all of its tasks independent of the current process. You can try to look at what happens when you read /pr oc/jitbusy inthe background and /pr oc/jitimer in the foreground.

Although the system appearsto be locked solid by the busy-waiting system call, both the timer queue and thekernel timers continue running.Thus, timers can be another source of race conditions, even on uniprocessor systems. Any data structures accessed by the timer function should be protected fromconcurrent access, either by being atomic types (discussed in Chapter 10) or byusing spinlocks.One must also be very careful to avoid race conditions with timer deletion. Consider a situation in which a module’s timer function is run on one processor whilea related event (a file is closed or the module is removed) happens on another.The result could be the timer function expecting a situation that is no longer valid,resulting in a system crash.

To avoid this kind of race, your module should usedel_timer_sync instead of del_timer. If the timer function can restart the timer itself(a common pattern), you should also have a ‘‘stop timer’’ flag that you set beforecalling del_timer_sync. The timer function should then check that flag and notreschedule itself with add_timer if the flag has been set.Another pattern that can cause race conditions is modifying timers by deletingthem with del_timer, then creating a new one with add_timer.

It is better, in thissituation, to simply use mod_timer to make the necessary change.20322 June 2001 16:37http://openlib.org.uaChapter 6: Flow of TimeBackward CompatibilityTask queues and timing issues have remained relatively constant over the years.Nonetheless, a few things have changed and must be kept in mind.The functions sleep_on_timeout, interruptible_sleep_on_timeout, and schedule_timeout were all added for the 2.2 kernel. In the 2.0 days, timeouts were handled with a variable (called timeout) in the task structure.

As a result, code thatnow makes a call likeinterruptible_sleep_on_timeout(my_queue, timeout);used to be implemented ascurrent->timeout = jiffies + timeout;interruptible_sleep_on(my_queue);The sysdep.h header recreates schedule_timeout for pre-2.4 kernels so that you canuse the new syntax and run on 2.0 and 2.2:extern inline void schedule_timeout(int timeout){current->timeout = jiffies + timeout;current->state = TASK_INTERRUPTIBLE;schedule();current->timeout = 0;}In 2.0, there were a couple of additional functions for putting functions into taskqueues.

queue_task_irq could be called instead of queue_task in situations inwhich interrupts were disabled, yielding a (very) small performance benefit.queue_task_irq_off is even faster, but does not function properly in situations inwhich the task is already queued or is running, and can thus only be used wherethose conditions are guaranteed not to occur. Neither of these two functions provided much in the way of performance benefits, and they were removed in kernel2.1.30.

Using queue_task in all cases works with all kernel versions. (It is worthnoting, though, that queue_task had a return type of void in 2.2 and prior kernels.)Prior to 2.4, the schedule_task function and associated keventd process did notexist. Instead, another predefined task queue, tq_scheduler, was provided.Tasks placed in tq_scheduler were run in the schedule function, and thusalways ran in process context. The actual process whose context would be usedwas always different, however; it was whatever process was being scheduled onthe CPU at the time. tq_scheduler typically had larger latencies, especially fortasks that resubmitted themselves. sysdep.h provides the following implementationfor schedule_task on 2.0 and 2.2 systems:20422 June 2001 16:37http://openlib.org.uaQuick Referenceextern inline int schedule_task(struct tq_struct *task){queue_task(task, &tq_scheduler);return 1;}As has been mentioned, the 2.3 development series added the tasklet mechanism;before, only task queues were available for ‘‘immediate deferred’’ execution.

Thebottom-half subsystem was implemented differently, though most of the changesare not visible to driver writers. We didn’t emulate tasklets for older kernels in sysdep.h because they are not strictly needed for driver operation; if you want to bebackward compatible you’ll need to either write your own emulation or use taskqueues instead.The in_interrupt function did not exist in Linux 2.0. Instead, a global variableintr_count kept track of the number of interrupt handlers running.

Queryingintr_count is semantically the same as calling in_interrupt, so compatibility iseasily implemented in sysdep.h.The del_timer_sync function did not exist prior to development kernel 2.4.0-test2.The usual sysdep.h header defines a minimal replacement when you build againstolder kernel headers. Kernel version 2.0 didn’t have mod_timer, either.

This gap isalso filled by our compatibility header.Quick ReferenceThis chapter introduced the following symbols:#include <linux/param.h>HZ The HZ symbol specifies the number of clock ticks generated per second.#include <linux/sched.h>volatile unsigned long jiffiesThe jiffies variable is incremented once for each clock tick; thus, it’s incremented HZ times per second.#include <asm/msr.h>rdtsc(low,high);rdtscl(low);Read the timestamp counter or its lower half.

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

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

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

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