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

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

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

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

Instead, the system administrator expects to be able to partition the device—to split it into several independent pseudodevices. If you try to create partitions on an sbull device with fdisk,you’ll run into problems. The fdisk program calls the partitions /dev/sbull01,/dev/sbull02, and so on, but those names don’t exist on the filesystem. More to thepoint, there is no mechanism in place for binding those names to partitions in thesbull device.

Something more must be done before a block device can be partitioned.To demonstrate how partitions are supported, we introduce a new device calledspull, a ‘‘Simple Partitionable Utility.’’ It is far simpler than sbull, lacking therequest queue management and some flexibility (like the ability to change thehard-sector size). The device resides in the spull directory and is completelydetached from sbull, even though they share some code.To be able to support partitions on a device, we must assign several minor numbers to each physical device.

One number is used to access the whole device (forexample, /dev/hda), and the others are used to access the various partitions (suchas /dev/hda1). Since fdisk creates partition names by adding a numerical suffix tothe whole-disk device name, we’ll follow the same naming convention in the spulldriver.The device nodes implemented by spull are called pd, for ‘‘partitionable disk.’’ Thefour whole devices (also called units) are thus named /dev/pda through /dev/pdd;each device supports at most 15 partitions. Minor numbers have the followingmeaning: the least significant four bits represent the partition number (where 0 isthe whole device), and the most significant four bits represent the unit number.This convention is expressed in the source file by the following macros:#define MAJOR_NR spull_major /* force definitions on in blk.h */int spull_major; /* must be declared before including blk.h */#define#define#define#defineSPULL_SHIFT 4/* max 16 partitions */SPULL_MAXNRDEV 4/* max 4 device units */DEVICE_NR(device) (MINOR(device)>>SPULL_SHIFT)DEVICE_NAME "pd"/* name for messaging */35522 June 2001 16:41http://openlib.org.uaChapter 12: Loading Block DriversThe spull driver also hardwires the value of the hard-sector size in order to simplify the code:#define SPULL_HARDSECT 512/* 512-byte hardware sectors */The Generic Hard DiskEvery partitionable device needs to know how it is partitioned.

The information isavailable in the partition table, and part of the initialization process consists ofdecoding the partition table and updating the internal data structures to reflect thepartition information.This decoding isn’t easy, but fortunately the kernel offers ‘‘generic hard disk’’ support usable by all block drivers. Such support considerably reduces the amount ofcode needed in the driver for handling partitions. Another advantage of thegeneric support is that the driver writer doesn’t need to understand how the partitioning is done, and new partitioning schemes can be supported in the kernelwithout requiring changes to driver code.A block driver that supports partitions must include <linux/genhd.h> andshould declare a struct gendisk structure.

This structure describes the layoutof the disk(s) provided by the driver; the kernel maintains a global list of suchstructures, which may be queried to see what disks and partitions are available onthe system.Before we go further, let’s look at some of the fields in struct gendisk. You’llneed to understand them in order to exploit generic device support.int majorThe major number for the device that the structure refers to.const char *major_nameThe base name for devices belonging to this major number. Each device nameis derived from this name by adding a letter for each unit and a number foreach partition. For example, ‘‘hd’’ is the base name that is used to build/dev/hda1 and /dev/hdb3.

In modern kernels, the full length of the disk namecan be up to 32 characters; the 2.0 kernel, however, was more restricted.Drivers wishing to be backward portable to 2.0 should limit the major_namefield to five characters. The name for spull is pd (‘‘partitionable disk’’).int minor_shiftThe number of bit shifts needed to extract the drive number from the deviceminor number. In spull the number is 4. The value in this field should be consistent with the definition of the macro DEVICE_NR(device) (see “TheHeader File blk.h”). The macro in spull expands to device>>4.35622 June 2001 16:41http://openlib.org.uaPartitionable Devicesint max_pThe maximum number of partitions.

In our example, max_p is 16, or moregenerally, 1 << minor_shift.struct hd_struct *partThe decoded partition table for the device. The driver uses this item to determine what range of the disk’s sectors is accessible through each minor number. The driver is responsible for allocation and deallocation of this array,which most drivers implement as a static array of max_nr << minor_shiftstructures.

The driver should initialize the array to zeros before the kerneldecodes the partition table.int *sizesAn array of integers with the same information as the global blk_size array.In fact, they are usually the same array. The driver is responsible for allocatingand deallocating the sizes array. Note that the partition check for the devicecopies this pointer to blk_size, so a driver handling partitionable devicesdoesn’t need to allocate the latter array.int nr_realThe number of real devices (units) that exist.void *real_devicesA private area that may be used by the driver to keep any additional requiredinformation.void struct gendisk *nextA pointer used to implement the linked list of generic hard-disk structures.struct block_device_operations *fops;A pointer to the block operations structure for this device.Many of the fields in the gendisk structure are set up at initialization time, so thecompile-time setup is relatively simple:struct gendisk spull_gendisk = {major:0,/* Major number assigned later */major_name:"pd",/* Name of the major device */minor_shift:SPULL_SHIFT, /* Shift to get device number */max_p:1 << SPULL_SHIFT, /* Number of partitions */fops:&spull_bdops, /* Block dev operations *//* everything else is dynamic */};Partition DetectionWhen a module initializes itself, it must set things up properly for partition detection.

