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

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

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

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

The Linux kernel defines a set of macros that handle conversionsbetween the processor’s byte ordering and that of the data you need to store orload in a specific byte order. For example:u32 _ _cpu_to_le32 (u32);u32 _ _le32_to_cpu (u32);These two macros convert a value from whatever the CPU uses to an unsigned, little-endian, 32-bit quantity and back. They work whether your CPU is big-endian29822 June 2001 16:40http://openlib.org.uaOther Portability Issuesor little-endian, and, for that matter, whether it is a 32-bit processor or not. Theyreturn their argument unchanged in cases where there is no work to be done. Useof these macros makes it easy to write portable code without having to use a lot ofconditional compilation constructs.There are dozens of similar routines; you can see the full list in <linux/byteorder/big_endian.h> and <linux/byteorder/little_endian.h>.After a while, the pattern is not hard to follow.

_ _be64_to_cpu converts anunsigned, big-endian, 64-bit value to the internal CPU representation._ _le16_to_cpus, instead, handles signed, little-endian, 16-bit quantities. When dealing with pointers, you can also use functions like _ _cpu_to_le32p, which take apointer to the value to be converted rather than the value itself.

See the includefile for the rest.Not all Linux versions defined all the macros that deal with byte ordering. In particular, the linux/byteorder directory appeared in version 2.1.72 to make order inthe various <asm/byteorder.h> files and remove duplicate definitions. If youuse our sysdep.h, you’ll be able to use all of the macros available in Linux 2.4when compiling code for 2.0 or 2.2.Data AlignmentThe last problem worth considering when writing portable code is how to accessunaligned data—for example, how to read a four-byte value stored at an addressthat isn’t a multiple of four bytes.

PC users often access unaligned data items, butfew architectures permit it. Most modern architectures generate an exception everytime the program tries unaligned data transfers; data transfer is handled by theexception handler, with a great performance penalty. If you need to accessunaligned data, you should use the following macros:#include <asm/unaligned.h>get_unaligned(ptr);put_unaligned(val, ptr);These macros are typeless and work for every data item, whether it’s one, two,four, or eight bytes long. They are defined with any kernel version.Another issue related to alignment is portability of data structures across platforms.The same data structure (as defined in the C-language source file) can be compiled differently on different platforms.

The compiler arranges structure fields tobe aligned according to conventions that differ from platform to platform. At leastin theory, the compiler can even reorder structure fields in order to optimize memory usage.** Field reordering doesn’t happen in currently supported architectures because it couldbreak interoperability with existing code, but a new architecture may define field reordering rules for structures with holes due to alignment restrictions.29922 June 2001 16:40http://openlib.org.uaChapter 10: Judicious Use of Data TypesIn order to write data structures for data items that can be moved across architectures, you should always enforce natural alignment of the data items in addition tostandardizing on a specific endianness.

Natural alignment means storing dataitems at an address that is a multiple of their size (for instance, 8-byte items go inan address multiple of 8). To enforce natural alignment while preventing the compiler from moving fields around, you should use filler fields that avoid leavingholes in the data structure.To show how alignment is enforced by the compiler, the dataalign program is distributed in the misc-pr ogs directory of the sample code, and an equivalentkdataalign module is part of misc-modules. This is the output of the program onseveral platforms and the output of the module on the SPARC64:arch Align:i386i686alphaarmv4lia64mipsppcsparcsparc64char111111111short222222222int444444444long448484444ptr long-long444488448848484848kernel: arch Align: char short int longkernel: sparc641248u8 u16 u32 u64124412441248124412481248124812481248ptr long-long u8 u16 u32 u64881248It’s interesting to note that not all platforms align 64-bit values on 64-bit boundaries, so you’ll need filler fields to enforce alignment and ensure portability.Linked ListsOperating system kernels, like many other programs, often need to maintain listsof data structures.

