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

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

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

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

At the same time, no otheruser can open it, thus avoiding external interference. Since this version of thefunction is almost identical to the preceding one, only the relevant part is reproduced here:spin_lock(&scull_u_lock);if (scull_u_count &&(scull_u_owner != current->uid) && /* allow user */(scull_u_owner != current->euid) && /* allow whoever did su */16722 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver Operations!capable(CAP_DAC_OVERRIDE)) { /* still allow root */spin_unlock(&scull_u_lock);return -EBUSY; /* -EPERM would confuse the user */}if (scull_u_count == 0)scull_u_owner = current->uid; /* grab it */scull_u_count++;spin_unlock(&scull_u_lock);We chose to return -EBUSY and not -EPERM, even though the code is performinga permission check, in order to point a user who is denied access in the rightdirection.

The reaction to ‘‘Permission denied’’ is usually to check the mode andowner of the /dev file, while ‘‘Device busy’’ correctly suggests that the user shouldlook for a process already using the device.This code also checks to see if the process attempting the open has the ability tooverride file access permissions; if so, the open will be allowed even if the opening process is not the owner of the device. The CAP_DAC_OVERRIDE capabilityfits the task well in this case.The code for close is not shown, since all it does is decrement the usage count.Blocking open as an Alternative to EBUSYWhen the device isn’t accessible, returning an error is usually the most sensibleapproach, but there are situations in which you’d prefer to wait for the device.For example, if a data communication channel is used both to transmit reports ona timely basis (using cr ontab) and for casual usage according to people’s needs,it’s much better for the timely report to be slightly delayed rather than fail justbecause the channel is currently busy.This is one of the choices that the programmer must make when designing adevice driver, and the right answer depends on the particular problem beingsolved.The alternative to EBUSY, as you may have guessed, is to implement blockingopen.The scullwuid device is a version of sculluid that waits for the device on openinstead of returning -EBUSY.

