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

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

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

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

sbull calls the necessary function (register_disk) as follows:for (i = 0; i < sbull_devs; i++)register_disk(NULL, MKDEV(major, i), 1, &sbull_bdops,sbull_size << 1);In the 2.4.0 kernel, register_disk does nothing when invoked in this manner. Thereal purpose of register_disk is to set up the partition table, which is not supportedby sbull. All block drivers, however, make this call whether or not they supportpartitions, indicating that it may become necessary for all block devices in thefuture. A block driver without partitions will work without this call in 2.4.0, but itis safer to include it.

We revisit register_disk in detail later in this chapter, when wecover partitions.The cleanup function used by sbull looks like this:for (i=0; i<sbull_devs; i++)fsync_dev(MKDEV(sbull_major, i)); /* flush the devices */unregister_blkdev(major, "sbull");/** Fix up the request queue(s)32722 June 2001 16:41http://openlib.org.uaChapter 12: Loading Block Drivers*/blk_cleanup_queue(BLK_DEFAULT_QUEUE(major));/* Clean up the global arrays */read_ahead[major] = 0;kfree(blk_size[major]);blk_size[major] = NULL;kfree(blksize_size[major]);blksize_size[major] = NULL;kfree(hardsect_size[major]);hardsect_size[major] = NULL;Here, the call to fsync_dev is needed to free all references to the device that thekernel keeps in various caches.

fsync_dev is the implementation of block_fsync,which is the fsync ‘‘method’’ for block devices.The Header File blk.hAll block drivers should include the header file <linux/blk.h>. This file definesmuch of the common code that is used in block drivers, and it provides functionsfor dealing with the I/O request queue.Actually, the blk.h header is quite unusual, because it defines several symbolsbased on the symbol MAJOR_NR, which must be declared by the driver befor e itincludes the header. This convention was developed in the early days of Linux,when all block devices had preassigned major numbers and modular block driverswere not supported.If you look at blk.h, you’ll see that several device-dependent symbols are declaredaccording to the value of MAJOR_NR, which is expected to be known in advance.However, if the major number is dynamically assigned, the driver has no way toknow its assigned number at compile time and cannot correctly define MAJOR_NR.If MAJOR_NR is undefined, blk.h can’t set up some of the macros used with therequest queue.

Fortunately, MAJOR_NR can be defined as an integer variable andall will work fine for add-on block drivers.blk.h makes use of some other predefined, driver-specific symbols as well. Thefollowing list describes the symbols in <linux/blk.h> that must be defined inadvance; at the end of the list, the code used in sbull is shown.MAJOR_NRThis symbol is used to access a few arrays, in particular blk_dev and blksize_size. A custom driver like sbull, which is unable to assign a constantvalue to the symbol, should #define it to the variable holding the majornumber.

For sbull, this is sbull_major.32822 June 2001 16:41http://openlib.org.uaThe Header File blk.hDEVICE_NAMEThe name of the device being created. This string is used in printing errormessages.DEVICE_NR(kdev_t device)This symbol is used to extract the ordinal number of the physical device fromthe kdev_t device number. This symbol is used in turn to declare CURRENT_DEV, which can be used within the request function to determinewhich hardware device owns the minor number involved in a transfer request.The value of this macro can be MINOR(device) or another expression,according to the convention used to assign minor numbers to devices and partitions. The macro should return the same device number for all partitions onthe same physical device—that is, DEVICE_NR represents the disk number,not the partition number.

Partitionable devices are introduced later in thischapter.DEVICE_INTRThis symbol is used to declare a pointer variable that refers to the current bottom-half handler. The macros SET_INTR(intr) and CLEAR_INTR are usedto assign the variable. Using multiple handlers is convenient when the devicecan issue interrupts with different meanings.DEVICE_ON(kdev_t device)DEVICE_OFF(kdev_t device)These macros are intended to help devices that need to perform processingbefore or after a set of transfers is performed; for example, they could be usedby a floppy driver to start the drive motor before I/O and to stop it afterward.Modern drivers no longer use these macros, and DEVICE_ON does not evenget called anymore. Portable drivers, though, should define them (as emptysymbols), or compilation errors will result on 2.0 and 2.2 kernels.DEVICE_NO_RANDOMBy default, the function end_r equest contributes to system entropy (theamount of collected ‘‘randomness’’), which is used by /dev/random.

