Linux Device Drivers 2nd Edition, страница 12

PDF-файл Linux Device Drivers 2nd Edition, страница 12 Основы автоматизированного проектирования (ОАП) (17688): Книга - 3 семестрLinux Device Drivers 2nd Edition: Основы автоматизированного проектирования (ОАП) - PDF, страница 12 (17688) - СтудИзба2018-01-10СтудИзба

Описание файла

PDF-файл из архива "Linux Device Drivers 2nd Edition", который расположен в категории "". Всё это находится в предмете "основы автоматизированного проектирования (оап)" из 3 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "основы автоматизированного производства (оап)" в общих файлах.

Просмотр PDF-файла онлайн

Текст 12 страницы из PDF

It onlyworks, however, for built-in drivers; it has no effect on modules. _ _exit, instead,causes the omission of the marked function when the driver is not built as a module; again, in modules, it has no effect.The use of _ _init (and _ _initdata for data items) can reduce the amount ofmemory used by the kernel. There is no harm in marking module initializationfunctions with _ _init, even though currently there is no benefit either. Management of initialization sections has not been implemented yet for modules, but it’s apossible enhancement for the future.Using ResourcesA module can’t accomplish its task without using system resources such as3522 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running Modulesmemory, I/O ports, I/O memory, and interrupt lines, as well as DMA channels ifyou use old-fashioned DMA controllers like the Industry Standard Architecture(ISA) one.As a programmer, you are already accustomed to managing memory allocation;writing kernel code is no different in this regard.

Your program obtains a memoryarea using kmalloc and releases it using kfr ee. These functions behave like mallocand fr ee, except that kmalloc takes an additional argument, the priority. Usually, apriority of GFP_KERNEL or GFP_USER will do. The GFP acronym stands for “getfree page.” (Memory allocation is covered in detail in Chapter 7.)Beginning driver programmers may initially be surprised at the need to allocateI/O ports, I/O memory,* and interrupt lines explicitly. After all, it is possible for akernel module to simply access these resources without telling the operating system about it. Although system memory is anonymous and may be allocated fromanywhere, I/O memory, ports, and interrupts have very specific roles. Forinstance, a driver needs to be able to allocate the exact ports it needs, not justsome ports.

But drivers cannot just go about making use of these system resourceswithout first ensuring that they are not already in use elsewhere.I/O Ports and I/O MemoryThe job of a typical driver is, for the most part, writing and reading I/O ports andI/O memory. Access to I/O ports and I/O memory (collectively called I/O regions)happens both at initialization time and during normal operations.Unfortunately, not all bus architectures offer a clean way to identify I/O regionsbelonging to each device, and sometimes the driver must guess where its I/Oregions live, or even probe for the devices by reading and writing to “possible”address ranges. This problem is especially true of the ISA bus, which is still in usefor simple devices to plug in a personal computer and is very popular in theindustrial world in its PC/104 implementation (see PC/104 and PC/104+ in Chapter15).Despite the features (or lack of features) of the bus being used by a hardwaredevice, the device driver should be guaranteed exclusive access to its I/O regionsin order to prevent interference from other drivers.

For example, if a module probing for its hardware should happen to write to ports owned by another device,weird things would undoubtedly happen.The developers of Linux chose to implement a request/free mechanism for I/Oregions, mainly as a way to prevent collisions between different devices. Themechanism has long been in use for I/O ports and was recently generalized tomanage resource allocation at large. Note that this mechanism is just a software* The memory areas that reside on the peripheral device are commonly called I/O memoryto differentiate them from system RAM, which is customarily called memory).3622 June 2001 16:34http://openlib.org.uaUsing Resourcesabstraction that helps system housekeeping, and may or may not be enforced byhardware features. For example, unauthorized access to I/O ports doesn’t produceany error condition equivalent to “segmentation fault”—the hardware can’t enforceport registration.Information about registered resources is available in text form in the files/pr oc/ioports and /pr oc/iomem, although the latter was only introduced during 2.3development.

We’ll discuss version 2.4 now, introducing portability issues at theend of the chapter.PortsA typical /pr oc/ioports file on a recent PC that is running version 2.4 of the kernelwill look like the following:0000-001f : dma10020-003f : pic10040-005f : timer0060-006f : keyboard0080-008f : dma page reg00a0-00bf : pic200c0-00df : dma200f0-00ff : fpu0170-0177 : ide101f0-01f7 : ide002f8-02ff : serial(set)0300-031f : NE20000376-0376 : ide103c0-03df : vga+03f6-03f6 : ide003f8-03ff : serial(set)1000-103f : Intel Corporation1000-1003 : acpi1004-1005 : acpi1008-100b : acpi100c-100f : acpi1100-110f : Intel Corporation1300-131f : pcnet_cs1400-141f : Intel Corporation1800-18ff : PCI CardBus #021c00-1cff : PCI CardBus #045800-581f : Intel Corporationd000-dfff : PCI Bus #01d000-d0ff : ATI Technologies82371AB PIIX4 ACPI82371AB PIIX4 IDE82371AB PIIX4 ACPI82371AB PIIX4 USBInc 3D Rage LT Pro AGP-133Each entry in the file specifies (in hexadecimal) a range of ports locked by a driveror owned by a hardware device.