It differs from sculluid only in the following part ofthe open operation:spin_lock(&scull_w_lock);while (scull_w_count &&(scull_w_owner != current->uid) && /* allow user */(scull_w_owner != current->euid) && /* allow whoever did su */!capable(CAP_DAC_OVERRIDE)) {spin_unlock(&scull_w_lock);16822 June 2001 16:36http://openlib.org.uaAccess Control on a Device Fileif (filp->f_flags & O_NONBLOCK) return -EAGAIN;interruptible_sleep_on(&scull_w_wait);if (signal_pending(current)) /* a signal arrived */return -ERESTARTSYS; /* tell the fs layer to handle it *//* else, loop */spin_lock(&scull_w_lock);}if (scull_w_count == 0)scull_w_owner = current->uid; /* grab it */scull_w_count++;spin_unlock(&scull_w_lock);The implementation is based once again on a wait queue. Wait queues were created to maintain a list of processes that sleep while waiting for an event, so they fitperfectly here.The release method, then, is in charge of awakening any pending process:int scull_w_release(struct inode *inode, struct file *filp){scull_w_count--;if (scull_w_count == 0)wake_up_interruptible(&scull_w_wait); /* awaken other uid’s */MOD_DEC_USE_COUNT;return 0;}The problem with a blocking-open implementation is that it is really unpleasantfor the interactive user, who has to keep guessing what is going wrong.

The interactive user usually invokes precompiled commands such as cp and tar and can’tjust add O_NONBLOCK to the open call. Someone who’s making a backup usingthe tape drive in the next room would prefer to get a plain ‘‘device or resourcebusy’’ message instead of being left to guess why the hard drive is so silent todaywhile tar is scanning it.This kind of problem (different, incompatible policies for the same device) is bestsolved by implementing one device node for each access policy. An example ofthis practice can be found in the Linux tape driver, which provides multiple devicefiles for the same device. Different device files will, for example, cause the drive torecord with or without compression, or to automatically rewind the tape when thedevice is closed.Cloning the Device on OpenAnother technique to manage access control is creating different private copies ofthe device depending on the process opening it.16922 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver OperationsClearly this is possible only if the device is not bound to a hardware object; scull isan example of such a ‘‘software’’ device.

The internals of /dev/tty use a similartechnique in order to give its process a different ‘‘view’’ of what the /dev entrypoint represents. When copies of the device are created by the software driver, wecall them virtual devices—just as virtual consoles use a single physical tty device.Although this kind of access control is rarely needed, the implementation can beenlightening in showing how easily kernel code can change the application’s perspective of the surrounding world (i.e., the computer).

The topic is quite exotic,actually, so if you aren’t interested, you can jump directly to the next section.The /dev/scullpriv device node implements virtual devices within the scull package. The scullpriv implementation uses the minor number of the process’s controlling tty as a key to access the virtual device. You can nonetheless easily modify thesources to use any integer value for the key; each choice leads to a different policy. For example, using the uid leads to a different virtual device for each user,while using a pid key creates a new device for each process accessing it.The decision to use the controlling terminal is meant to enable easy testing of thedevice using input/output redirection: the device is shared by all commands runon the same virtual terminal and is kept separate from the one seen by commandsrun on another terminal.The open method looks like the following code.

It must look for the right virtualdevice and possibly create one. The final part of the function is not shownbecause it is copied from the bare scull, which we’ve already seen./* The clone-specific data structure includes a key field */struct scull_listitem {Scull_Dev device;int key;struct scull_listitem *next;};/* The list of devices, and a lock to protect it */struct scull_listitem *scull_c_head;spinlock_t scull_c_lock;/* Look for a device or create one if missing */static Scull_Dev *scull_c_lookfor_device(int key){struct scull_listitem *lptr, *prev = NULL;for (lptr = scull_c_head; lptr && (lptr->key != key); lptr = lptr->next)prev=lptr;if (lptr) return &(lptr->device);/* not found */lptr = kmalloc(sizeof(struct scull_listitem), GFP_ATOMIC);if (!lptr) return NULL;17022 June 2001 16:36http://openlib.org.uaAccess Control on a Device File/* initialize the device */memset(lptr, 0, sizeof(struct scull_listitem));lptr->key = key;scull_trim(&(lptr->device)); /* initialize it */sema_init(&(lptr->device.sem), 1);/* place it in the list */if (prev) prev->next = lptr;elsescull_c_head = lptr;return &(lptr->device);}int scull_c_open(struct inode *inode, struct file *filp){Scull_Dev *dev;int key, num = NUM(inode->i_rdev);if (!filp->private_data && num > 0)return -ENODEV; /* not devfs: allow 1 device only */if (!current->tty) {PDEBUG("Process \"%s\" has no ctl tty\n",current->comm);return -EINVAL;}key = MINOR(current->tty->device);/* look for a scullc device in the list */spin_lock(&scull_c_lock);dev = scull_c_lookfor_device(key);spin_unlock(&scull_c_lock);if (!dev) return -ENOMEM;/* then, everything else is copied from the bare scull device */The release method does nothing special.

It would normally release the device onlast close, but we chose not to maintain an open count in order to simplify thetesting of the driver. If the device were released on last close, you wouldn’t beable to read the same data after writing to the device unless a background processwere to keep it open. The sample driver takes the easier approach of keeping thedata, so that at the next open, you’ll find it there. The devices are released whenscull_cleanup is called.Here’s the release implementation for /dev/scullpriv, which closes the discussion ofdevice methods.int scull_c_release(struct inode *inode, struct file *filp){/** Nothing to do, because the device is persistent.* A ‘real’ cloned device should be freed on last close17122 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver Operations*/MOD_DEC_USE_COUNT;return 0;}Backward CompatibilityMany parts of the device driver API covered in this chapter have changed betweenthe major kernel releases.

For those of you needing to make your driver work withLinux 2.0 or 2.2, here is a quick rundown of the differences you will encounter.Wait Queues in Linux 2.2 and 2.0A relatively small amount of the material in this chapter changed in the 2.3 development cycle. The one significant change is in the area of wait queues. The 2.2kernel had a different and simpler implementation of wait queues, but it lackedsome important features, such as exclusive sleeps. The new implementation ofwait queues was introduced in kernel version 2.3.1.The 2.2 wait queue implementation used variables of the type structwait_queue * instead of wait_queue_head_t.

This pointer had to be initialized to NULL prior to its first use. A typical declaration and initialization of a waitqueue looked like this:struct wait_queue *my_queue = NULL;The variousexception ofworks for allis part of thefunctions for sleeping and waking up looked the same, with thethe variable type for the queue itself.

As a result, writing code that2.x kernels is easily done with a bit of code like the following, whichsysdep.h header we use to compile our sample code.# define DECLARE_WAIT_QUEUE_HEAD(head) struct wait_queue *head = NULLtypedef struct wait_queue *wait_queue_head_t;# define init_waitqueue_head(head) (*(head)) = NULLThe synchronous versions of wake_up were added in 2.3.29, and sysdep.h provides macros with the same names so that you can use the feature in your codewhile maintaining portability. The replacement macros expand to normalwake_up, since the underlying mechanisms were missing from earlier kernels. Thetimeout versions of sleep_on were added in kernel 2.1.127.

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

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

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

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