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

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

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

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

These “vector” versions take an array of structures, each of which containsa pointer to a buffer and a length value. A readv call would then be expected toread the indicated amount into each buffer in turn. writev, instead, would gathertogether the contents of each buffer and put them out as a single write operation.Until version 2.3.44 of the kernel, however, Linux always emulated readv andwritev with multiple calls to read and write.

If your driver does not supply methods to handle the vector operations, they will still be implemented that way. Inmany situations, however, greater efficiency is achieved by implementing readvand writev directly in the driver.The prototypes for the vector operations are as follows:ssize_t (*readv) (struct file *filp, const struct iovec *iov,unsigned long count, loff_t *ppos);ssize_t (*writev) (struct file *filp, const struct iovec *iov,unsigned long count, loff_t *ppos);Here, the filp and ppos arguments are the same as for read and write.

Theiovec structure, defined in <linux/uio.h>, looks like this:struct iovec{void *iov_base;_ _kernel_size_t iov_len;};Each iovec describes one chunk of data to be transferred; it starts at iov_base(in user space) and is iov_len bytes long. The count parameter to the methodtells how many iovec structures there are. These structures are created by theapplication, but the kernel copies them into kernel space before calling the driver.The simplest implementation of the vectored operations would be a simple loopthat just passes the address and length out of each iovec to the driver’s read orwrite function. Often, however, efficient and correct behavior requires that thedriver do something smarter.

For example, a writev on a tape drive should writethe contents of all the iovec structures as a single record on the tape.Many drivers, though, will gain no benefit from implementing these methodsthemselves. Thus, scull omits them. The kernel will emulate them with read andwrite, and the end result is the same.8422 June 2001 16:35http://openlib.org.uaThe Device FilesystemPlaying with the New DevicesOnce you are equipped with the four methods just described, the driver can becompiled and tested; it retains any data you write to it until you overwrite it withnew data.

The device acts like a data buffer whose length is limited only by theamount of real RAM available. You can try using cp, dd, and input/output redirection to test the driver.The fr ee command can be used to see how the amount of free memory shrinksand expands according to how much data is written into scull.To get more confident with reading and writing one quantum at a time, you canadd a printk at an appropriate point in the driver and watch what happens whilean application reads or writes large chunks of data. Alternatively, use the straceutility to monitor the system calls issued by a program, together with their returnvalues. Tracing a cp or an ls -l > /dev/scull0 will show quantized reads and writes.Monitoring (and debugging) techniques are presented in detail in the next chapter.The Device FilesystemAs suggested at the beginning of the chapter, recent versions of the Linux kerneloffer a special filesystem for device entry points.

The filesystem has been availablefor a while as an unofficial patch; it was made part of the official source tree in2.3.46. A backport to 2.2 is available as well, although not included in the official2.2 kernels.Although use of the special filesystem is not widespread as we write this, the newfeatures offer a few advantages to the device driver writer. Therefore, our versionof scull exploits devfs if it is being used in the target system. The module uses kernel configuration information at compile time to know whether particular featureshave been enabled, and in this case we depend on CONFIG_DEVFS_FS beingdefined or not.The main advantages of devfs are as follows:•Device entry points in /dev are created at device initialization and removed atdevice removal.•The device driver can specify device names, ownership, and permission bits,but user-space programs can still change ownership and permission (but notthe filename).•There is no need to allocate a major number for the device driver and dealwith minor numbers.As a result, there is no need to run a script to create device special files when amodule is loaded or unloaded, because the driver is autonomous in managing itsown special files.8522 June 2001 16:35http://openlib.org.uaChapter 3: Char DriversTo handle device creation and removal, the driver should call the following functions:#include <linux/devfs_fs_kernel.h>devfs_handle_t devfs_mk_dir (devfs_handle_t dir,const char *name, void *info);devfs_handle_t devfs_register (devfs_handle_t dir,const char *name, unsigned int flags,unsigned int major, unsigned int minor,umode_t mode, void *ops, void *info);void devfs_unregister (devfs_handle_t de);The devfs implementation offers several other functions for kernel code to use.They allow creation of symbolic links, access to the internal data structures toretrieve devfs_handle_t items from inodes, and other tasks.

Those other functions are not covered here because they are not very important or easily understood. The curious reader could look at the header file for further information.The various arguments to the register/unregister functions are as follows:dirThe parent directory where the new special file should be created. Mostdrivers will use NULL to create special files in /dev directly. To create anowned directory, a driver should call devfs_mk_dir.nameThe name of the device, without the leading /dev/. The name can includeslashes if you want the device to be in a subdirectory; the subdirectory is created during the registration process. Alternatively, you can specify a valid dirpointer to the hosting subdirectory.flagsA bit mask of devfs flags.

DEVFS_FL_DEFAULT can be a good choice, andDEVFS_FL_AUTO_DEVNUM is the flag you need for automatic assignment ofmajor and minor numbers. The actual flags are described later.majorminorThe major and minor numbers for theDEVFS_FL_AUTO_DEVNUM is specified in the flags.device.UnusedifmodeAccess mode of the new device.opsA pointer to the file operation structure for the device.8622 June 2001 16:35http://openlib.org.uaThe Device FilesysteminfoA default value for filp->private_data.

The filesystem will initialize thepointer to this value when the device is opened. The info pointer passed todevfs_mk_dir is not used by devfs and acts as a “client data” pointer.de A “devfs entry” obtained by a previous call to devfs_r egister.The flags are used to select specific features to be enabled for the special filebeing created.

Although the flags are briefly and clearly documented in<linux/devfs_fs_kernel.h>, it’s worth introducing some of them.DEVFS_FL_NONEDEVFS_FL_DEFAULTThe former symbol is simply 0, and is suggested for code readability. The latter macro is currently defined to DEVFS_FL_NONE, but is a good choice to beforward compatible with future implementations of the filesystem.DEVFS_FL_AUTO_OWNERThe flag makes the device appear to be owned by the last uid/gid that openedit, and read/write for anybody when no process has it opened. The feature isuseful for tty device files but is also interesting for device drivers to preventconcurrent access to a nonshareable device.

We’ll see access policy issues inChapter 5.DEVFS_FL_SHOW_UNREGDEVFS_FL_HIDEThe former flag requests not to remove the device file from /dev when it isunregistered. The latter requests never to show it in /dev. The flags are notusually needed for normal devices.DEVFS_FL_AUTO_DEVNUMAutomatically allocate a device number for this device. The number willremain associated with the device name even after the devfs entry is unregistered, so if the driver is reloaded before the system is shut down, it willreceive the same major/minor pair.DEVFS_FL_NO_PERSISTENCEDon’t keep track of this entry after it is removed. This flags saves some systemmemory after module removal, at the cost of losing persistence of device features across module unload/reload.

Persistent features are access mode, fileownership, and major/minor numbers.It is possible to query the flags associated with a device or to change them at runtime. The following two functions perform the tasks:int devfs_get_flags (devfs_handle_t de, unsigned int *flags);int devfs_set_flags (devfs_handle_t de, unsigned int flags);8722 June 2001 16:35http://openlib.org.uaChapter 3: Char DriversUsing devfs in PracticeBecause devfs leads to serious user-space incompatibilities as far as device namesare concerned, not all installed systems use it. Independently of how the new feature will be accepted by Linux users, it’s unlikely you’ll write devfs-only driversanytime soon; thus, you’ll need to add support for the “older” way of dealing withfile creation and permission from user space and using major/minor numbers inkernel space.The code needed to implement a device driver that only runs with devfs installedis a subset of the code you need to support both environments, so we only showthe dual-mode initialization.

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

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

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

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