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

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

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

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

Unfortunately, quite a few drivers still use the old convention. Theyhave to: changing the command codes would break no end of binary programs. Inour sources, however, we will use the new command code convention exclusively.To choose ioctl numbers for your driver according to the new convention, youshould first check include/asm/ioctl.h and Documentation/ioctl-number.txt. Theheader defines the bitfields you will be using: type (magic number), ordinal number, direction of transfer, and size of argument. The ioctl-number.txt file lists themagic numbers used throughout the kernel, so you’ll be able to choose your ownmagic number and avoid overlaps. The text file also lists the reasons why the convention should be used.The old, and now deprecated, way of choosing an ioctl number was easy: authorschose a magic eight-bit number, such as ‘‘k’’ (hex 0x6b), and added an ordinalnumber, like this:#define SCULL_IOCTL1 0x6b01#define SCULL_IOCTL2 0x6b02/* ....

*/If both the application and the driver agreed on the numbers, you only needed toimplement the switch statement in your driver. However, this way of definingioctl numbers, which had its foundations in Unix tradition, shouldn’t be used anymore. We’ve only shown the old way to give you a taste of what ioctl numberslook like.The new way to define numbers uses four bitfields, which have the followingmeanings. Any new symbols we introduce in the following list are defined in<linux/ioctl.h>.13022 June 2001 16:36http://openlib.org.uaioctltypeThe magic number. Just choose one number (after consulting ioctl-number.txt)and use it throughout the driver. This field is eight bits wide(_IOC_TYPEBITS).numberThe ordinal (sequential) number.

It’s eight bits (_IOC_NRBITS) wide.directionThe direction of data transfer, if the particular command involves a data transfer. The possible values are _IOC_NONE (no data transfer), _IOC_READ,_IOC_WRITE, and _IOC_READ | _IOC_WRITE (data is transferred bothways). Data transfer is seen from the application’s point of view; _IOC_READmeans reading fr om the device, so the driver must write to user space.

Notethat the field is a bit mask, so _IOC_READ and _IOC_WRITE can be extractedusing a logical AND operation.sizeThe size of user data involved. The width of this field is architecture dependent and currently ranges from 8 to 14 bits. You can find its value for yourspecific architecture in the macro _IOC_SIZEBITS. If you intend your driverto be portable, however, you can only count on a size up to 255. It’s notmandatory that you use the size field.

If you need larger data structures, youcan just ignore it. We’ll see soon how this field is used.The header file <asm/ioctl.h>, which is included by <linux/ioctl.h>,defines macros that help set up the command numbers as follows:_IO(type,nr), _IOR(type,nr,dataitem), _IOW(type,nr,dataitem),and _IOWR(type,nr,dataitem). Each macro corresponds to one of the possible values for the direction of the transfer. The type and number fields arepassed as arguments, and the size field is derived by applying sizeof to thedataitem argument. The header also defines macros to decode the numbers:_IOC_DIR(nr), _IOC_TYPE(nr), _IOC_NR(nr), and _IOC_SIZE(nr). Wewon’t go into any more detail about these macros because the header file is clear,and sample code is shown later in this section.Here is how some ioctl commands are defined in scull. In particular, these commands set and get the driver’s configurable parameters./* Use ’k’ as magic number */#define SCULL_IOC_MAGIC ’k’#define SCULL_IOCRESET _IO(SCULL_IOC_MAGIC, 0)/*****STGQmeansmeansmeansmeans"Set" through a ptr"Tell" directly with the argument value"Get": reply by setting through a pointer"Query": response is on the return value13122 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver Operations* X means "eXchange": G and S atomically* H means "sHift": T and Q atomically*/#define SCULL_IOCSQUANTUM _IOW(SCULL_IOC_MAGIC, 1, scull_quantum)#define SCULL_IOCSQSET _IOW(SCULL_IOC_MAGIC, 2, scull_qset)#define SCULL_IOCTQUANTUM _IO(SCULL_IOC_MAGIC, 3)#define SCULL_IOCTQSET _IO(SCULL_IOC_MAGIC, 4)#define SCULL_IOCGQUANTUM _IOR(SCULL_IOC_MAGIC, 5, scull_quantum)#define SCULL_IOCGQSET _IOR(SCULL_IOC_MAGIC, 6, scull_qset)#define SCULL_IOCQQUANTUM _IO(SCULL_IOC_MAGIC, 7)#define SCULL_IOCQQSET _IO(SCULL_IOC_MAGIC, 8)#define SCULL_IOCXQUANTUM _IOWR(SCULL_IOC_MAGIC, 9, scull_quantum)#define SCULL_IOCXQSET _IOWR(SCULL_IOC_MAGIC,10, scull_qset)#define SCULL_IOCHQUANTUM _IO(SCULL_IOC_MAGIC, 11)#define SCULL_IOCHQSET _IO(SCULL_IOC_MAGIC, 12)#define SCULL_IOCHARDRESET _IO(SCULL_IOC_MAGIC, 15) /* debugging tool */#define SCULL_IOC_MAXNR 15The last command, HARDRESET, is used to reset the module’s usage count to 0 sothat the module can be unloaded should something go wrong with the counter.The actual source file also defines all the commands between IOCHQSET andHARDRESET, although they’re not shown here.We chose to implement both ways of passing integer arguments — by pointer andby explicit value, although by an established convention ioctl should exchangevalues by pointer.

