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

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

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

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

SA_INTERRUPT requests installation of a fast handler(as opposed to a slow one). SA_SHIRQ installs a shared handler, and the thirdflag asserts that interrupt timestamps can be used to generate system entropy./proc/interrupts/proc/statThese filesystem nodes are used to report information about hardware interrupts and installed handlers.unsigned long probe_irq_on(void);int probe_irq_off(unsigned long);These functions are used by the driver when it has to probe to determinewhat interrupt line is being used by a device.

The result of pr obe_irq_on mustbe passed back to pr obe_irq_off after the interrupt has been generated. Thereturn value of pr obe_irq_off is the detected interrupt number.28922 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt Handlingvoid disable_irq(int irq);void disable_irq_nosync(int irq);void enable_irq(int irq);A driver can enable and disable interrupt reporting. If the hardware tries togenerate an interrupt while interrupts are disabled, the interrupt is lost forever.A driver using a shared handler must not use these functions.DECLARE_TASKLET(name, function, arg);tasklet_schedule(struct tasklet_struct *);Utilities for dealing with tasklets.

DECLARE_TASKLET declares a tasklet withthe given name; when run, the given function will be called with arg. Usetasklet_schedule to schedule a tasklet for execution.#include <linux/interrupt.h>void mark_bh(int nr);This function marks a bottom half for execution.#include <linux/spinlock.h>spinlock_t my_lock = SPINLOCK_UNLOCKED;spin_lock_init(spinlock_t *lock);spin_lock(spinlock_t *lock);spin_lock_irqsave(spinlock_t *lock, unsigned long flags);spin_lock_irq(spinlock_t *lock);spin_lock_bh(spinlock_t *lock);spin_unlock(spinlock_t *lock);spin_unlock_irqrestore(spinlock_t *lock, unsigned longflags);spin_unlock_irq(spinlock_t *lock);spin_unlock_bh(spinlock_t *lock);spin_is_locked(spinlock_t *lock);spin_trylock(spinlock_t *lock)spin_unlock_wait(spinlock_t *lock);Various utilities for using spinlocks.rwlock_t my_lock = RW_LOCK_UNLOCKED;read_lock(rwlock_t *lock);read_lock_irqsave(rwlock_t *lock, unsigned long flags);read_lock_irq(rwlock_t *lock);read_lock_bh(rwlock_t *lock);read_unlock(rwlock_t *lock);read_unlock_irqrestore(rwlock_t *lock, unsigned long flags);read_unlock_irq(rwlock_t *lock);read_unlock_bh(rwlock_t *lock);29022 June 2001 16:39http://openlib.org.uaQuick Referencewrite_lock(rwlock_t *lock);write_lock_irqsave(rwlock_t *lock, unsigned long flags);write_lock_irq(rwlock_t *lock);write_lock_bh(rwlock_t *lock);write_unlock(rwlock_t *lock);write_unlock_irqrestore(rwlock_t *lock, unsigned longflags);write_unlock_irq(rwlock_t *lock);write_unlock_bh(rwlock_t *lock);The variations on locking and unlocking for reader-writer spinlocks.#include <asm/bitops.h>void set_bit(nr, void *addr);void clear_bit(nr, void *addr);void change_bit(nr, void *addr);test_bit(nr, void *addr);int test_and_set_bit(nr, void *addr);int test_and_clear_bit(nr, void *addr);int test_and_change_bit(nr, void *addr);These functions atomically access bit values; they can be used for flags or lockvariables.

Using these functions prevents any race condition related to concurrent access to the bit.#include <asm/atomic.h>void atomic_add(atomic_t i, atomic_t *v);void atomic_sub(atomic_t i, atomic_t *v);void atomic_inc(atomic_t *v);void atomic_dec(atomic_t *v);int atomic_dec_and_test(atomic_t *v);These functions atomically access integer variables. To achieve a clean compile, the atomic_t variables must be accessed only through these functions.#include <linux/sched.h>TASK_RUNNINGTASK_INTERRUPTIBLETASK_UNINTERRUPTIBLEThe most commonly used values for the state of the current task.

They areused as hints for schedule.set_current_state(int state);Sets the current task state to the given value.29122 June 2001 16:39http://openlib.org.uaChapter 9: Interrupt Handlingvoid add_wait_queue(struct wait_queue ** p, structwait_queue * wait)void remove_wait_queue(struct wait_queue ** p, structwait_queue * wait)void _ _add_wait_queue(struct wait_queue ** p, structwait_queue * wait)void _ _remove_wait_queue(struct wait_queue ** p, structwait_queue * wait)The lowest-level functions that use wait queues.

