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

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

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

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

Whenever a file structure is shared (for example, after a fork or a dup), release won’t be invoked until allcopies are closed. If you need to flush pending data when any copy is closed, youshould implement the flush method.6522 June 2001 16:35http://openlib.org.uaChapter 3: Char DriversThese methods, added late in the 2.3 development cycle, implement scatter/gather read and write operations. Applications occasionally need to do asingle read or write operation involving multiple memory areas; these systemcalls allow them to do so without forcing extra copy operations on the data.struct module *owner;This field isn’t a method like everything else in the file_operations structure.

Instead, it is a pointer to the module that “owns” this structure; it is usedby the kernel to maintain the module’s usage count.The scull device driver implements only the most important device methods, anduses the tagged format to declare its file_operations structure:struct file_operations scull_fops = {llseek: scull_llseek,read: scull_read,write: scull_write,ioctl: scull_ioctl,open: scull_open,release: scull_release,};This declaration uses the tagged structure initialization syntax, as we described earlier. This syntax is preferred because it makes drivers more portable acrosschanges in the definitions of the structures, and arguably makes the code morecompact and readable. Tagged initialization allows the reordering of structuremembers; in some cases, substantial performance improvements have been realized by placing frequently accessed members in the same hardware cache line.It is also necessary to set the owner field of the file_operations structure.

Insome kernel code, you will often see owner initialized with the rest of the structure, using the tagged syntax as follows:owner: THIS_MODULE,That approach works, but only on 2.4 kernels. A more portable approach is to usethe SET_MODULE_OWNER macro, which is defined in <linux/module.h>. scullperforms this initialization as follows:SET_MODULE_OWNER(&scull_fops);This macro works on any structure that has an owner field; we will encounter thisfield again in other contexts later in the book.The file Structurestruct file, defined in <linux/fs.h>, is the second most important datastructure used in device drivers.

Note that a file has nothing to do with the6622 June 2001 16:35http://openlib.org.uaThe file StructureFILEs of user-space programs. A FILE is defined in the C library and neverappears in kernel code. A struct file, on the other hand, is a kernel structurethat never appears in user programs.The file structure represents an open file. (It is not specific to device drivers;every open file in the system has an associated struct file in kernel space.) Itis created by the kernel on open and is passed to any function that operates onthe file, until the last close. After all instances of the file are closed, the kernelreleases the data structure.

An open file is different from a disk file, represented bystruct inode.In the kernel sources, a pointer to struct file is usually called either file orfilp (“file pointer”). We’ll consistently call the pointer filp to prevent ambiguities with the structure itself. Thus, file refers to the structure and filp to apointer to the structure.The most important fields of struct file are shown here. As in the previoussection, the list can be skipped on a first reading. In the next section though,when we face some real C code, we’ll discuss some of the fields, so they are herefor you to refer to.mode_t f_mode;The file mode identifies the file as either readable or writable (or both), bymeans of the bits FMODE_READ and FMODE_WRITE.

You might want to checkthis field for read/write permission in your ioctl function, but you don’t needto check permissions for read and write because the kernel checks beforeinvoking your method. An attempt to write without permission, for example,is rejected without the driver even knowing about it.loff_t f_pos;The current reading or writing position. loff_t is a 64-bit value (longlong in gcc terminology).

The driver can read this value if it needs to knowthe current position in the file, but should never change it (read and writeshould update a position using the pointer they receive as the last argumentinstead of acting on filp->f_pos directly).unsigned int f_flags;These are the file flags, such as O_RDONLY, O_NONBLOCK, and O_SYNC. Adriver needs to check the flag for nonblocking operation, while the other flagsare seldom used. In particular, read/write permission should be checked usingf_mode instead of f_flags. All the flags are defined in the header<linux/fcntl.h>.6722 June 2001 16:35http://openlib.org.uaChapter 3: Char Driversstruct file_operations *f_op;The operations associated with the file.

The kernel assigns the pointer as partof its implementation of open, and then reads it when it needs to dispatch anyoperations. The value in filp->f_op is never saved for later reference; thismeans that you can change the file operations associated with your file whenever you want, and the new methods will be effective immediately after youreturn to the caller. For example, the code for open associated with majornumber 1 (/dev/null, /dev/zer o, and so on) substitutes the operations infilp->f_op depending on the minor number being opened. This practiceallows the implementation of several behaviors under the same major numberwithout introducing overhead at each system call.

