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

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

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

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

Thefunction that this BH executes is the one that drives the kernel timers. There isno way to use this facility for a driver short of using add_timer.27222 June 2001 16:39http://openlib.org.uaTasklets and Bottom-Half ProcessingThe remaining BH bottom halves are used by specific kernel drivers. There are noentry points in them for a module, and it wouldn’t make sense for there to be any.The list of these other bottom halves is steadily shrinking as the drivers are converted to using tasklets.Once a BH has been marked, it is executed when bh_action (ker nel/softirq.c) isinvoked, which happens when tasklets are run. This happens whenever a processexits from a system call or when an interrupt handler exits. Tasklets are alwaysexecuted as part of the timer interrupt, so a driver can usually expect that a bottom-half routine will be executed at most 10 ms after it has been scheduled.Writing a BH Bottom HalfIt’s quite apparent from the list of available bottom halves in “The BH Mechanism”that a driver implementing a bottom half should attach its code to IMMEDIATE_BHby using the immediate queue.When IMMEDIATE_BH is marked, the function in charge of the immediate bottomhalf just consumes the immediate queue.

If your interrupt handler queues its BHhandler to tq_immediate and marks the IMMEDIATE_BH bottom half, thequeued task will be called at just the right time. Because in all kernels we areinterested in you can queue the same task multiple times without trashing the taskqueue, you can queue your bottom half every time the top-half handler runs. We’llsee this behavior in a while.Drivers with exotic configurations—multiple bottom halves or other setups thatcan’t easily be handled with a plain tq_immediate—can be satisfied by using acustom task queue.

The interrupt handler queues the tasks in its own queue, andwhen it’s ready to run them, a simple queue-consuming function is inserted intothe immediate queue. See “Running Your Own Task Queues” in Chapter 6 fordetails.Let’s now look at the short BH implementation. When loaded with bh=1, themodule installs an interrupt handler that uses a BH bottom half:void short_bh_interrupt(int irq, void *dev_id, struct pt_regs *regs){/* cast to stop ’volatile’ warning */do_gettimeofday((struct timeval *) tv_head);short_incr_tv(&tv_head);/* Queue the bh. Don’t care about multiple enqueueing */queue_task(&short_task, &tq_immediate);mark_bh(IMMEDIATE_BH);short_bh_count++; /* record that an interrupt arrived */}27322 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt HandlingAs expected, this code calls queue_task without checking whether the task isalready enqueued.The BH, then, performs the rest of the work.

This BH is, in fact, the sameshort_do_tasklet that was shown previuosly.Here’s an example of what you see when loading short by specifying bh=1:morgana% echo 1122334455 > /dev/shortint ; cat /dev/shortintbh after550588804.87665350588804.87669350588804.87672050588804.87674750588804.876774The actual timings that you will see will vary, of course, depending on your particular system.Interrupt SharingThe notion of an IRQ conflict is almost synonymous with the PC architecture. Ingeneral, IRQ lines on the PC have not been able to serve more than one device,and there have never been enough of them.

As a result, frustrated users have oftenspent much time with their computer case open, trying to find a way to make allof their hardware play well together.But, in fact, there is nothing in the design of the hardware itself that says thatinterrupt lines cannot be shared. The problems are on the software side. With thearrival of the PCI bus, the writers of system software have had to work a littleharder, since all PCI interrupts can explicitly be shared. So Linux supports sharedinterrupts — and on all buses where it makes any sense, not just the PCI. Thus,suitably aware drivers for ISA devices can also share an IRQ line.The question of interrupt sharing under the ISA bus brings in the issue of leveltriggered versus edge-triggered interrupt lines.