The leading underscores indicate a lower-level functionality. In this case, interrupt reporting must alreadybe disabled in the processor.wait_event(wait_queue_head_t queue, condition);wait_event_interruptible(wait_queue_head_t queue, condition);These macros wait on the given queue until the given condition evaluatestrue.29222 June 2001 16:39http://openlib.org.uaCHAPTER TENJUDICIOUS USE OFDATA TYPESBefore we go on to more advanced topics, we need to stop for a quick note onportability issues. Modern versions of the Linux kernel are highly portable, runningon several very different architectures. Given the multiplatform nature of Linux,drivers intended for serious use should be portable as well.But a core issue with kernel code is being able both to access data items ofknown length (for example, filesystem data structures or registers on deviceboards) and to exploit the capabilities of different processors (32-bit and 64-bitarchitectures, and possibly 16 bit as well).Several of the problems encountered by kernel developers while porting x86 codeto new architectures have been related to incorrect data typing.

Adherence to strictdata typing and compiling with the -Wall -Wstrict-prototypes flags can preventmost bugs.Data types used by kernel data are divided into three main classes: standard Ctypes such as int, explicitly sized types such as u32, and types used for specifickernel objects, such as pid_t.

We are going to see when and how each of thethree typing classes should be used. The final sections of the chapter talk aboutsome other typical problems you might run into when porting driver code fromthe x86 to other platforms, and introduce the generalized support for linked listsexported by recent kernel headers.If you follow the guidelines we provide, your driver should compile and run evenon platforms on which you are unable to test it.Use of Standard C TypesAlthough most programmers are accustomed to freely using standard types likeint and long, writing device drivers requires some care to avoid typing conflictsand obscure bugs.29322 June 2001 16:40http://openlib.org.uaChapter 10: Judicious Use of Data TypesThe problem is that you can’t use the standard types when you need ‘‘a two-bytefiller’’ or ‘‘something representing a four-byte string’’ because the normal C datatypes are not the same size on all architectures.

To show the data size of the various C types, the datasize program has been included in the sample files providedon the O’Reilly FTP site, in the directory misc-pr ogs. This is a sample run of theprogram on a PC (the last four types shown are introduced in the next section):morgana% misc-progs/datasizearchSize: char shorinti686124long4ptr long-long48u8 u16 u32 u641248The program can be used to show that long integers and pointers feature a different size on 64-bit platforms, as demonstrated by running the program on differentLinux computers:archSize:i386alphaarmv4lia64m68kmipsppcsparcsparc64char111111111shor222222222int444444444long484844444ptr long-long488848884848484848u8 u16 u32 u64124812481248124812481248124812481248It’s interesting to note that the user space of Linux-sparc64 runs 32-bit code, sopointers are 32 bits wide in user space, even though they are 64 bits wide in kernel space. This can be verified by loading the kdatasize module (available in thedirectory misc-modules within the sample files).

The module reports size information at load time using printk and returns an error (so there’s no need to unloadit):kernel: archSize:kernel: sparc64char short int long1248ptr long-long u8 u16 u32 u64881248Although you must be careful when mixing different data types, sometimes thereare good reasons to do so. One such situation is for memory addresses, which arespecial as far as the kernel is concerned. Although conceptually addresses arepointers, memory administration is better accomplished by using an unsigned integer type; the kernel treats physical memory like a huge array, and a memoryaddress is just an index into the array. Furthermore, a pointer is easily dereferenced; when dealing directly with memory addresses you almost never want todereference them in this manner.

Using an integer type prevents this dereferencing, thus avoiding bugs. Therefore, addresses in the kernel are unsigned long,exploiting the fact that pointers and long integers are always the same size, atleast on all the platforms currently supported by Linux.29422 June 2001 16:40http://openlib.org.uaAssigning an Explicit Size to Data ItemsThe C99 standard defines the intptr_t and uintptr_t types for an integervariable which can hold a pointer value. These types are almost unused in the 2.4kernel, but it would not be surprising to see them show up more often as a resultof future development work.Assigning an Explicit Size to Data ItemsSometimes kernel code requires data items of a specific size, either to match predefined binary structures* or to align data within structures by inserting ‘‘filler’’fields (but please refer to “Data Alignment” later in this chapter for informationabout alignment issues).The kernel offers the following data types to use whenever you need to know thesize of your data.

All the types are declared in <asm/types.h>, which in turn isincluded by <linux/types.h>:u8;u16;u32;u64;/*/*/*/*unsignedunsignedunsignedunsignedbyte (8 bits) */word (16 bits) */32-bit value */64-bit value */These data types are accessible only from kernel code (i.e., _ _KERNEL_ _ mustbe defined before including <linux/types.h>).

The corresponding signedtypes exist, but are rarely needed; just replace u with s in the name if you needthem.If a user-space program needs to use these types, it can prefix the names with adouble underscore: _ _u8 and the other types are defined independent of_ _KERNEL_ _. If, for example, a driver needs to exchange binary structures witha program running in user space by means of ioctl, the header files should declare32-bit fields in the structures as _ _u32.It’s important to remember that these types are Linux specific, and using them hinders porting software to other Unix flavors.

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

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

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

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