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

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

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

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

The list_head data structureQuick ReferenceThe following symbols were introduced in this chapter.#include <linux/types.h>typedef u8;typedef u16;typedef u32;typedef u64;These types are guaranteed to be 8-, 16-, 32-, and 64-bit unsigned integer values. The equivalent signed types exist as well.

In user space, you can refer tothe types as _ _u8, _ _u16, and so forth.#include <asm/page.h>PAGE_SIZEPAGE_SHIFTThese symbols define the number of bytes per page for the current architecture and the number of bits in the page offset (12 for 4-KB pages and 13 for8-KB pages).30322 June 2001 16:40http://openlib.org.uaChapter 10: Judicious Use of Data Types#include <asm/byteorder.h>_ _LITTLE_ENDIAN_ _BIG_ENDIANOnly one of the two symbols is defined, depending on the architecture.#include <asm/byteorder.h>u32 _ _cpu_to_le32 (u32);u32 _ _le32_to_cpu (u32);Functions for converting between known byte orders and that of the processor.

There are more than 60 such functions; see the various files ininclude/linux/byteorder/ for a full list and the ways in which they are defined.#include <asm/unaligned.h>get_unaligned(ptr);put_unaligned(val, ptr);Some architectures need to protect unaligned data access using these macros.The macros expand to normal pointer dereferencing for architectures that permit you to access unaligned data.#include <linux/list.h>list_add(struct list_head *new, struct list_head *head);list_add_tail(struct list_head *new, struct list_head*head);list_del(struct list_head *entry);list_empty(struct list_head *head);list_entry(entry, type, member);list_splice(struct list_head *list, struct list_head *head);Functions for manipulating circular, doubly linked lists.30422 June 2001 16:40http://openlib.org.uaCHAPTER ELEVENKMOD AND ADVANCEDMODULARIZATIONIn this second part of the book, we discuss more advanced topics than we’ve seenup to now.

Once again, we start with modularization.The introduction to modularization in Chapter 2 was only part of the story; thekernel and the modutils package support some advanced features that are morecomplex than we needed earlier to get a basic driver up and running. The featuresthat we talk about in this chapter include the kmod process and version supportinside modules (a facility meant to save you from recompiling your modules eachtime you upgrade your kernel). We also touch on how to run user-space helperprograms from within kernel code.The implementation of demand loading of modules has changed significantly overtime.

This chapter discusses the 2.4 implementation, as usual. The sample codeworks, as far as possible, on the 2.0 and 2.2 kernels as well; we cover the differences at the end of the chapter.Loading Modules on DemandTo make it easier for users to load and unload modules, to avoid wasting kernelmemory by keeping drivers in core when they are not in use, and to allow thecreation of ‘‘generic’’ kernels that can support a wide variety of hardware, Linuxoffers support for automatic loading and unloading of modules. To exploit this feature, you need to enable kmod support when you configure the kernel before youcompile it; most kernels from distributors come with kmod enabled. This ability torequest additional modules when they are needed is particularly useful for driversusing module stacking.The idea behind kmod is simple, yet effective.

Whenever the kernel tries to accesscertain types of resources and finds them unavailable, it makes a special kernelcall to the kmod subsystem instead of simply returning an error. If kmod succeedsin making the resource available by loading one or more modules, the kernel30522 June 2001 16:40http://openlib.org.uaChapter 11: kmod and Advanced Modularizationcontinues working; otherwise, it returns the error.

Virtually any resource can berequested this way: char and block drivers, filesystems, line disciplines, networkprotocols, and so on.One example of a driver that benefits from demand loading is the Advanced LinuxSound Architecture (ALSA) sound driver suite, which should (someday) replace thecurrent sound implementation (Open Sound System, or OSS) in the Linux kernel.*ALSA is split into many pieces. The set of core code that every system needs isloaded first.

Additional pieces get loaded depending on both the installed hardware (which sound card is present) and the desired functionality (MIDI sequencer,synthesizer, mixer, OSS compatibility, etc.). Thus, a large and complicated systemcan be broken down into components, with only the necessary parts being actually present in the running system.Another common use of automatic module loading is to make a ‘‘one size fits all’’kernel to package with distributions.

Distributors want their kernels to support asmuch hardware as possible. It is not possible, however, to simply configure inevery conceivable driver; the resulting kernel would be too large to load (and verywasteful of system memory), and having that many drivers trying to probe forhardware would be a near-certain way to create conflicts and confusion. Withautomatic loading, the kernel can adapt itself to the hardware it finds on each individual system.Requesting Modules in the KernelAny kernel-space code can request the loading of a module when needed, byinvoking a facility known as kmod.

kmod was initially implemented as a separate,standalone kernel process that handled module loading requests, but it has longsince been simplified by not requiring the separate process context. To use kmod,you must include <linux/kmod.h> in your driver source.To request the loading of a module, call request_module:int request_module(const char *module_name);The module_name can either be the name of a specific module file or the nameof a more generic capability; we’ll look more closely at module names in the nextsection. The return value from request_module will be 0, or one of the usual negative error codes if something goes wrong.Note that request_module is synchronous — it will sleep until the attempt to loadthe module has completed.

This means, of course, that request_module cannot becalled from interrupt context. Note also that a successful return from request_module does not guarantee that the capability you were after is now available. Thereturn value indicates that request_module was successful in running modpr obe,* The ALSA drivers can be found at www.alsa-project.org.30622 June 2001 16:40http://openlib.org.uaLoading Modules on Demandbut does not reflect the success status of modpr obe itself. Any number of problemsor configuration errors can lead request_module to return a success status when ithas not loaded the module you needed.Thus the proper usage of request_module usually requires testing for the existenceof a needed capability twice:if ( (ptr = look_for_feature()) == NULL) {/* if feature is missing, create request string */sprintf(modname, "fmt-for-feature-%i\n", featureid);request_module(modname); /* and try lo load it */}/* Check for existence of the feature again; error if missing */if ( (ptr = look_for_feature()) == NULL)return -ENODEV;The first check avoids redundant calls to request_module.

If the feature is notavailable in the running kernel, a request string is generated and request_moduleis used to look for it. The final check makes sure that the required feature hasbecome available.The User-Space SideThe actual task of loading a module requires help from user space, for the simplereason that it is far easier to implement the required degree of configurability andflexibility in that context. When the kernel code calls request_module, a new ‘‘kernel thread’’ process is created, which runs a helper program in the user context.This program is called modpr obe; we have seen it briefly earlier in this book.modpr obe can do a great many things.

In the simplest case, it just calls insmodwith the name of a module as passed to request_module. Kernel code, however,will often call request_module with a more abstract name representing a neededcapability, such as scsi_hostadapter; modpr obe will then find and load thecorrect module. modpr obe can also handle module dependencies; if a requestedmodule requires yet another module to function, modpr obe will load both—assuming that depmod -a was run after the modules have been installed.*The modpr obe utility is configured by the file /etc/modules.conf.† See the modules.conf manpage for the full list of things that can appear in this file. Here is anoverview of the most common sorts of entries:* Most distributions run depmod -a automatically at boot time, so you don’t need to worryabout that unless you installed new modules after you rebooted.

See the modprobe documentation for more details.† On older systems, this file is often called /etc/conf.modules instead. That name still works,but its use is deprecated.30722 June 2001 16:40http://openlib.org.uaChapter 11: kmod and Advanced Modularizationpath[misc]=directoryThis directive tells modpr obe that miscellaneous modules can be found in themisc subdirectory under the given directory.

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

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

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

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