Although the former kind of interrupt reporting is safe with regard to sharing, it may lead to software lockup if nothandled correctly. Edge-triggered interrupts, on the other hand, are not safe withregard to sharing; ISA is edge triggered, because this signaling is easier to implement at hardware level and therefore was the common choice in the 1980s. Thisissue is unrelated to electrical signal levels; in order to support sharing, the linemust be able to be driven active by multiple sources whether it is level triggeredor edge triggered.With a level-triggered interrupt line, the peripheral device asserts the IRQ signaluntil software clears the pending interrupt (usually by writing to a device register);therefore, if several devices pull the line active, the CPU will signal an interrupt as27422 June 2001 16:39http://openlib.org.uaInterrupt Sharingsoon as the IRQ is enabled until all drivers have serviced their devices.

Thisbehavior is safe with regard to sharing but may lead to lockup if a driver fails toclear its interrupt source.When using edge-triggered interrupts, on the other hand, interrupts may be lost: ifone device pulls the line active for too long a time, when another device pulls theline active no edge will be generated, and the processor will ignore the secondrequest. A shared handler may just not see the interrupt, and if its hardwaredoesn’t deassert the IRQ line no other interrupt will be notified for either shareddevice.For this reason, even if interrupt sharing is supported under ISA, it may not function properly; while some devices pull the IRQ line active for a single clock cycle,other devices are not so well behaved and may cause great pains to the driverwriter who tries to share the IRQ.

We won’t go any deeper into this issue; for therest of this section we assume that either the host bus supports sharing or that youknow what you are doing.To develop a driver that can manage a shared interrupt line, some details need tobe considered. As discussed later, some of the features described in this chapterare not available for devices using interrupt sharing. Whenever possible, it’s betterto support sharing because it presents fewer problems for the final user.

In somecases (e.g., when working with the PCI bus), interrupt sharing is mandatory.Installing a Shared HandlerShared interrupts are installed through request_irq just like nonshared ones, butthere are two differences:•The SA_SHIRQ bit must be specified in the flags argument when requestingthe interrupt.•The dev_id argument must be unique. Any pointer into the module’s addressspace will do, but dev_id definitely cannot be set to NULL.The kernel keeps a list of shared handlers associated with the interrupt, like adriver’s signature, and dev_id differentiates between them. If two drivers were toregister NULL as their signature on the same interrupt, things might get mixed upat unload time, causing the kernel to oops when an interrupt arrived.

For this reason, modern kernels will complain loudly if passed a NULL dev_id when registering shared interrupts.When a shared interrupt is requested, request_irq succeeds if either the interruptline is free or any handlers already registered for that line have also specified thatthe IRQ is to be shared. With 2.0 kernels, it was also necessary that all handlers fora shared interrupt were either fast or slow—the two modes could not be mixed.27522 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt HandlingWhenever two or more drivers are sharing an interrupt line and the hardwareinterrupts the processor on that line, the kernel invokes every handler registeredfor that interrupt, passing each its own dev_id.

Therefore, a shared handler mustbe able to recognize its own interrupts, and should quickly exit when its owndevice has not interrupted.If you need to probe for your device before requesting the IRQ line, the kernelcan’t help you. No probing function is available for shared handlers. The standardprobing mechanism works if the line being used is free, but if the line is alreadyheld by another driver with sharing capabilities, the probe will fail, even if yourdriver would have worked perfectly.The only available technique for probing shared lines, then, is the do-it-yourselfway. The driver should request every possible IRQ line as a shared handler andthen see where interrupts are reported.

The difference between that and do-ityourself probing is that the probing handler must check with the device to see thatthe interrupt actually occurred, because it could have been called in response toanother device interrupting on a shared line.Releasing the handler is performed in the normal way, using release_irq. Here thedev_id argument is used to select the correct handler to release from the list ofshared handlers for the interrupt. That’s why the dev_id pointer must be unique.A driver using a shared handler needs to be careful about one more thing: it can’tplay with enable_irq or disable_irq. If it does, things might go haywire for otherdevices sharing the line. In general, the programmer must remember that hisdriver doesn’t own the IRQ, and its behavior should be more ‘‘social’’ than is necessary if one owns the interrupt line.Running the HandlerAs suggested earlier, when the kernel receives an interrupt, all the registered handlers are invoked.

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

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

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

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