Thus, spull starts by setting up the spull_sizes array for the gendisk35722 June 2001 16:41http://openlib.org.uaChapter 12: Loading Block Driversstructure (which also gets stored in blk_size[MAJOR_NR] and in the sizesfield of the gendisk structure) and the spull_partitions array, which holdsthe actual partition information (and gets stored in the part member of thegendisk structure).

Both of these arrays are initialized to zeros at this time. Thecode looks like this:spull_sizes = kmalloc( (spull_devs << SPULL_SHIFT) * sizeof(int),GFP_KERNEL);if (!spull_sizes)goto fail_malloc;/* Start with zero-sized partitions, and correctly sized units */memset(spull_sizes, 0, (spull_devs << SPULL_SHIFT) * sizeof(int));for (i=0; i< spull_devs; i++)spull_sizes[i<<SPULL_SHIFT] = spull_size;blk_size[MAJOR_NR] = spull_gendisk.sizes = spull_sizes;/* Allocate the partitions array. */spull_partitions = kmalloc( (spull_devs << SPULL_SHIFT) *sizeof(struct hd_struct), GFP_KERNEL);if (!spull_partitions)goto fail_malloc;memset(spull_partitions, 0, (spull_devs << SPULL_SHIFT) *sizeof(struct hd_struct));/* fill in whole-disk entries */for (i=0; i < spull_devs; i++)spull_partitions[i << SPULL_SHIFT].nr_sects =spull_size*(blksize/SPULL_HARDSECT);spull_gendisk.part = spull_partitions;spull_gendisk.nr_real = spull_devs;The driver should also include its gendisk structure on the global list.

There isno kernel-supplied function for adding gendisk structures; it must be done byhand:spull_gendisk.next = gendisk_head;gendisk_head = &spull_gendisk;In practice, the only thing the system does with this list is to implement /pr oc/partitions.The register_disk function, which we have already seen briefly, handles the job ofreading the disk’s partition table.register_disk(struct gendisk *gd, int drive, unsigned minors,struct block_device_operations *ops, long size);Here, gd is the gendisk structure that we built earlier, drive is the device number, minors is the number of partitions supported, ops is theblock_device_operations structure for the driver, and size is the size ofthe device in sectors.35822 June 2001 16:41http://openlib.org.uaPartitionable DevicesFixed disks might read the partition table only at module initialization time andwhen BLKRRPART is invoked.

Drivers for removable drives will also need to makethis call in the revalidate method. Either way, it is important to remember that register_disk will call your driver’s request function to read the partition table, so thedriver must be sufficiently initialized at that point to handle requests. You shouldalso not have any locks held that will conflict with locks acquired in the requestfunction. register_disk must be called for each disk actually present on the system.spull sets up partitions in the revalidate method:int spull_revalidate(kdev_t i_rdev){/* first partition, # of partitions */int part1 = (DEVICE_NR(i_rdev) << SPULL_SHIFT) + 1;int npart = (1 << SPULL_SHIFT) -1;/* first clear old partition information */memset(spull_gendisk.sizes+part1, 0, npart*sizeof(int));memset(spull_gendisk.part +part1, 0, npart*sizeof(struct hd_struct));spull_gendisk.part[DEVICE_NR(i_rdev) << SPULL_SHIFT].nr_sects =spull_size << 1;/* then fill new info */printk(KERN_INFO "Spull partition check: (%d) ", DEVICE_NR(i_rdev));register_disk(&spull_gendisk, i_rdev, SPULL_MAXNRDEV, &spull_bdops,spull_size << 1);return 0;}It’s interesting to note that register_disk prints partition information by repeatedlycallingprintk(" %s", disk_name(hd, minor, buf));That’s why spull prints a leading string.

It’s meant to add some context to theinformation that gets stuffed into the system log.When a partitionable module is unloaded, the driver should arrange for all thepartitions to be flushed, by calling fsync_dev for every supported major/minor pair.All of the relevant memory should be freed as well, of course. The cleanup function for spull is as follows:for (i = 0; i < (spull_devs << SPULL_SHIFT); i++)fsync_dev(MKDEV(spull_major, i)); /* flush the devices */blk_cleanup_queue(BLK_DEFAULT_QUEUE(major));read_ahead[major] = 0;kfree(blk_size[major]); /* which is gendisk->sizes as well */blk_size[major] = NULL;kfree(spull_gendisk.part);kfree(blksize_size[major]);blksize_size[major] = NULL;35922 June 2001 16:41http://openlib.org.uaChapter 12: Loading Block DriversIt is also necessary to remove the gendisk structure from the global list.

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

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

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

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