Similarly, both ways are used to return an integer number: bypointer or by setting the return value. This works as long as the return value is apositive integer; on return from any system call, a positive value is preserved (aswe saw for read and write), while a negative value is considered an error and isused to set errno in user space.The ‘‘exchange’’ and ‘‘shift’’ operations are not particularly useful for scull.

Weimplemented ‘‘exchange’’ to show how the driver can combine separate operationsinto a single atomic one, and ‘‘shift’’ to pair ‘‘tell’’ and ‘‘query.’’ There are timeswhen atomic* test-and-set operations like these are needed, in particular, whenapplications need to set or release locks.The explicit ordinal number of the command has no specific meaning. It is usedonly to tell the commands apart.

Actually, you could even use the same ordinalnumber for a read command and a write command, since the actual ioctl numberis different in the ‘‘direction’’ bits, but there is no reason why you would want todo so. We chose not to use the ordinal number of the command anywhere but inthe declaration, so we didn’t assign a symbolic value to it. That’s why explicit* A fragment of program code is said to be atomic when it will always be executed asthough it were a single instruction, without the possibility of the processor being interrupted and something happening in between (such as somebody else’s code running).13222 June 2001 16:36http://openlib.org.uaioctlnumbers appear in the definition given previously. The example shows one wayto use the command numbers, but you are free to do it differently.The value of the ioctl cmd argument is not currently used by the kernel, and it’squite unlikely it will be in the future.

Therefore, you could, if you were feelinglazy, avoid the complex declarations shown earlier and explicitly declare a set ofscalar numbers. On the other hand, if you did, you wouldn’t benefit from usingthe bitfields. The header <linux/kd.h> is an example of this old-fashionedapproach, using 16-bit scalar values to define the ioctl commands.

That source filerelied on scalar numbers because it used the technology then available, not out oflaziness. Changing it now would be a gratuitous incompatibility.The Return ValueThe implementation of ioctl is usually a switch statement based on the commandnumber. But what should the default selection be when the command numberdoesn’t match a valid operation? The question is controversial. Several kernel functions return -EINVAL (‘‘Invalid argument’’), which makes sense because the command argument is indeed not a valid one. The POSIX standard, however, statesthat if an inappropriate ioctl command has been issued, then -ENOTTY should bereturned. The string associated with that value used to be ‘‘Not a typewriter’’ underall libraries up to and including libc5.

Only libc6 changed the message to ‘‘Inappropriate ioctl for device,’’ which looks more to the point. Because most recentLinux system are libc6 based, we’ll stick to the standard and return -ENOTTY. It’sstill pretty common, though, to return -EINVAL in response to an invalid ioctlcommand.The Predefined CommandsThough the ioctl system call is most often used to act on devices, a few commandsare recognized by the kernel. Note that these commands, when applied to yourdevice, are decoded befor e your own file operations are called. Thus, if youchoose the same number for one of your ioctl commands, you won’t ever see anyrequest for that command, and the application will get something unexpectedbecause of the conflict between the ioctl numbers.The predefined commands are divided into three groups:•Those that can be issued on any file (regular, device, FIFO, or socket)•Those that are issued only on regular files•Those specific to the filesystem typeCommands in the last group are executed by the implementation of the hostingfilesystem (see the chattr command).

Device driver writers are interested only inthe first group of commands, whose magic number is ‘‘T.’’ Looking at the workingsof the other groups is left to the reader as an exercise; ext2_ioctl is a most13322 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver Operationsinteresting function (though easier than you may expect), because it implementsthe append-only flag and the immutable flag.The following ioctl commands are predefined for any file:FIOCLEXSet the close-on-exec flag (File IOctl CLose on EXec). Setting this flag willcause the file descriptor to be closed when the calling process executes a newprogram.FIONCLEXClear the close-on-exec flag.FIOASYNCSet or reset asynchronous notification for the file (as discussed in “Asynchronous Notification” later in this chapter).

Note that kernel versions up toLinux 2.2.4 incorrectly used this command to modify the O_SYNC flag. Sinceboth actions can be accomplished in other ways, nobody actually uses theFIOASYNC command, which is reported here only for completeness.FIONBIO‘‘File IOctl Non-Blocking I/O’’ (described later in this chapter in “Blocking andNonblocking Operations”). This call modifies the O_NONBLOCK flag infilp->f_flags.

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

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

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

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