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

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

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

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

In the 2.0 and 2.2 kernels, there was no central facility for the allocation of memory resources. You can use the macros anyway if you includesysdep.h because it nullifies the three macros when compiling for 2.0 or 2.2.24822 June 2001 16:39http://openlib.org.uaQuick ReferenceQuick ReferenceThis chapter introduced the following symbols related to hardware management.#include <linux/kernel.h>void barrier(void)This ‘‘software’’ memory barrier requests the compiler to consider all memoryvolatile across this instruction.#include <asm/system.h>void rmb(void);void wmb(void);void mb(void);Hardware memory barriers. They request the CPU (and the compiler) tocheckpoint all memory reads, writes, or both, across this instruction.#include <asm/io.h>unsigned inb(unsigned port);void outb(unsigned char byte, unsigned port);unsigned inw(unsigned port);void outw(unsigned short word, unsigned port);unsigned inl(unsigned port);void outl(unsigned doubleword, unsigned port);These functions are used to read and write I/O ports.

They can also be calledby user-space programs, provided they have the right privileges to accessports.unsigned inb_p(unsigned port);...The statement SLOW_DOWN_IO is sometimes needed to deal with slow ISAboards on the x86 platform. If a small delay is needed after an I/O operation,you can use the six pausing counterparts of the functions introduced in theprevious entry; these pausing functions have names ending in _p.void insb(unsigned port, void *addr, unsigned long count);void outsb(unsigned port, void *addr, unsigned long count);void insw(unsigned port, void *addr, unsigned long count);void outsw(unsigned port, void *addr, unsigned long count);void insl(unsigned port, void *addr, unsigned long count);void outsl(unsigned port, void *addr, unsigned long count);The ‘‘string functions’’ are optimized to transfer data from an input port to aregion of memory, or the other way around.

Such transfers are performed byreading or writing the same port count times.24922 June 2001 16:39http://openlib.org.uaChapter 8: Hardware Management#include <linux/ioport.h>int check_region(unsigned long start, unsigned long len);void request_region(unsigned long start, unsigned long len,char *name);void release_region(unsigned long start, unsigned long len);Resource allocators for I/O ports. The check function returns 0 for success andless than 0 in case of error.int check_mem_region(unsigned long start, unsigned longlen);void request_mem_region(unsigned long start, unsigned longlen, char *name);void release_mem_region(unsigned long start, unsigned longlen);These functions handle resource allocation for memory regions.#include <asm/io.h>void *ioremap(unsigned long phys_addr, unsigned long size);void *ioremap_nocache(unsigned long phys_addr, unsigned longsize);void iounmap(void *virt_addr);ior emap remaps a physical address range into the processor’s virtual addressspace, making it available to the kernel.

iounmap frees the mapping when itis no longer needed.#include <linux/io.h>unsigned readb(address);unsigned readw(address);unsigned readl(address);void writeb(unsigned value, address);void writew(unsigned value, address);void writel(unsigned value, address);memset_io(address, value, count);memcpy_fromio(dest, source, nbytes);memcpy_toio(dest, source, nbytes);These functions are used to access I/O memory regions, either low ISA memory or high PCI buffers.25022 June 2001 16:39http://openlib.org.uaCHAPTER NINEINTERRUPT HANDLINGAlthough some devices can be controlled using nothing but their I/O regions,most real-world devices are a bit more complicated than that.

Devices have to dealwith the external world, which often includes things such as spinning disks, moving tape, wires to distant places, and so on. Much has to be done in a time framethat is different, and slower, than that of the processor. Since it is almost alwaysundesirable to have the processor wait on external events, there must be a way fora device to let the processor know when something has happened.That way, of course, is interrupts.

An interrupt is simply a signal that the hardwarecan send when it wants the processor’s attention. Linux handles interrupts in muchthe same way that it handles signals in user space. For the most part, a driver needonly register a handler for its device’s interrupts, and handle them properly whenthey arrive.

Of course, underneath that simple picture there is some complexity; inparticular, interrupt handlers are somewhat limited in the actions they can performas a result of how they are run.It is difficult to demonstrate the use of interrupts without a real hardware device togenerate them. Thus, the sample code used in this chapter works with the parallelport.

We’ll be working with the short module from the previous chapter; withsome small additions it can generate and handle interrupts from the parallel port.The module’s name, short, actually means short int (it is C, isn’t it?), to remind usthat it handles interrupts.Overall Control of InterruptsThe way that Linux handles interrupts has changed quite a bit over the years, dueto changes in design and in the hardware it works with. The PC’s view of interrupts in the early days was quite simple; there were just 16 interrupt lines and one25122 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt Handlingprocessor to deal with them.

Modern hardware can have many more interrupts,and can also be equipped with fancy advanced programmable interrupt controllers(APICs), which can distribute interrupts across multiple processors in an intelligent(and programmable) way.Happily, Linux has been able to deal with all of these changes with relatively fewincompatibilities at the driver level. Thus, the interface described in this chapterworks, with few differences, across many kernel versions. Sometimes things dowork out nicely.Unix-like systems have used the functions cli and sti to disable and enable interrupts for many years.

