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

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

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

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

Note that dev_t is not defined in kernelmode, and therefore int is used.As long as your code uses these operations to manipulate device numbers, itshould continue to work even as the internal data structures change.6222 June 2001 16:35http://openlib.org.uaFile OperationsFile OperationsIn the next few sections, we’ll look at the various operations a driver can performon the devices it manages. An open device is identified internally by a file structure, and the kernel uses the file_operations structure to access the driver’sfunctions.

The structure, defined in <linux/fs.h>, is an array of function pointers. Each file is associated with its own set of functions (by including a field calledf_op that points to a file_operations structure). The operations are mostly incharge of implementing the system calls and are thus named open, read, and soon. We can consider the file to be an “object” and the functions operating on it tobe its “methods,” using object-oriented programming terminology to denoteactions declared by an object to act on itself. This is the first sign of object-oriented programming we see in the Linux kernel, and we’ll see more in later chapters.Conventionally, a file_operations structure or a pointer to one is called fops(or some variation thereof ); we’ve already seen one such pointer as an argumentto the register_chrdev call.

Each field in the structure must point to the function inthe driver that implements a specific operation, or be left NULL for unsupportedoperations. The exact behavior of the kernel when a NULL pointer is specified isdifferent for each function, as the list later in this section shows.The file_operations structure has been slowly getting bigger as new functionality is added to the kernel. The addition of new operations can, of course,create portability problems for device drivers. Instantiations of the structure ineach driver used to be declared using standard C syntax, and new operations werenormally added to the end of the structure; a simple recompilation of the driverswould place a NULL value for that operation, thus selecting the default behavior,usually what you wanted.Since then, kernel developers have switched to a “tagged” initialization format thatallows initialization of structure fields by name, thus circumventing most problemswith changed data structures.

The tagged initialization, however, is not standard Cbut a (useful) extension specific to the GNU compiler. We will look at an exampleof tagged structure initialization shortly.The following list introduces all the operations that an application can invoke on adevice. We’ve tried to keep the list brief so it can be used as a reference, merelysummarizing each operation and the default kernel behavior when a NULL pointeris used. You can skip over this list on your first reading and return to it later.The rest of the chapter, after describing another important data structure (thefile, which actually includes a pointer to its own file_operations), explainsthe role of the most important operations and offers hints, caveats, and real codeexamples.

We defer discussion of the more complex operations to later chaptersbecause we aren’t ready to dig into topics like memory management, blockingoperations, and asynchronous notification quite yet.6322 June 2001 16:35http://openlib.org.uaChapter 3: Char DriversThe following list shows what operations appear in struct file_operationsfor the 2.4 series of kernels, in the order in which they appear. Although there areminor differences between 2.4 and earlier kernels, they will be dealt with later inthis chapter, so we are just sticking to 2.4 for a while.

The return value of eachoperation is 0 for success or a negative error code to signal an error, unless otherwise noted.loff_t (*llseek) (struct file *, loff_t, int);The llseek method is used to change the current read/write position in a file,and the new position is returned as a (positive) return value. The loff_t is a“long offset” and is at least 64 bits wide even on 32-bit platforms. Errors aresignaled by a negative return value. If the function is not specified for thedriver, a seek relative to end-of-file fails, while other seeks succeed by modifying the position counter in the file structure (described in “The file Structure” later in this chapter).ssize_t (*read) (struct file *, char *, size_t, loff_t *);Used to retrieve data from the device.

A null pointer in this position causes theread system call to fail with -EINVAL (“Invalid argument”). A non-negativereturn value represents the number of bytes successfully read (the return valueis a “signed size” type, usually the native integer type for the target platform).ssize_t (*write) (struct file *, const char *, size_t,loff_t *);Sends data to the device.

If missing, -EINVAL is returned to the program calling the write system call. The return value, if non-negative, represents thenumber of bytes successfully written.int (*readdir) (struct file *, void *, filldir_t);This field should be NULL for device files; it is used for reading directories,and is only useful to filesystems.unsigned int (*poll) (struct file *, structpoll_table_struct *);The poll method is the back end of two system calls, poll and select, both usedto inquire if a device is readable or writable or in some special state.

Eithersystem call can block until a device becomes readable or writable. If a driverdoesn’t define its poll method, the device is assumed to be both readable andwritable, and in no special state. The return value is a bit mask describing thestatus of the device.int (*ioctl) (struct inode *, struct file *, unsigned int,unsigned long);The ioctl system call offers a way to issue device-specific commands (like formatting a track of a floppy disk, which is neither reading nor writing). Additionally, a few ioctl commands are recognized by the kernel without referring6422 June 2001 16:35http://openlib.org.uaFile Operationsto the fops table.

If the device doesn’t offer an ioctl entry point, the systemcall returns an error for any request that isn’t predefined (-ENOTTY, “No suchioctl for device”). If the device method returns a non-negative value, the samevalue is passed back to the calling program to indicate successful completion.int (*mmap) (struct file *, struct vm_area_struct *);mmap is used to request a mapping of device memory to a process’s addressspace. If the device doesn’t implement this method, the mmap system callreturns -ENODEV.int (*open) (struct inode *, struct file *);Though this is always the first operation performed on the device file, thedriver is not required to declare a corresponding method. If this entry is NULL,opening the device always succeeds, but your driver isn’t notified.int (*flush) (struct file *);The flush operation is invoked when a process closes its copy of a filedescriptor for a device; it should execute (and wait for) any outstanding operations on the device.

This must not be confused with the fsync operationrequested by user programs. Currently, flush is used only in the network filesystem (NFS) code. If flush is NULL, it is simply not invoked.int (*release) (struct inode *, struct file *);This operation is invoked when the file structure is being released. Likeopen, release can be missing.*int (*fsync) (struct inode *, struct dentry *, int);This method is the back end of the fsync system call, which a user calls toflush any pending data.

If not implemented in the driver, the system callreturns -EINVAL.int (*fasync) (int, struct file *, int);This operation is used to notify the device of a change in its FASYNC flag.Asynchronous notification is an advanced topic and is described in Chapter 5.The field can be NULL if the driver doesn’t support asynchronous notification.int (*lock) (struct file *, int, struct file_lock *);The lock method is used to implement file locking; locking is an indispensablefeature for regular files, but is almost never implemented by device drivers.ssize_t (*readv) (struct file *, const struct iovec *,unsigned long, loff_t *);ssize_t (*writev) (struct file *, const struct iovec *,unsigned long, loff_t *);* Note that release isn’t invoked every time a process calls close.

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

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

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

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