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

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

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

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

Other paths worth settinginclude boot, which points to a directory of modules that should be loaded atboot time, and toplevel, which gives a top-level directory under which atree of module subdirectories may be found. You almost certainly want toinclude a separate keep directive as well.keepNormally, a path directive will cause modpr obe to discard all other paths(including the defaults) that it may have known about. By placing a keepbefor e any path directives, you can cause modpr obe to add new paths to thelist instead of replacing it.alias alias_name real_nameCauses modpr obe to load the module real_name when asked to loadalias_name.

The alias name usually identifies a specific capability; it has values such as scsi_hostadapter, eth0, or sound. This is the means bywhich generic requests (‘‘a driver for the first Ethernet card’’) get mapped intospecific modules. Alias lines are usually created by the system installation process; once it has figured out what hardware a specific system has, it generatesthe appropriate alias entries to get the right drivers loaded.options [-k] module optsProvides a set of options (opts) for the given module when it is loaded. Ifthe -k flag is provided, the module will not be automatically removed by amodpr obe -r run.pre-install module commandpost-install module commandpre-remove module commandpost-remove module commandThe first two specify a command to be run either before or after the givenmodule is installed; the second two run the command before or after moduleremoval.

These directives are useful for causing extra user-space processing tohappen or for running a required daemon process. The command should begiven as a full pathname to avoid possible problems.Note that, for the removal commands to be run, the module must be removedwith modpr obe. They will not be run if the module is removed with rmmod,or if the system goes down (gracefully or otherwise).modpr obe supports far more directives than we have listed here, but the others aregenerally only needed in complicated situations.30822 June 2001 16:40http://openlib.org.uaLoading Modules on DemandA typical /etc/modules.conf looks like this:alias scsi_hostadapter aic7xxxalias eth0 eepro100pre-install pcmcia_core /etc/rc.d/init.d/pcmcia startoptions short irq=1alias sound es1370This file tells modpr obe which drivers to load to make the SCSI system, Ethernet,and sound cards work.

It also ensures that if the PCMCIA drivers are loaded, astartup script is invoked to run the card services daemon. Finally, an option is provided to be passed to the short driver.Module Loading and SecurityThe loading of a module into the kernel has obvious security implications, sincethe loaded code runs at the highest possible privilege level. For this reason, it isimportant to be very careful in how you work with the module-loading system.When editing the modules.conf file, one should always keep in mind that anybodywho can load kernel modules has complete control over the system. Thus, forexample, any directories added to the load path should be very carefully protected, as should the modules.conf file itself.Note that insmod will normally refuse to load any modules that are not owned bythe root account; this behavior is an attempt at a defense against an attacker whoobtains write access to a module directory.

You can override this check with anoption to insmod (or a modules.conf line), but doing so reduces the security ofyour system.One other thing to keep in mind is that the module name parameter that you passto request_module eventually ends up on the modpr obe command line. If thatmodule name is provided by a user-space program in any way, it must be verycarefully validated before being handed off to request_module. Consider, forexample, a system call that configures network interfaces. In response to an invocation of ifconfig, this system call tells request_module to load the driver for the(user-specified) interface. A hostile user can then carefully choose a fictitious interface name that will cause modpr obe to do something improper.

This is a real vulnerability that was discovered late in the 2.4.0-test development cycle; the worstproblems have been cleaned up, but the system is still vulnerable to maliciousmodule names.Module Loading ExampleLet’s now try to use the demand-loading functions in practice. To this end, we’lluse two modules called master and slave, found in the directory misc-modules inthe source files provided on the O’Reilly FTP site.30922 June 2001 16:40http://openlib.org.uaChapter 11: kmod and Advanced ModularizationIn order to run this test code without installing the modules in the default modulesearch path, you can add something like the following lines to your /etc/modules.conf:keeppath[misc]=˜rubini/driverBook/src/misc-modulesThe slave module performs no function; it just takes up space until removed.