In modern Linux systems, however, using them directly isdiscouraged. It is increasingly impossible for any routine to know whether interrupts are enabled when it is called; thus, simply enabling interrupts with sti beforereturn is a bad practice. Your function may be returning to a function that expectsinterrupts to be still disabled.Thus, if you must disable interrupts, it is better to use the following calls:unsigned long flags;save_flags(flags);cli();/* This code runs with interrupts disabled */restore_flags(flags);Note that save_flags is a macro, and that it is passed the variable to hold the flagsdirectly—without an & operator.

There is also an important constraint on the useof these macros: save_flags and restor e_flags must be called from the same function. In other words, you cannot pass the flags to another function, unless theother function is inlined. Code that ignores this restriction will work on somearchitectures but will fail on others.Increasingly, however, even code like the previous example is discouraged wherever possible. In a multiprocessor system, critical code cannot be protected just bydisabling interrupts; some sort of locking mechanism must be used.

Functionssuch as spin_lock_irqsave (covered in “Using Spinlocks,” later in this chapter) provide locking and interrupt control together; these functions are the only really safeway to control concurrency in the presence of interrupts.cli, meanwhile, disables interrupts on all processors on the system, and can thusaffect the performance of the system as a whole.** The truth is just a little more complicated than this. If you are already handling an interrupt, cli only disables interrupts on the current CPU.25222 June 2001 16:39http://openlib.org.uaInstalling an Interrupt HandlerThus, explicit calls to cli and related functions are slowly disappearing from muchof the kernel. There are occasions where you need them in a device driver, butthey are rare.

Before calling cli, think about whether you really need to disable allinterrupts on the system.Preparing the Parallel PortAlthough the parallel interface is simple, it can trigger interrupts. This capability isused by the printer to notify the lp driver that it is ready to accept the next character in the buffer.Like most devices, the parallel port doesn’t actually generate interrupts before it’sinstructed to do so; the parallel standard states that setting bit 4 of port 2 (0x37a,0x27a, or whatever) enables interrupt reporting.

A simple outb call to set the bitis performed by short at module initialization.Once interrupts are enabled, the parallel interface generates an interrupt wheneverthe electrical signal at pin 10 (the so-called ACK bit) changes from low to high.The simplest way to force the interface to generate interrupts (short of hooking upa printer to the port) is to connect pins 9 and 10 of the parallel connector. A shortlength of wire inserted into the appropriate holes in the parallel port connector onthe back of your system will create this connection. The pinout of the parallel portis shown in Figure 8-1.Pin 9 is the most significant bit of the parallel data byte.

If you write binary data to/dev/short0, you’ll generate several interrupts. Writing ASCII text to the port won’tgenerate interrupts, though, because the most significant bit won’t be set.If you’d rather avoid soldering, but you do have a printer at hand, you can run thesample interrupt handler using a real printer, as shown later. Note, however, thatthe probing functions we are going to introduce depend on the jumper betweenpin 9 and 10 being in place, and you’ll need it to experiment with probing usingour code.Installing an Interrupt HandlerIf you want to actually ‘‘see’’ interrupts being generated, writing to the hardwaredevice isn’t enough; a software handler must be configured in the system.

If theLinux kernel hasn’t been told to expect your interrupt, it will simply acknowledgeand ignore it.Interrupt lines are a precious and often limited resource, particularly when thereare only 15 or 16 of them. The kernel keeps a registry of interrupt lines, similar tothe registry of I/O ports. A module is expected to request an interrupt channel (orIRQ, for interrupt request) before using it, and to release it when it’s done.

In25322 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt Handlingmany situations, modules are also expected to be able to share interrupt lines withother drivers, as we will see. The following functions, declared in<linux/sched.h>, implement the interface:int request_irq(unsigned int irq,void (*handler)(int, void *, struct pt_regs *),unsigned long flags,const char *dev_name,void *dev_id);void free_irq(unsigned int irq, void *dev_id);The value returned from request_irq to the requesting function is either 0 to indicate success or a negative error code, as usual.

It’s not uncommon for the functionto return -EBUSY to signal that another driver is already using the requested interrupt line. The arguments to the functions are as follows:unsigned int irqThis is the interrupt number being requested.void (*handler)(int, void *, struct pt_regs *)The pointer to the handling function being installed. We’ll discuss the arguments to this function later in this chapter.unsigned long flagsAs you might expect, a bit mask of options (described later) related to interrupt management.const char *dev_nameThe string passed to request_irq is used in /pr oc/interrupts to show the ownerof the interrupt (see the next section).void *dev_idThis pointer is used for shared interrupt lines. It is a unique identifier that isused when the interrupt line is freed and that may also be used by the driverto point to its own private data area (to identify which device is interrupting).When no sharing is in force, dev_id can be set to NULL, but it a good ideaanyway to use this item to point to the device structure.

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

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

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

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