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

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

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

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

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

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

This section brieflydescribes the mechanism. However, the basic resource allocation functions(request_r egion and the rest) are still implemented (via macros) and are still universally used because they are backward compatible with earlier kernel versions.Most module programmers will not need to know about what is really happeningunder the hood, but those working on more complex drivers may be interested.Linux resource management is able to control arbitrary resources, and it can do soin a hierarchical manner. Globally known resources (the range of I/O ports, say)can be subdivided into smaller subsets—for example, the resources associatedwith a particular bus slot. Individual drivers can then further subdivide their rangeif need be.Resource ranges are<linux/ioport.h>:describedviaaresourcestructure,declaredinstruct resource {const char *name;unsigned long start, end;unsigned long flags;struct resource *parent, *sibling, *child;};4022 June 2001 16:34http://openlib.org.uaUsing ResourcesTop-level (root) resources are created at boot time.

For example, the resourcestructure describing the I/O port range is created as follows:struct resource ioport_resource ={ "PCI IO", 0x0000, IO_SPACE_LIMIT, IORESOURCE_IO };Thus, the name of the resource is PCI IO, and it covers a range from zerothrough IO_SPACE_LIMIT, which, according to the hardware platform being run,can be 0xffff (16 bits of address space, as happens on the x86, IA-64, Alpha,M68k, and MIPS), 0xffffffff (32 bits: SPARC, PPC, SH) or0xffffffffffffffff (64 bits: SPARC64).Subranges of a given resource may be created with allocate_r esource.

For example, during PCI initialization a new resource is created for a region that is actuallyassigned to a physical device. When the PCI code reads those port or memoryassignments, it creates a new resource for just those regions, and allocates themunder ioport_resource or iomem_resource.A driver can then request a subset of a particular resource (actually a subrange ofa global resource) and mark it as busy by calling _ _request_r egion, which returnsa pointer to a new struct resource data structure that describes the resourcebeing requested (or returns NULL in case of error).

The structure is already part ofthe global resource tree, and the driver is not allowed to use it at will.An interested reader may enjoy looking at the details by browsing the source inker nel/resource.c and looking at the use of the resource management scheme inthe rest of the kernel. Most driver writers, however, will be more than adequatelyserved by request_r egion and the other functions introduced in the previous section.This layered mechanism brings a couple of benefits.

One is that it makes the I/Ostructure of the system apparent within the data structures of the kernel. The resultshows up in /pr oc/ioports, for example:e800-e8ff : Adaptec AHA-2940U2/W / 7890e800-e8be : aic7xxxThe range e800-e8ff is allocated to an Adaptec card, which has identified itselfto the PCI bus driver. The aic7xxx driver has then requested most of that range—in this case, the part corresponding to real ports on the card.The other advantage to controlling resources in this way is that it partitions theport space into distinct subranges that reflect the hardware of the underlying system. Since the resource allocator will not allow an allocation to cross subranges, itcan block a buggy driver (or one looking for hardware that does not exist on thesystem) from allocating ports that belong to more than range—even if some ofthose ports are unallocated at the time.4122 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesAutomatic and Manual ConfigurationSeveral parameters that a driver needs to know can change from system to system.For instance, the driver must know the hardware’s actual I/O addresses, or memory range (this is not a problem with well-designed bus interfaces and only appliesto ISA devices).

Sometimes you’ll need to pass parameters to a driver to help it infinding its own device or to enable/disable specific features.Depending on the device, there may be other parameters in addition to the I/Oaddress that affect the driver’s behavior, such as device brand and release number.It’s essential for the driver to know the value of these parameters in order to workcorrectly.

Setting up the driver with the correct values (i.e., configuring it) is oneof the tricky tasks that need to be performed during driver initialization.Basically, there are two ways to obtain the correct values: either the user specifiesthem explicitly or the driver autodetects them. Although autodetection is undoubtedly the best approach to driver configuration, user configuration is much easier toimplement.

A suitable trade-off for a driver writer is to implement automatic configuration whenever possible, while allowing user configuration as an option tooverride autodetection. An additional advantage of this approach to configurationis that the initial development can be done without autodetection, by specifyingthe parameters at load time, and autodetection can be implemented later.Many drivers also have configuration options that control other aspects of theiroperation. For example, drivers for SCSI adapters often have options controllingthe use of tagged command queuing, and the Integrated Device Electronics (IDE)drivers allow user control of DMA operations. Thus, even if your driver reliesentirely on autodetection to locate hardware, you may want to make other configuration options available to the user.Parameter values can be assigned at load time by insmod or modpr obe ; the lattercan also read parameter assignment from a configuration file (typically/etc/modules.conf ).