Themaster module, on the other hand, looks like this:#include <linux/kmod.h>#include "sysdep.h"int master_init_module(void){int r[2]; /* results */r[0]=request_module("slave");r[1]=request_module("nonexistent");printk(KERN_INFO "master: loading results are %i, %i\n", r[0],r[1]);return 0; /* success */}void master_cleanup_module(void){ }At load time, master tries to load two modules: the slave module and one thatdoesn’t exist. The printk messages reach your system logs and possibly the console.

This is what happens in a system configured for kmod support when thedaemon is active and the commands are issued on the text console:morgana.root# depmod -amorgana.root# insmod ./master.omaster: loading results are 0, 0morgana.root# cat /proc/modulesslave2480master7400es1370348321(autoclean)(unused)Both the return value from request_module and the /pr oc/modules file (describedin ‘‘Initialization and Shutdown’’ in Chapter 2) show that the slave module hasbeen correctly loaded. Note, however, that the attempt to load nonexistent alsoshows a successful return value. Because modpr obe was run, request_modulereturns success, regardless of what happened to modpr obe.A subsequent removal of master will produce results like the following:morgana.root# rmmod mastermorgana.root# cat /proc/modulesslave2480es1370348321(autoclean)31022 June 2001 16:40http://openlib.org.uaIntermodule CommunicationThe slave module has been left behind in the kernel, where it will remain until thenext module cleanup pass is done (which is often never on modern systems).Running User-Mode Helper ProgramsAs we have seen, the request_module function runs a program in user mode (i.e.,running as a separate process, in an unprivileged processor mode, and in userspace) to help it get its job done.

In the 2.3 development series, the kernel developers made the ‘‘run a user-mode helper’’ capability available to the rest of thekernel code. Should your driver need to run a user-mode program to support itsoperations, this mechanism is the way to do it. Since it’s part of the kmod implementation, we’ll look at it here. If you are interested in this capability, a look atker nel/kmod.c is recommended; it’s not much code and illustrates nicely the use ofuser-mode helpers.The interface for running helper programs is fairly simple. As of kernel 2.4.0-test9,there is a function call_user modehelper; it is used primarily by the hot-plug subsystem (i.e., for USB devices and such) to perform module loading and configuration tasks when a new device is attached to the system.

Its prototype is:int call_usermodehelper(char *path, char **argv, char **envp);The arguments will be familiar: they are the name of the executable to run, arguments to pass to it (argv[0], by convention, is the name of the program itself),and the values of any environment variables. Both arrays must be terminated byNULL values, just like with the execve system call. call_user modehelper will sleepuntil the program has been started, at which point it returns the status of the operation.Helper programs run in this mode are actually run as children of a kernel threadcalled keventd. An important implication of this design is that there is no way foryour code to know when the helper program has finished or what its exit status is.Running helper programs is thus a bit of an act of faith.It is worth pointing out that truly legitimate uses of user-mode helper programs arerare.

In most cases, it is better to set up a script to be run at module installationtime that does all needed work as part of loading the module rather than to wireinvocations of user-mode programs into kernel code. This sort of policy is best leftto the user whenever possible.Intermodule CommunicationVery late in the pre-2.4.0 development series, the kernel developers added a newinterface providing limited communication between modules.

This intermodulescheme allows modules to register strings pointing to data of interest, which canbe retrieved by other modules. We’ll look briefly at this interface, using a variationof our master and slave modules.31122 June 2001 16:40http://openlib.org.uaChapter 11: kmod and Advanced ModularizationWe use the same master module, but introduce a new slave module called inter.All inter does is to make a string and a function available under the nameime_string (ime means ‘‘intermodule example’’) and ime_function; it looks,in its entirety, as follows:static char *string = "inter says ’Hello World’";void ime_function(const char *who){printk(KERN_INFO "inter: ime_function called by %s\n", who);}int ime_init(void){inter_module_register("ime_string", THIS_MODULE, string);inter_module_register("ime_function", THIS_MODULE, ime_function);return 0;}void ime_cleanup(void){inter_module_unregister("ime_string");inter_module_unregister("ime_function");}This code uses inter_module_r egister, which has this prototype:void inter_module_register(const char *string, struct module *module,const void *data);string is the string other modules will use to find the data; module is a pointerto the module owning the data, which will almost always be THIS_MODULE; anddata is a pointer to whatever data is to be shared.

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

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

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

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