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

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

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

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

OnCISC processors, operations that take a significant amount of time can be executedconcurrently with other, quicker ones.These optimizations are transparent and benign when applied to conventionalmemory (at least on uniprocessor systems), but they can be fatal to correct I/Ooperations because they interfere with those ‘‘side effects’’ that are the main reason why a driver accesses I/O registers. The processor cannot anticipate a situation in which some other process (running on a separate processor, or somethinghappening inside an I/O controller) depends on the order of memory access. Adriver must therefore ensure that no caching is performed and no read or writereordering takes place when accessing registers: the compiler or the CPU may justtry to outsmart you and reorder the operations you request; the result can bestrange errors that are very difficult to debug.The problem with hardware caching is the easiest to face: the underlying hardwareis already configured (either automatically or by Linux initialization code) to disable any hardware cache when accessing I/O regions (whether they are memoryor port regions).The solution to compiler optimization and hardware reordering is to place a memory barrier between operations that must be visible to the hardware (or to anotherprocessor) in a particular order.

Linux provides four macros to cover all possibleordering needs.#include <linux/kernel.h>void barrier(void)This function tells the compiler to insert a memory barrier, but has no effecton the hardware. Compiled code will store to memory all values that are currently modified and resident in CPU registers, and will reread them later whenthey are needed.#include <asm/system.h>void rmb(void);void wmb(void);void mb(void);These functions insert hardware memory barriers in the compiled instructionflow; their actual instantiation is platform dependent. An rmb (read memorybarrier) guarantees that any reads appearing before the barrier are completedprior to the execution of any subsequent read.

wmb guarantees ordering inwrite operations, and the mb instruction guarantees both. Each of these functions is a superset of barrier.22822 June 2001 16:39http://openlib.org.uaUsing I/O PortsA typical usage of memory barriers in a device driver may have this sort of form:writel(dev->registers.addr, io_destination_address);writel(dev->registers.size, io_size);writel(dev->registers.operation, DEV_READ);wmb();writel(dev->registers.control, DEV_GO);In this case, it is important to be sure that all of the device registers controlling aparticular operation have been properly set prior to telling it to begin. The memory barrier will enforce the completion of the writes in the necessary order.Because memory barriers affect performance, they should only be used wherereally needed. The different types of barriers can also have different performancecharacteristics, so it is worthwhile to use the most specific type possible.

Forexample, on the x86 architecture, wmb( ) currently does nothing, since writes outside the processor are not reordered. Reads are reordered, however, so mb( ) willbe slower than wmb( ).It is worth noting that most of the other kernel primitives dealing with synchronization, such as spinlock and atomic_t operations, also function as memorybarriers.Some architectures allow the efficient combination of an assignment and a memory barrier. Version 2.4 of the kernel provides a few macros that perform this combination; in the default case they are defined as follows:#define set_mb(var, value) do {var = value; mb();} while 0#define set_wmb(var, value) do {var = value; wmb();} while 0#define set_rmb(var, value) do {var = value; rmb();} while 0Where appropriate, <asm/system.h> defines these macros to use architecturespecific instructions that accomplish the task more quickly.The header file sysdep.h defines macros described in this section for the platformsand the kernel versions that lack them.Using I/O PortsI/O ports are the means by which drivers communicate with many devices outthere—at least part of the time.

This section covers the various functions availablefor making use of I/O ports; we also touch on some portability issues.Let us start with a quick reminder that I/O ports must be allocated before beingused by your driver. As we discussed in “I/O Ports and I/O Memory” in Chapter 2,the functions used to allocate and free ports are:22922 June 2001 16:39http://openlib.org.uaChapter 8: Hardware Management#include <linux/ioport.h>int check_region(unsigned long start, unsigned long len);struct resource *request_region(unsigned long start,unsigned long len, char *name);void release_region(unsigned long start, unsigned long len);After a driver has requested the range of I/O ports it needs to use in its activities, itmust read and/or write to those ports. To this aim, most hardware differentiatesbetween 8-bit, 16-bit, and 32-bit ports.

