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

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

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

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

Systems with recent compilers willsupport the C99-standard types, such as uint8_t and uint32_t; when possible,those types should be used in favor of the Linux-specific variety. If your code mustwork with 2.0 kernels, however, use of these types will not be possible (since onlyolder compilers work with 2.0).You might also note that sometimes the kernel uses conventional types, such asunsigned int, for items whose dimension is architecture independent. This isusually done for backward compatibility. When u32 and friends were introducedin version 1.1.67, the developers couldn’t change existing data structures to the* This happens when reading partition tables, when executing a binary file, or whendecoding a network packet.29522 June 2001 16:40http://openlib.org.uaChapter 10: Judicious Use of Data Typesnew types because the compiler issues a warning when there is a type mismatchbetween the structure field and the value being assigned to it.* Linus didn’t expectthe OS he wrote for his own use to become multiplatform; as a result, old structures are sometimes loosely typed.Interface-Specific TypesMost of the commonly used data types in the kernel have their own typedefstatements, thus preventing any portability problems.

For example, a process identifier (pid) is usually pid_t instead of int. Using pid_t masks any possible difference in the actual data typing. We use the expression inter face-specific to referto a type defined by a library in order to provide an interface to a specific datastructure.Even when no interface-specific type is defined, it’s always important to use theproper data type in a way consistent with the rest of the kernel. A jiffy count, forinstance, is always unsigned long, independent of its actual size, so theunsigned long type should always be used when working with jiffies. In thissection we concentrate on use of ‘‘_t’’ types.The complete list of _t types appears in <linux/types.h>, but the list is rarelyuseful.

When you need a specific type, you’ll find it in the prototype of the functions you need to call or in the data structures you use.Whenever your driver uses functions that require such ‘‘custom’’ types and youdon’t follow the convention, the compiler issues a warning; if you use the -Wallcompiler flag and are careful to remove all the warnings, you can feel confidentthat your code is portable.The main problem with _t data items is that when you need to print them, it’s notalways easy to choose the right printk or printf format, and warnings you resolveon one architecture reappear on another.

For example, how would you print asize_t, which is unsigned long on some platforms and unsigned int onsome others?Whenever you need to print some interface-specific data, the best way to do it isby casting the value to the biggest possible type (usually long or unsignedlong) and then printing it through the corresponding format. This kind of tweaking won’t generate errors or warnings because the format matches the type, andyou won’t lose data bits because the cast is either a null operation or an extensionof the item to a bigger data type.In practice, the data items we’re talking about aren’t usually meant to be printed,so the issue applies only to debugging messages. Most often, the code needs only* As a matter of fact, the compiler signals type inconsistencies even if the two types are justdifferent names for the same object, like unsigned long and u32 on the PC.29622 June 2001 16:40http://openlib.org.uaOther Portability Issuesto store and compare the interface-specific types, in addition to passing them asarguments to library or kernel functions.Although _t types are the correct solution for most situations, sometimes the righttype doesn’t exist.

This happens for some old interfaces that haven’t yet beencleaned up.The one ambiguous point we’ve found in the kernel headers is data typing for I/Ofunctions, which is loosely defined (see the section ‘‘Platform Dependencies’’ inChapter 8). The loose typing is mainly there for historical reasons, but it can createproblems when writing code. For example, one can get into trouble by swappingthe arguments to functions like outb; if there were a port_t type, the compilerwould find this type of error.Other Portability IssuesIn addition to data typing, there are a few other software issues to keep in mindwhen writing a driver if you want it to be portable across Linux platforms.A general rule is to be suspicious of explicit constant values.

Usually the code hasbeen parameterized using preprocessor macros. This section lists the most important portability problems. Whenever you encounter other values that have beenparameterized, you’ll be able to find hints in the header files and in the devicedrivers distributed with the official kernel.Time IntervalsWhen dealing with time intervals, don’t assume that there are 100 jiffies per second.

Although this is currently true for Linux-x86, not every Linux platform runs at100 Hz (as of 2.4 you find values ranging from 20 to 1200, although 20 is onlyused in the IA-64 simulator). The assumption can be false even for the x86 if youplay with the HZ value (as some people do), and nobody knows what will happenin future kernels. Whenever you calculate time intervals using jiffies, scale yourtimes using HZ (the number of timer interrupts per second).

For example, to checkagainst a timeout of half a second, compare the elapsed time against HZ/2. Moregenerally, the number of jiffies corresponding to msec milliseconds is alwaysmsec*HZ/1000. This detail had to be fixed in many network drivers when porting them to the Alpha; some of them didn’t work on that platform because theyassumed HZ to be 100.Page SizeWhen playing games with memory, remember that a memory page is PAGE_SIZEbytes, not 4 KB.

Assuming that the page size is 4 KB and hard-coding the value isa common error among PC programmers — instead, supported platforms showpage sizes from 4 KB to 64 KB, and sometimes they differ between different29722 June 2001 16:40http://openlib.org.uaChapter 10: Judicious Use of Data Typesimplementations of the same platform. The relevant macros are PAGE_SIZE andPAGE_SHIFT.

The latter contains the number of bits to shift an address to get itspage number. The number currently is 12 or greater, for 4 KB and bigger pages.The macros are defined in <asm/page.h>; user-space programs can use getpagesize if they ever need the information.Let’s look at a nontrivial situation. If a driver needs 16 KB for temporary data, itshouldn’t specify an order of 2 to get_fr ee_pages. You need a portable solution.Using an array of #ifdef conditionals may work, but it only accounts for platforms you care to list and would break on other architectures, such as one thatmight be supported in the future. We suggest that you use this code instead:int order = (14 - PAGE_SHIFT > 0) ? 14 - PAGE_SHIFT : 0;buf = get_free_pages(GFP_KERNEL, order);The solution depends on the knowledge that 16 KB is 1<<14.

The quotient of twonumbers is the difference of their logarithms (orders), and both 14 andPAGE_SHIFT are orders. The value of order is calculated at compile time, andthe implementation shown is a safe way to allocate memory for any power of two,independent of PAGE_SIZE.Byte OrderBe careful not to make assumptions about byte ordering. Whereas the PC storesmultibyte values low-byte first (little end first, thus little-endian), most high-levelplatforms work the other way (big-endian).

Modern processors can operate ineither mode, but most of them prefer to work in big-endian mode; support for little-endian memory access has been added to interoperate with PC data and Linuxusually prefers to run in the native processor mode. Whenever possible, your codeshould be written such that it does not care about byte ordering in the data itmanipulates. However, sometimes a driver needs to build an integer number outof single bytes or do the opposite.You’ll need to deal with endianness when you fill in network packet headers, forexample, or when you are dealing with a peripheral that operates in a specificbyte ordering mode. In that case, the code should include <asm/byteorder.h>and should check whether _ _BIG_ENDIAN or _ _LITTLE_ENDIAN is defined bythe header.You could code a bunch of #ifdef _ _LITTLE_ENDIAN conditionals, but thereis a better way.

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

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

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

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