The Linux kernel has, at times, been host to several linked listimplementations at the same time. To reduce the amount of duplicated code, thekernel developers have created a standard implementation of circular, doublylinked lists; others needing to manipulate lists are encouraged to use this facility,introduced in version 2.1.45 of the kernel.To use the list mechanism, your driver must include the file <linux/list.h>.This file defines a simple structure of type list_head:struct list_head {struct list_head *next, *prev;};Linked lists used in real code are almost invariably made up of some type of structure, each one describing one entry in the list. To use the Linux list facility in your30022 June 2001 16:40http://openlib.org.uaLinked Listscode, you need only embed a list_head inside the structures that make up thelist. If your driver maintains a list of things to do, say, its declaration would looksomething like this:struct todo_struct {struct list_head list;int priority; /* driver specific *//* ...

add other driver-specific fields */};The head of the list must be a standalone list_head structure. List heads mustbe initialized prior to use with the INIT_LIST_HEAD macro. A ‘‘things to do’’ listhead could be declared and initialized with:struct list_head todo_list;INIT_LIST_HEAD(&todo_list);Alternatively, lists can be initialized at compile time as follows:LIST_HEAD(todo_list);Several functions are defined in <linux/list.h> that work with lists:list_add(struct list_head *new, struct list_head *head);This function adds the new entry immediately after the list head—normally atthe beginning of the list.

It can thus be used to build stacks. Note, however,that the head need not be the nominal head of the list; if you pass alist_head structure that happens to be in the middle of the list somewhere,the new entry will go immediately after it. Since Linux lists are circular, thehead of the list is not generally different from any other entry.list_add_tail(struct list_head *new, struct list_head*head);Add a new entry just before the given list head—at the end of the list, in otherwords.

list_add_tail can thus be used to build first-in first-out queues.list_del(struct list_head *entry);The given entry is removed from the list.list_empty(struct list_head *head);Returns a nonzero value if the given list is empty.list_splice(struct list_head *list, struct list_head *head);This function joins two lists by inserting list immediately after head.The list_head structures are good for implementing a list of like structures, butthe invoking program is usually more interested in the larger structures that make30122 June 2001 16:40http://openlib.org.uaChapter 10: Judicious Use of Data Typesup the list as a whole.

A macro, list_entry, is provided that will map a list_headstructure pointer back into a pointer to the structure that contains it. It is invokedas follows:list_entry(struct list_head *ptr, type_of_struct, field_name);where ptr is a pointer to the struct list_head being used,type_of_struct is the type of the structure containing the ptr, andfield_name is the name of the list field within the structure. In ourtodo_struct structure from before, the list field is called simply list. Thus, wewould turn a list entry into its containing structure with a line like this:struct todo_struct *todo_ptr =list_entry(listptr, struct todo_struct, list);The list_entry macro takes a little getting used to, but is not that hard to use.The traversal of linked lists is easy: one need only follow the prev and nextpointers.

As an example, suppose we want to keep the list of todo_structitems sorted in descending priority order. A function to add a new entry wouldlook something like this:void todo_add_entry(struct todo_struct *new){struct list_head *ptr;struct todo_struct *entry;for (ptr = todo_list.next; ptr != &todo_list; ptr = ptr->next) {entry = list_entry(ptr, struct todo_struct, list);if (entry->priority < new->priority) {list_add_tail(&new->list, ptr);return;}}list_add_tail(&new->list, &todo_struct)}The <linux/list.h> file also defines a macro list_for_each that expands to thefor loop used in this code. As you may suspect, you must be careful when modifying the list while traversing it.Figure 10-1 shows how the simple struct list_head is used to maintain a listof data structures.Although not all features exported by the list.h as it appears in Linux 2.4 are available with older kernels, our sysdep.h fills the gap by declaring all macros andfunctions for use in older kernels.30222 June 2001 16:40http://openlib.org.uaQuick ReferenceLists in<linux/list.h>An empty listprevnextstruct list_headA list head with a two-item listA custom structureincluding a list_headEffects of the list_entry macroFigur e 10-1.

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

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

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

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