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

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

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

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

The user of adriver that is distributed in the form of a module can invoke such a script from thesystem’s rc.local file or call it manually whenever the module is needed.#!/bin/shmodule="scull"device="scull"mode="664"# invoke insmod with all arguments we were passed# and use a pathname, as newer modutils don’t look in . by default/sbin/insmod -f ./$module.o $* || exit 1# remove stale nodesrm -f /dev/${device}[0-3]major=‘awk "\\$2==\"$module\" {print \\$1}" /proc/devices‘mknodmknodmknodmknod/dev/${device}0/dev/${device}1/dev/${device}2/dev/${device}3cccc$major$major$major$major0123# give appropriate group/permissions, and change the group.# Not all distributions have staff; some have "wheel" instead.group="staff"grep ’ˆstaff:’ /etc/group > /dev/null || group="wheel"chgrp $group /dev/${device}[0-3]chmod $mode /dev/${device}[0-3]The script can be adapted for another driver by redefining the variables andadjusting the mknod lines.

The script just shown creates four devices because fouris the default in the scull sources.The last few lines of the script may seem obscure: why change the group andmode of a device? The reason is that the script must be run by the superuser, sonewly created special files are owned by root.

The permission bits default so thatonly root has write access, while anyone can get read access. Normally, a devicenode requires a different access policy, so in some way or another access rightsmust be changed. The default in our script is to give access to a group of users,5922 June 2001 16:35http://openlib.org.uaChapter 3: Char Driversbut your needs may vary. Later, in the section “Access Control on a Device File” inChapter 5, the code for sculluid will demonstrate how the driver can enforce itsown kind of authorization for device access.

A scull_unload script is then availableto clean up the /dev directory and remove the module.As an alternative to using a pair of scripts for loading and unloading, you couldwrite an init script, ready to be placed in the directory your distribution uses forthese scripts.* As part of the scull source, we offer a fairly complete and configurable example of an init script, called scull.init; it accepts the conventional arguments — either “start” or “stop” or “restart” — and performs the role of bothscull_load and scull_unload.If repeatedly creating and destroying /dev nodes sounds like overkill, there is auseful workaround. If you are only loading and unloading a single driver, you canjust use rmmod and insmod after the first time you create the special files withyour script: dynamic numbers are not randomized, and you can count on the samenumber to be chosen if you don’t mess with other (dynamic) modules.

Avoidinglengthy scripts is useful during development. But this trick, clearly, doesn’t scale tomore than one driver at a time.The best way to assign major numbers, in our opinion, is by defaulting to dynamicallocation while leaving yourself the option of specifying the major number at loadtime, or even at compile time. The code we suggest using is similar to the codeintroduced for autodetection of port numbers. The scull implementation uses aglobal variable, scull_major, to hold the chosen number. The variable is initialized to SCULL_MAJOR, defined in scull.h.

The default value of SCULL_MAJOR inthe distributed source is 0, which means “use dynamic assignment.” The user canaccept the default or choose a particular major number, either by modifying themacro before compiling or by specifying a value for scull_major on the insmod command line. Finally, by using the scull_load script, the user can pass arguments to insmod on scull_load ’s command line.†Here’s the code we use in scull ’s source to get a major number:result = register_chrdev(scull_major, "scull", &scull_fops);if (result < 0) {printk(KERN_WARNING "scull: can’t get major %d\n",scull_major);return result;}if (scull_major == 0) scull_major = result; /* dynamic */* Distributions vary widely on the location of init scripts; the most common directoriesused are /etc/init.d, /etc/rc.d/init.d, and /sbin/init.d.

In addition, if your script is to be runat boot time, you will need to make a link to it from the appropriate run-level directory(i.e., . . . /rc3.d).† The init script scull.init doesn’t accept driver options on the command line, but it supports a configuration file because it’s designed for automatic use at boot and shutdowntime.6022 June 2001 16:35http://openlib.org.uaMajor and Minor NumbersRemoving a Driver from the SystemWhen a module is unloaded from the system, the major number must be released.This is accomplished with the following function, which you call from the module’s cleanup function:int unregister_chrdev(unsigned int major, const char *name);The arguments are the major number being released and the name of the associated device.

The kernel compares the name to the registered name for that number, if any: if they differ, -EINVAL is returned. The kernel also returns -EINVAL ifthe major number is out of the allowed range.Failing to unregister the resource in the cleanup function has unpleasant effects./pr oc/devices will generate a fault the next time you try to read it, because one ofthe name strings still points to the module’s memory, which is no longer mapped.This kind of fault is called an oops because that’s the message the kernel printswhen it tries to access invalid addresses.*When you unload the driver without unregistering the major number, recovery willbe difficult because the strcmp function in unr egister_chrdev must dereference apointer (name) to the original module. If you ever fail to unregister a major number, you must reload both the same module and another one built on purpose tounregister the major.

The faulty module will, with luck, get the same address, andthe name string will be in the same place, if you didn’t change the code. The saferalternative, of course, is to reboot the system.In addition to unloading the module, you’ll often need to remove the device filesfor the removed driver. The task can be accomplished by a script that pairs to theone used at load time. The script scull_unload does the job for our sample device;as an alternative, you can invoke scull.init stop.If dynamic device files are not removed from /dev, there’s a possibility of unexpected errors: a spare /dev/framegrabber on a developer’s computer might refer toa fire-alarm device one month later if both drivers used a dynamic major number.“No such file or directory” is a friendlier response to opening /dev/framegrabberthan the new driver would produce.dev_t and kdev_tSo far we’ve talked about the major number.

Now it’s time to discuss the minornumber and how the driver uses it to differentiate among devices.Every time the kernel calls a device driver, it tells the driver which device is beingacted upon. The major and minor numbers are paired in a single data type that thedriver uses to identify a particular device. The combined device number (the major* The word oops is used as both a noun and a verb by Linux enthusiasts.6122 June 2001 16:35http://openlib.org.uaChapter 3: Char Driversand minor numbers concatenated together) resides in the field i_rdev of theinode structure, which we introduce later.

Some driver functions receive a pointerto struct inode as the first argument. So if you call the pointer inode (asmost driver writers do), the function can extract the device number by looking atinode->i_rdev.Historically, Unix declared dev_t (device type) to hold the device numbers. Itused to be a 16-bit integer value defined in <sys/types.h>.

Nowadays, morethan 256 minor numbers are needed at times, but changing dev_t is difficultbecause there are applications that “know” the internals of dev_t and wouldbreak if the structure were to change. Thus, while much of the groundwork hasbeen laid for larger device numbers, they are still treated as 16-bit integers fornow.Within the Linux kernel, however, a different type, kdev_t, is used. This datatype is designed to be a black box for every kernel function. User programs donot know about kdev_t at all, and kernel functions are unaware of what is insidea kdev_t. If kdev_t remains hidden, it can change from one kernel version tothe next as needed, without requiring changes to everyone’s device drivers.The information about kdev_t is confined in <linux/kdev_t.h>, which ismostly comments. The header makes instructive reading if you’re interested in thereasoning behind the code.

There’s no need to include the header explicitly in thedrivers, however, because <linux/fs.h> does it for you.The following macros and functions are the operations you can perform onkdev_t:MAJOR(kdev_t dev);Extract the major number from a kdev_t structure.MINOR(kdev_t dev);Extract the minor number.MKDEV(int ma, int mi);Create a kdev_t built from major and minor numbers.kdev_t_to_nr(kdev_t dev);Convert a kdev_t type to a number (a dev_t).to_kdev_t(int dev);Convert a number to kdev_t.

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

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

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

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