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

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

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

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

_IOC_SIZEBITS is an importantvalue to check, because it changes across architectures._IOC_NONE_IOC_READ_IOC_WRITEThe possible values for the ‘‘direction’’ bitfield. ‘‘Read’’ and ‘‘write’’ are different bits and can be OR’d to specify read/write. The values are 0 based._IOC(dir,type,nr,size)_IO(type,nr)_IOR(type,nr,size)_IOW(type,nr,size)_IOWR(type,nr,size)Macros used to create an ioctl command._IOC_DIR(nr)_IOC_TYPE(nr)_IOC_NR(nr)_IOC_SIZE(nr)Macros used to decode a command. In particular, _IOC_TYPE(nr) is an ORcombination of _IOC_READ and _IOC_WRITE.#include <asm/uaccess.h>int access_ok(int type, const void *addr, unsigned longsize);This function checks that a pointer to user space is actually usable. access_okreturns a nonzero value if the access should be allowed.17722 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver OperationsVERIFY_READVERIFY_WRITEThe possible values for the type argument in access_ok.

VERIFY_WRITE is asuperset of VERIFY_READ.#include <asm/uaccess.h>int put_user(datum,ptr);int get_user(local,ptr);int _ _put_user(datum,ptr);int _ _get_user(local,ptr);Macros used to store or retrieve a datum to or from user space. The number ofbytes being transferred depends on sizeof(*ptr). The regular versions callaccess_ok first, while the qualified versions (_ _put_user and _ _get_user)assume that access_ok has already been called.#include <linux/capability.h>Defines the various CAP_ symbols for capabilities under Linux 2.2 and later.int capable(int capability);Returns nonzero if the process has the given capability.#include <linux/wait.h>typedef struct { /* .

. . */ } wait_queue_head_t;void init_waitqueue_head(wait_queue_head_t *queue);DECLARE_WAIT_QUEUE_HEAD(queue);The defined type for Linux wait queues. A wait_queue_head_t must beexplicitly initialized with either init_waitqueue_head at runtime ordeclar e_wait_queue_head at compile time.#include <linux/sched.h>void interruptible_sleep_on(wait_queue_head_t *q);void sleep_on(wait_queue_head_t *q);void interruptible_sleep_on_timeout(wait_queue_head_t *q,long timeout);void sleep_on_timeout(wait_queue_head_t *q, long timeout);Calling any of these functions puts the current process to sleep on a queue.Usually, you’ll choose the interruptible form to implement blocking read andwrite.void wake_up(struct wait_queue **q);void wake_up_interruptible(struct wait_queue **q);void wake_up_sync(struct wait_queue **q);void wake_up_interruptible_sync(struct wait_queue **q);These functions wake processes that are sleeping on the queue q.

The _interruptible form wakes only interruptible processes. The _sync versions will notreschedule the CPU before returning.17822 June 2001 16:36http://openlib.org.uaQuick Referencetypedef struct { /* . . . */ } wait_queue_t;init_waitqueue_entry(wait_queue_t *entry, struct task_struct*task);The wait_queue_t type is used when sleeping without calling sleep_on.Wait queue entries must be initialized prior to use; the task argument used isalmost always current.void add_wait_queue(wait_queue_head_t *q, wait_queue_t*wait);void add_wait_queue_exclusive(wait_queue_head_t *q,wait_queue_t *wait);void remove_wait_queue(wait_queue_head_t *q, wait_queue_t*wait);These functions add an entry to a wait queue; add_wait_queue_exclusive addsthe entry to the end of the queue for exclusive waits.

Entries should beremoved from the queue after sleeping with remove_wait_queue.void wait_event(wait_queue_head_t q, int condition);int wait_event_interruptible(wait_queue_head_t q, int condition);These two macros will cause the process to sleep on the given queue until thegiven condition evaluates to a true value.void schedule(void);This function selects a runnable process from the run queue. The chosen process can be current or a different one. You won’t usually call scheduledirectly, because the sleep_on functions do it internally.#include <linux/poll.h>void poll_wait(struct file *filp, wait_queue_head_t *q,poll_table *p)This function puts the current process into a wait queue without schedulingimmediately. It is designed to be used by the poll method of device drivers.int fasync_helper(struct inode *inode, struct file *filp,int mode, struct fasync_struct **fa);This function is a ‘‘helper’’ for implementing the fasync device method.

Themode argument is the same value that is passed to the method, while fapoints to a device-specific fasync_struct *.void kill_fasync(struct fasync_struct *fa, int sig, intband);If the driver supports asynchronous notification, this function can be used tosend a signal to processes registered in fa.17922 June 2001 16:36http://openlib.org.uaChapter 5: Enhanced Char Driver Operations#include <linux/spinlock.h>typedef struct { /* . . .

*/ } spinlock_t;void spin_lock_init(spinlock_t *lock);The spinlock_t type defines a spinlock, which must be initialized (withspin_lock_init) prior to use.spin_lock(spinlock_t *lock);spin_unlock(spinlock_t *lock);spin_lock locks the given lock, perhaps waiting until it becomes available. Thelock can then be released with spin_unlock.18022 June 2001 16:36http://openlib.org.uaCHAPTER SIXFLOW OF TIMEAt this point, we know the basics of how to write a full-featured char module.Real-world drivers, however, need to do more than implement the necessary operations; they have to deal with issues such as timing, memory management, hardware access, and more. Fortunately, the kernel makes a number of facilitiesavailable to ease the task of the driver writer.