The commands accept the specification of integer and stringvalues on the command line. Thus, if your module were to provide an integerparameter called skull_ival and a string parameter skull_sval, the parameters couldbe set at module load time with an insmod command like:insmod skull skull_ival=666 skull_sval="the beast"However, before insmod can change module parameters, the module must makethem available. Parameters are declared with the MODULE_PARM macro, which isdefined in module.h. MODULE_PARM takes two parameters: the name of the variable, and a string describing its type. The macro should be placed outside of anyfunction and is typically found near the head of the source file.

The two parameters mentioned earlier could be declared with the following lines:4222 June 2001 16:34http://openlib.org.uaAutomatic and Manual Configurationint skull_ival=0;char *skull_sval;MODULE_PARM (skull_ival, "i");MODULE_PARM (skull_sval, "s");Five types are currently supported for module parameters: b, one byte; h, a short(two bytes); i, an integer; l, a long; and s, a string. In the case of string values, apointer variable should be declared; insmod will allocate the memory for the usersupplied parameter and set the variable accordingly. An integer value precedingthe type indicates an array of a given length; two numbers, separated by ahyphen, give a minimum and maximum number of values. If you want to find theauthor’s description of this feature, you should refer to the header file<linux/module.h>.As an example, an array that must have at least two and no more than four valuescould be declared as:int skull_array[4];MODULE_PARM (skull_array, "2-4i");There is also a macro MODULE_PARM_DESC, which allows the programmer toprovide a description for a module parameter.

This description is stored in theobject file; it can be viewed with a tool like objdump, and can also be displayedby automated system administration tools. An example might be as follows:int base_port = 0x300;MODULE_PARM (base_port, "i");MODULE_PARM_DESC (base_port, "The base I/O port (default 0x300)");All module parameters should be given a default value; insmod will change thevalue only if explicitly told to by the user. The module can check for explicitparameters by testing parameters against their default values. Automatic configuration, then, can be designed to work this way: if the configuration variables havethe default value, perform autodetection; otherwise, keep the current value. Inorder for this technique to work, the “default” value should be one that the userwould never actually want to specify at load time.The following code shows how skull autodetects the port address of a device. Inthis example, autodetection is used to look for multiple devices, while manualconfiguration is restricted to a single device.

The function skull_detect occurredearlier, in “Ports,” while skull_init_board is in charge of device-specific initialization and thus is not shown./** port ranges: the device can reside between* 0x280 and 0x300, in steps of 0x10. It uses 0x10 ports.*/#define SKULL_PORT_FLOOR 0x280#define SKULL_PORT_CEIL 0x300#define SKULL_PORT_RANGE 0x0104322 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running Modules/** the following function performs autodetection, unless a specific* value was assigned by insmod to "skull_port_base"*/static int skull_port_base=0; /* 0 forces autodetection */MODULE_PARM (skull_port_base, "i");MODULE_PARM_DESC (skull_port_base, "Base I/O port for skull");static int skull_find_hw(void) /* returns the # of devices */{/* base is either the load-time value or the first trial */int base = skull_port_base ? skull_port_base: SKULL_PORT_FLOOR;int result = 0;/* loop one time if value assigned; try them all if autodetecting */do {if (skull_detect(base, SKULL_PORT_RANGE) == 0) {skull_init_board(base);result++;}base += SKULL_PORT_RANGE; /* prepare for next trial */}while (skull_port_base == 0 && base < SKULL_PORT_CEIL);return result;}If the configuration variables are used only within the driver (they are not published in the kernel’s symbol table), the driver writer can make life a little easierfor the user by leaving off the prefix on the variable names (in this case,skull_ ).

Prefixes usually mean little to users except extra typing.For completeness, there are three other macros that place documentation into theobject file. They are as follows:MODULE_AUTHOR (name)Puts the author’s name into the object file.MODULE_DESCRIPTION (desc)Puts a description of the module into the object file.MODULE_SUPPORTED_DEVICE (dev)Places an entry describing what device is supported by this module. Comments in the kernel source suggest that this parameter may eventually be usedto help with automated module loading, but no such use is made at this time.4422 June 2001 16:34http://openlib.org.uaDoing It in User SpaceDoing It in User SpaceA Unix programmer who’s addressing kernel issues for the first time might well benervous about writing a module.

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