Usually you can’t mix them like you normally do with system memory access.*A C program, therefore, must call different functions to access different size ports.As suggested in the previous section, computer architectures that support onlymemory-mapped I/O registers fake port I/O by remapping port addresses to memory addresses, and the kernel hides the details from the driver in order to easeportability. The Linux kernel headers (specifically, the architecture-dependentheader <asm/io.h>) define the following inline functions to access I/O ports.From now on, when we use unsigned without further type specifications, we are referring to an architecture-dependent definitionwhose exact nature is not relevant.

The functions are almost alwaysportable because the compiler automatically casts the values duringassignment — their being unsigned helps prevent compile-time warnings. No information is lost with such casts as long as the programmer assigns sensible values to avoid overflow. We’ll stick to thisconvention of ‘‘incomplete typing’’ for the rest of the chapter.unsigned inb(unsigned port);void outb(unsigned char byte, unsigned port);Read or write byte ports (eight bits wide). The port argument is defined asunsigned long for some platforms and unsigned short for others. Thereturn type of inb is also different across architectures.unsigned inw(unsigned port);void outw(unsigned short word, unsigned port);These functions access 16-bit ports (word wide); they are not available whencompiling for the M68k and S390 platforms, which support only byte I/O.* Sometimes I/O ports are arranged like memory, and you can (for example) bind two8-bit writes into a single 16-bit operation.

This applies, for instance, to PC video boards,but in general you can’t count on this feature.23022 June 2001 16:39http://openlib.org.uaUsing I/O Portsunsigned inl(unsigned port);void outl(unsigned longword, unsigned port);These functions access 32-bit ports. longword is either declared asunsigned long or unsigned int, according to the platform. Like wordI/O, ‘‘long’’ I/O is not available on M68k and S390.Note that no 64-bit port I/O operations are defined. Even on 64-bit architectures,the port address space uses a 32-bit (maximum) data path.The functions just described are primarily meant to be used by device drivers, butthey can also be used from user space, at least on PC-class computers.

The GNU Clibrary defines them in <sys/io.h>. The following conditions should apply inorder for inb and friends to be used in user-space code:•The program must be compiled with the -O option to force expansion ofinline functions.•The ioper m or iopl system calls must be used to get permission to perform I/Ooperations on ports. ioper m gets permission for individual ports, while ioplgets permission for the entire I/O space. Both these functions are Intel specific.•The program must run as root to invoke ioper m or iopl * Alternatively, one ofits ancestors must have gained port access running as root.If the host platform has no ioper m and no iopl system calls, user space can stillaccess I/O ports by using the /dev/port device file.

Note, though, that the meaningof the file is very platform specific, and most likely not useful for anything but thePC.The sample sources misc-pr ogs/inp.c and misc-pr ogs/outp.c are a minimal tool forreading and writing ports from the command line, in user space. They expect tobe installed under multiple names (i.e., inpb, inpw, and inpl and will manipulatebyte, word, or long ports depending on which name was invoked by the user.They use /dev/port if ioper m is not present.The programs can be made setuid root, if you want to live dangerously and playwith your hardware without acquiring explicit privileges.String OperationsIn addition to the single-shot in and out operations, some processors implementspecial instructions to transfer a sequence of bytes, words, or longs to and from asingle I/O port or the same size. These are the so-called string instructions, andthey perform the task more quickly than a C-language loop can do.

The following* Technically, it must have the CAP_SYS_RAWIO capability, but that is the same as runningas root on current systems.23122 June 2001 16:39http://openlib.org.uaChapter 8: Hardware Managementmacros implement the concept of string I/O by either using a single machineinstruction or by executing a tight loop if the target processor has no instructionthat performs string I/O. The macros are not defined at all when compiling for theM68k and S390 platforms. This should not be a portability problem, since theseplatforms don’t usually share device drivers with other platforms, because theirperipheral buses are different.The prototypes for string functions are the following:void insb(unsigned port, void *addr, unsigned long count);void outsb(unsigned port, void *addr, unsigned long count);Read or write count bytes starting at the memory address addr.

Data is readfrom or written to the single port port.void insw(unsigned port, void *addr, unsigned long count);void outsw(unsigned port, void *addr, unsigned long count);Read or write 16-bit values to a single 16-bit port.void insl(unsigned port, void *addr, unsigned long count);void outsl(unsigned port, void *addr, unsigned long count);Read or write 32-bit values to a single 32-bit port.Pausing I/OSome platforms — most notably the i386—can have problems when the processortries to transfer data too quickly to or from the bus.

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

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

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

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