In the next few chapters we’ll fill ininformation on some of the kernel resources that are available, starting with howtiming issues are addressed. Dealing with time involves the following, in order ofincreasing complexity:•Understanding kernel timing•Knowing the current time•Delaying operation for a specified amount of time•Scheduling asynchronous functions to happen after a specified time lapseTime Intervals in the KernelThe first point we need to cover is the timer interrupt, which is the mechanism thekernel uses to keep track of time intervals.

Interrupts are asynchronous events thatare usually fired by external hardware; the CPU is interrupted in its current activityand executes special code (the Interrupt Service Routine, or ISR) to serve the interrupt. Interrupts and ISR implementation issues are covered in Chapter 9.Timer interrupts are generated by the system’s timing hardware at regular intervals;this interval is set by the kernel according to the value of HZ, which is an18122 June 2001 16:37http://openlib.org.uaChapter 6: Flow of Timearchitecture-dependent value defined in <linux/param.h>. Current Linux versions define HZ to be 100 for most platforms, but some platforms use 1024, andthe IA-64 simulator uses 20.

Despite what your preferred platform uses, no driverwriter should count on any specific value of HZ.Every time a timer interrupt occurs, the value of the variable jiffies is incremented. jiffies is initialized to 0 when the system boots, and is thus the number of clock ticks since the computer was turned on. It is declared in<linux/sched.h> as unsigned long volatile, and will possibly overflowafter a long time of continuous system operation (but no platform features jiffyoverflow in less than 16 months of uptime). Much effort has gone into ensuringthat the kernel operates properly when jiffies overflows.

Driver writers do notnormally have to worry about jiffies overflows, but it is good to be aware ofthe possibility.It is possible to change the value of HZ for those who want systems with a different clock interrupt frequency. Some people using Linux for hard real-time taskshave been known to raise the value of HZ to get better response times; they arewilling to pay the overhead of the extra timer interrupts to achieve their goals. Allin all, however, the best approach to the timer interrupt is to keep the defaultvalue for HZ, by virtue of our complete trust in the kernel developers, who havecertainly chosen the best value.Processor-Specific RegistersIf you need to measure very short time intervals or you need extremely high precision in your figures, you can resort to platform-dependent resources, selecting precision over portability.Most modern CPUs include a high-resolution counter that is incremented everyclock cycle; this counter may be used to measure time intervals precisely.

Giventhe inherent unpredictability of instruction timing on most systems (due to instruction scheduling, branch prediction, and cache memory), this clock counter is theonly reliable way to carry out small-scale timekeeping tasks. In response to theextremely high speed of modern processors, the pressing demand for empiricalperformance figures, and the intrinsic unpredictability of instruction timing in CPUdesigns caused by the various levels of cache memories, CPU manufacturers introduced a way to count clock cycles as an easy and reliable way to measure timelapses. Most modern processors thus include a counter register that is steadilyincremented once at each clock cycle.The details differ from platform to platform: the register may or may not be readable from user space, it may or may not be writable, and it may be 64 or 32 bitswide — in the latter case you must be prepared to handle overflows.

Whether ornot the register can be zeroed, we strongly discourage resetting it, even when18222 June 2001 16:37http://openlib.org.uaTime Intervals in the Kernelhardware permits. Since you can always measure differences using unsigned variables, you can get the work done without claiming exclusive ownership of theregister by modifying its current value.The most renowned counter register is the TSC (timestamp counter), introduced inx86 processors with the Pentium and present in all CPU designs ever since.

It is a64-bit register that counts CPU clock cycles; it can be read from both kernel spaceand user space.After including <asm/msr.h> (for ‘‘machine-specific registers’’), you can use oneof these macros:rdtsc(low,high);rdtscl(low);The former atomically reads the 64-bit value into two 32-bit variables; the latterreads the low half of the register into a 32-bit variable and is sufficient in mostcases.

For example, a 500-MHz system will overflow a 32-bit counter once every8.5 seconds; you won’t need to access the whole register if the time lapse you arebenchmarking reliably takes less time.These lines, for example, measure the execution of the instruction itself:unsigned long ini, end;rdtscl(ini); rdtscl(end);printk("time lapse: %li\n", end - ini);Some of the other platforms offer similar functionalities, and kernel headers offeran architecture-independent function that you can use instead of rdtsc. It is calledget_cycles, and was introduced during 2.1 development.

Its prototype is#include <linux/timex.h>cycles_t get_cycles(void);The function is defined for every platform, and it always returns 0 on the platforms that have no cycle-counter register. The cycles_t type is an appropriateunsigned type that can fit in a CPU register. The choice to fit the value in a singleregister means, for example, that only the lower 32 bits of the Pentium cyclecounter are returned by get_cycles. The choice is a sensible one because it avoidsthe problems with multiregister operations while not preventing most commonuses of the counter—namely, measuring short time lapses.Despite the availability of an architecture-independent function, we’d like to takethe chance to show an example of inline assembly code.

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

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

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

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