If thedevice isn’t able to contribute significant entropy to the random device,DEVICE_NO_RANDOM should be defined. /dev/random was introduced in“Installing an Interrupt Handler” in Chapter 9, where SA_SAMPLE_RANDOMwas explained.DEVICE_REQUESTUsed to specify the name of the request function used by the driver. The onlyeffect of defining DEVICE_REQUEST is to cause a forward declaration of therequest function to be done; it is a holdover from older times, and most (orall) drivers can leave it out.32922 June 2001 16:41http://openlib.org.uaChapter 12: Loading Block DriversThe sbull driver declares the symbols in the following way:#define MAJOR_NR sbull_major /* force definitions on in blk.h */static int sbull_major; /* must be declared before including blk.h */#define#define#define#define#define#defineDEVICE_NR(device) MINOR(device)DEVICE_NAME "sbull"DEVICE_INTR sbull_intrptrDEVICE_NO_RANDOMDEVICE_REQUEST sbull_requestDEVICE_OFF(d) /* do-nothing *//*/*/*/*has no partition bits */name for messaging */pointer to bottom half */no entropy to contribute */#include <linux/blk.h>#include "sbull.h"/* local definitions */The blk.h header uses the macros just listed to define some additional macrosusable by the driver.

We’ll describe those macros in the following sections.Handling Requests: A SimpleIntroductionThe most important function in a block driver is the request function, which performs the low-level operations related to reading and writing data. This sectiondiscusses the basic design of the request procedure.The Request QueueWhen the kernel schedules a data transfer, it queues the request in a list, orderedin such a way that it maximizes system performance. The queue of requests isthen passed to the driver’s request function, which has the following prototype:void request_fn(request_queue_t *queue);The request function should perform the following tasks for each request in thequeue:1.Check the validity of the request.

This test is performed by the macroINIT_REQUEST, defined in blk.h; the test consists of looking for problemsthat could indicate a bug in the system’s request queue handling.2.Perform the actual data transfer. The CURRENT variable (a macro, actually) canbe used to retrieve the details of the current request. CURRENT is a pointer tostruct request, whose fields are described in the next section.33022 June 2001 16:41http://openlib.org.uaHandling Requests: A Simple Introduction3.Clean up the request just processed. This operation is performed byend_r equest, a static function whose code resides in blk.h. end_r equest handles the management of the request queue and wakes up processes waitingon the I/O operation. It also manages the CURRENT variable, ensuring that itpoints to the next unsatisfied request.

The driver passes the function a singleargument, which is 1 in case of success and 0 in case of failure. Whenend_r equest is called with an argument of 0, an ‘‘I/O error’’ message is delivered to the system logs (via printk).4.Loop back to the beginning, to consume the next request.Based on the previous description, a minimal request function, which does notactually transfer any data, would look like this:void sbull_request(request_queue_t *q){while(1) {INIT_REQUEST;printk("<1>request %p: cmd %i sec %li (nr. %li)\n", CURRENT,CURRENT->cmd,CURRENT->sector,CURRENT->current_nr_sectors);end_request(1); /* success */}}Although this code does nothing but print messages, running this function provides good insight into the basic design of data transfer.

It also demonstrates acouple of features of the macros defined in <linux/blk.h>. The first is that,although the while loop looks like it will never terminate, the fact is that theINIT_REQUEST macro performs a return when the request queue is empty.The loop thus iterates over the queue of outstanding requests and then returnsfrom the request function. Second, the CURRENT macro always describes therequest to be processed. We get into the details of CURRENT in the next section.A block driver using the request function just shown will actually work—for ashort while. It is possible to make a filesystem on the device and access it for aslong as the data remains in the system’s buffer cache.This empty (but verbose) function can still be run in sbull by defining the symbolSBULL_EMPTY_REQUEST at compile time.

If you want to understand how thekernel handles different block sizes, you can experiment with blksize= on theinsmod command line. The empty request function shows the internal workings ofthe kernel by printing the details of each request.The request function has one very important constraint: it must be atomic. requestis not usually called in direct response to user requests, and it is not running in thecontext of any particular process. It can be called at interrupt time, from tasklets,or from any number of other places. Thus, it must not sleep while carrying out itstasks.33122 June 2001 16:41http://openlib.org.uaChapter 12: Loading Block DriversPerforming the Actual Data TransferTo understand how to build a working request function for sbull, let’s look at howthe kernel describes a request within a struct request.

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

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

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

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