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

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

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

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

The facility consists of two functions, declared in<linux/interrupt.h> (which also describes the probing machinery):unsigned long probe_irq_on(void);This function returns a bit mask of unassigned interrupts. The driver must preserve the returned bit mask and pass it to pr obe_irq_off later. After this call,the driver should arrange for its device to generate at least one interrupt.int probe_irq_off(unsigned long);After the device has requested an interrupt, the driver calls this function, passing as argument the bit mask previously returned by pr obe_irq_on.pr obe_irq_off returns the number of the interrupt that was issued after‘‘probe_on.’’ If no interrupts occurred, 0 is returned (thus, IRQ 0 can’t beprobed for, but no custom device can use it on any of the supported architectures anyway).

If more than one interrupt occurred (ambiguous detection),pr obe_irq_off returns a negative value.The programmer should be careful to enable interrupts on the device after the callto pr obe_irq_on and to disable them befor e calling pr obe_irq_off, Additionally, youmust remember to service the pending interrupt in your device after pr obe_irq_off.The short module demonstrates how to use such probing. If you load the modulewith probe=1, the following code is executed to detect your interrupt line, provided pins 9 and 10 of the parallel connector are bound together:int count = 0;do {unsigned long mask;mask = probe_irq_on();outb_p(0x10,short_base+2);outb_p(0x00,short_base);outb_p(0xFF,short_base);outb_p(0x00,short_base+2);/*/*/*/*enable reporting */clear the bit */set the bit: interrupt! */disable reporting */25922 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt Handlingudelay(5); /* give it some time */short_irq = probe_irq_off(mask);if (short_irq == 0) { /* none of them? */printk(KERN_INFO "short: no irq reported by probe\n");short_irq = -1;}/** If more than one line has been activated, the result is* negative.

We should service the interrupt (no need for lpt port)* and loop over again. Loop at most five times, then give up*/} while (short_irq < 0 && count++ < 5);if (short_irq < 0)printk("short: probe failed %i times, giving up\n", count);Note the use of udelay before calling pr obe_irq_off. Depending on the speed ofyour processor, you may have to wait for a brief period to give the interrupt timeto actually be delivered.If you dig through the kernel sources, you may stumble across references to a different pair of functions:void autoirq_setup(int waittime);Set up for an IRQ probe.

The waittime argument is not used.int autoirq_report(int waittime);Delays for the given interval (in jiffies), then returns the number of the IRQseen since autoirq_setup was called.These functions are used primarily in the network driver code, for historical reasons. They are currently implemented with pr obe_irq_on and pr obe_irq_off; thereis not usually any reason to use the autoirq_ functions over the pr obe_irq_ functions.Probing might be a lengthy task. While this is not true for short, probing a framegrabber, for example, requires a delay of at least 20 ms (which is ages for the processor), and other devices might take even longer.

Therefore, it’s best to probe forthe interrupt line only once, at module initialization, independently of whetheryou install the handler at device open (as you should) or within the initializationfunction (which is not recommended).It’s interesting to note that on some platforms (PowerPC, M68k, most MIPS implementations, and both SPARC versions), probing is unnecessary and therefore theprevious functions are just empty placeholders, sometimes called ‘‘useless ISA nonsense.’’ On other platforms, probing is only implemented for ISA devices.

Anyway,most architectures define the functions (even if empty) to ease porting existingdevice drivers.Generally speaking, probing is a hack, and mature architectures are like the PCIbus, which provides all the needed information.26022 June 2001 16:39http://openlib.org.uaInstalling an Interrupt HandlerDo-it-yourself probingProbing can be implemented in the driver itself without too much trouble.

Theshort module performs do-it-yourself detection of the IRQ line if it is loaded withprobe=2.The mechanism is the same as the one described earlier: enable all unused interrupts, then wait and see what happens. We can, however, exploit our knowledgeof the device. Often a device can be configured to use one IRQ number from a setof three or four; probing just those IRQs enables us to detect the right one, without having to test for all possible IRQs.The short implementation assumes that 3, 5, 7, and 9 are the only possible IRQvalues. These numbers are actually the values that some parallel devices allow youto select.The following code probes by testing all ‘‘possible’’ interrupts and looking at whathappens.