In earlier versions of the kernel the file had thesame format, but without the “layered” structure that is shown through indentation.3722 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesThe file can be used to avoid port collisions when a new device is added to thesystem and an I/O range must be selected by moving jumpers: the user can checkwhat ports are already in use and set up the new device to use an available I/Orange.

Although you might object that most modern hardware doesn’t use jumpersany more, the issue is still relevant for custom devices and industrial components.But what is more important than the ioports file itself is the data structure behindit. When the software driver for a device initializes itself, it can know what portranges are already in use; if the driver needs to probe I/O ports to detect the newdevice, it will be able to avoid probing those ports that are already in use by otherdrivers.ISA probing is in fact a risky task, and several drivers distributed with the officialLinux kernel refuse to perform probing when loaded as modules, to avoid the riskof destroying a running system by poking around in ports where some yetunknown hardware may live.

Fortunately, modern (as well as old-but-wellthought-out) bus architectures are immune to all these problems.The programming interface used to access the I/O registry is made up of threefunctions: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);check_r egion may be called to see if a range of ports is available for allocation; itreturns a negative error code (such as -EBUSY or -EINVAL) if the answer is no.request_r egion will actually allocate the port range, returning a non-NULL pointervalue if the allocation succeeds. Drivers don’t need to use or save the actualpointer returned—checking against NULL is all you need to do.* Code that needsto work only with 2.4 kernels need not call check_r egion at all; in fact, it’s betternot to, since things can change between the calls to check_r egion andrequest_r egion.

If you want to be portable to older kernels, however, you mustuse check_r egion because request_r egion used to return void before 2.4. Yourdriver should call release_r egion, of course, to release the ports when it is donewith them.The three functions<linux/ioport.h>.areactuallymacros,andtheyaredeclaredinThe typical sequence for registering ports is the following, as it appears in theskull sample driver. (The function skull_ probe_hw is not shown here because itcontains device-specific code.)* The actual pointer is used only when the function is called internally by the resourcemanagement subsystem of the kernel.3822 June 2001 16:34http://openlib.org.uaUsing Resources#include <linux/ioport.h>#include <linux/errno.h>static int skull_detect(unsigned int port, unsigned int range){int err;if ((err = check_region(port,range)) < 0) return err; /* busy */if (skull_probe_hw(port,range) != 0) return -ENODEV; /* not found */request_region(port,range,"skull");/* "Can’t fail" */return 0;}This code first looks to see if the required range of ports is available; if the portscannot be allocated, there is no point in looking for the hardware.

The actual allocation of the ports is deferred until after the device is known to exist. Therequest_r egion call should never fail; the kernel only loads a single module at atime, so there should not be a problem with other modules slipping in and stealing the ports during the detection phase. Paranoid code can check, but bear inmind that kernels prior to 2.4 define request_r egion as returning void.Any I/O ports allocated by the driver must eventually be released; skull does itfrom within cleanup_module :static void skull_release(unsigned int port, unsigned int range){release_region(port,range);}The request/free approach to resources is similar to the register/unregistersequence described earlier for facilities and fits well in the goto-based implementation scheme already outlined.MemorySimilar to what happens for I/O ports, I/O memory information is available in the/pr oc/iomem file.

This is a fraction of the file as it appears on a personal computer:00000000-0009fbff : System RAM0009fc00-0009ffff : reserved000a0000-000bffff : Video RAM area000c0000-000c7fff : Video ROM000f0000-000fffff : System ROM00100000-03feffff : System RAM00100000-0022c557 : Kernel code0022c558-0024455f : Kernel data20000000-2fffffff : Intel Corporation68000000-68000fff : Texas Instruments68001000-68001fff : Texas Instrumentse0000000-e3ffffff : PCI Bus #01e4000000-e7ffffff : PCI Bus #01e4000000-e4ffffff : ATI Technologies440BX/ZX - 82443BX/ZX Host bridgePCI1225PCI1225 (#2)Inc 3D Rage LT Pro AGP-1333922 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running Modulese6000000-e6000fff : ATI Technologies Inc 3D Rage LT Pro AGP-133fffc0000-ffffffff : reservedOnce again, the values shown are hexadecimal ranges, and the string after thecolon is the name of the “owner” of the I/O region.As far as driver writing is concerned, the registry for I/O memory is accessed inthe same way as for I/O ports, since they are actually based on the same internalmechanism.To obtain and relinquish access to a certain I/O memory region, the driver shoulduse the following calls:int check_mem_region(unsigned long start, unsigned long len);int request_mem_region(unsigned long start, unsigned long len,char *name);int release_mem_region(unsigned long start, unsigned long len);A typical driver will already know its own I/O memory range, and the sequenceshown previously for I/O ports will reduce to the following:if (check_mem_region(mem_addr, mem_size)) { printk("drivername:memory already in use\n"); return -EBUSY; }request_mem_region(mem_addr, mem_size, "drivername");Resource Allocation in Linux 2.4The current resource allocation mechanism was introduced in Linux 2.3.11 andprovides a flexible way of controlling system resources.

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