The ability to replace thefile operations is the kernel equivalent of “method overriding” in object-oriented programming.void *private_data;The open system call sets this pointer to NULL before calling the open methodfor the driver. The driver is free to make its own use of the field or to ignoreit. The driver can use the field to point to allocated data, but then must freememory in the release method before the file structure is destroyed by thekernel.

private_data is a useful resource for preserving state informationacross system calls and is used by most of our sample modules.struct dentry *f_dentry;The directory entry (dentry) structure associated with the file. Dentries are anoptimization introduced in the 2.1 development series. Device driver writersnormally need not concern themselves with dentry structures, other than toaccess the inode structure as filp->f_dentry->d_inode.The real structure has a few more fields, but they aren’t useful to device drivers.We can safely ignore those fields because drivers never fill file structures; theyonly access structures created elsewhere.open and releaseNow that we’ve taken a quick look at the fields, we’ll start using them in real scullfunctions.The open MethodThe open method is provided for a driver to do any initialization in preparation forlater operations.

In addition, open usually increments the usage count for thedevice so that the module won’t be unloaded before the file is closed. The count,described in “The Usage Count” in Chapter 2, is then decremented by the releasemethod.6822 June 2001 16:35http://openlib.org.uaopen and releaseIn most drivers, open should perform the following tasks:•Increment the usage count•Check for device-specific errors (such as device-not-ready or similar hardwareproblems)•Initialize the device, if it is being opened for the first time•Identify the minor number and update the f_op pointer, if necessary•Allocate and fill any data structure to be put in filp->private_dataIn scull, most of the preceding tasks depend on the minor number of the devicebeing opened. Therefore, the first thing to do is identify which device is involved.We can do that by looking at inode->i_rdev.We’ve already talked about how the kernel doesn’t use the minor number of thedevice, so the driver is free to use it at will.

In practice, different minor numbersare used to access different devices or to open the same device in a different way.For example, /dev/st0 (minor number 0) and /dev/st1 (minor 1) refer to differentSCSI tape drives, whereas /dev/nst0 (minor 128) is the same physical device as/dev/st0, but it acts differently (it doesn’t rewind the tape when it is closed). All ofthe tape device files have different minor numbers, so that the driver can tell themapart.A driver never actually knows the name of the device being opened, just thedevice number—and users can play on this indifference to names by aliasing newnames to a single device for their own convenience.

If you create two special fileswith the same major/minor pair, the devices are one and the same, and there is noway to differentiate between them. The same effect can be obtained using a symbolic or hard link, and the preferred way to implement aliasing is creating a symbolic link.The scull driver uses the minor number like this: the most significant nibble(upper four bits) identifies the type (personality) of the device, and the least significant nibble (lower four bits) lets you distinguish between individual devices if thetype supports more than one device instance. Thus, scull0 is different fromscullpipe0 in the top nibble, while scull0 and scull1 differ in the bottom nibble.*Two macros (TYPE and NUM) are defined in the source to extract the bits from adevice number, as shown here:#define TYPE(dev) (MINOR(dev) >> 4) /* high nibble */#define NUM(dev) (MINOR(dev) & 0xf) /* low nibble */* Bit splitting is a typical way to use minor numbers.

The IDE driver, for example, uses thetop two bits for the disk number, and the bottom six bits for the partition number.6922 June 2001 16:35http://openlib.org.uaChapter 3: Char DriversFor each device type, scull defines a specific file_operations structure, whichis placed in filp->f_op at open time. The following code shows how multiplefops are implemented:struct file_operations *scull_fop_array[]={&scull_fops, /* type 0 */&scull_priv_fops, /* type 1 */&scull_pipe_fops, /* type 2 */&scull_sngl_fops, /* type 3 */&scull_user_fops, /* type 4 */&scull_wusr_fops /* type 5 */};#define SCULL_MAX_TYPE 5/* In scull_open, the fop_array is used according to TYPE(dev) */int type = TYPE(inode->i_rdev);if (type > SCULL_MAX_TYPE) return -ENODEV;filp->f_op = scull_fop_array[type];The kernel invokes open according to the major number; scull uses the minornumber in the macros just shown. TYPE is used to index into scull_fop_arrayin order to extract the right set of methods for the device type being opened.In scull, filp->f_op is assigned to the correct file_operations structure asdetermined by the device type, found in the minor number.

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

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

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

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