The trials array lists the IRQs to try and has 0 as the end marker; thetried array is used to keep track of which handlers have actually been registeredby this driver.int trials[] = {3, 5, 7, 9, 0};int tried[] = {0, 0, 0, 0, 0};int i, count = 0;/** Install the probing handler for all possible lines. Remember* the result (0 for success, or -EBUSY) in order to only free* what has been acquired*/for (i=0; trials[i]; i++)tried[i] = request_irq(trials[i], short_probing,SA_INTERRUPT, "short probe", NULL);do {short_irq = 0; /* none obtained yet */outb_p(0x10,short_base+2); /* enable */outb_p(0x00,short_base);outb_p(0xFF,short_base); /* toggle the bit */outb_p(0x00,short_base+2); /* disable */udelay(5); /* give it some time *//* the value has been set by the handler */if (short_irq == 0) { /* none of them? */printk(KERN_INFO "short: no irq reported by probe\n");}/** If more than one line has been activated, the result is* negative.

We should service the interrupt (but the lpt port* doesn’t need it) and loop over again. Do it at most 5 times*/26122 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt Handling} while (short_irq <=0 && count++ < 5);/* end of loop, uninstall the handler */for (i=0; trials[i]; i++)if (tried[i] == 0)free_irq(trials[i], NULL);if (short_irq < 0)printk("short: probe failed %i times, giving up\n", count);You might not know in advance what the ‘‘possible’’ IRQ values are. In that case,you’ll need to probe all the free interrupts, instead of limiting yourself to a fewtrials[]. To probe for all interrupts, you have to probe from IRQ 0 to IRQNR_IRQS-1, where NR_IRQS is defined in <asm/irq.h> and is platform dependent.Now we are missing only the probing handler itself. The handler’s role is toupdate short_irq according to which interrupts are actually received.

A 0 valuein short_irq means ‘‘nothing yet,’’ while a negative value means ‘‘ambiguous.’’These values were chosen to be consistent with pr obe_irq_off and to allow thesame code to call either kind of probing within short.c.void short_probing(int irq, void *dev_id, struct pt_regs *regs){if (short_irq == 0) short_irq = irq;/* found */if (short_irq != irq) short_irq = -irq; /* ambiguous */}The arguments to the handler are described later. Knowing that irq is the interrupt being handled should be sufficient to understand the function just shown.Fast and Slow HandlersOlder versions of the Linux kernel took great pains to distinguish between ‘‘fast’’and ‘‘slow’’ interrupts. Fast interrupts were those that could be handled veryquickly, whereas handling slow interrupts took significantly longer.

Slow interruptscould be sufficiently demanding of the processor that it was worthwhile to reenable interrupts while they were being handled. Otherwise, tasks requiring quickattention could be delayed for too long.In modern kernels most of the differences between fast and slow interrupts havedisappeared. There remains only one: fast interrupts (those that were requestedwith the SA_INTERRUPT flag) are executed with all other interrupts disabled onthe current processor. Note that other processors can still handle interrupts, thoughyou will never see two processors handling the same IRQ at the same time.To summarize the slow and fast executing environments:26222 June 2001 16:39http://openlib.org.uaInstalling an Interrupt Handler•A fast handler runs with interrupt reporting disabled in the microprocessor,and the interrupt being serviced is disabled in the interrupt controller.

Thehandler can nonetheless enable reporting in the processor by calling sti.•A slow handler runs with interrupt reporting enabled in the processor, and theinterrupt being serviced is disabled in the interrupt controller.So, which type of interrupt should your driver use? On modern systems,SA_INTERRUPT is only intended for use in a few, specific situations (such astimer interrupts). Unless you have a strong reason to run your interrupt handlerwith other interrupts disabled, you should not use SA_INTERRUPT.This description should satisfy most readers, though someone with a taste forhardware and some experience with her computer might be interested in goingdeeper.

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

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

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

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