Linux Device Drivers 2nd Edition, страница 14

PDF-файл Linux Device Drivers 2nd Edition, страница 14 Основы автоматизированного проектирования (ОАП) (17688): Книга - 3 семестрLinux Device Drivers 2nd Edition: Основы автоматизированного проектирования (ОАП) - PDF, страница 14 (17688) - СтудИзба2018-01-10СтудИзба

Описание файла

PDF-файл из архива "Linux Device Drivers 2nd Edition", который расположен в категории "". Всё это находится в предмете "основы автоматизированного проектирования (оап)" из 3 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "основы автоматизированного производства (оап)" в общих файлах.

Просмотр PDF-файла онлайн

Текст 14 страницы из PDF

Writing a user program that reads and writesdirectly to the device ports is much easier.Indeed, there are some arguments in favor of user-space programming, and sometimes writing a so-called user-space device driver is a wise alternative to kernelhacking.The advantages of user-space drivers can be summarized as follows:•The full C library can be linked in. The driver can perform many exotic taskswithout resorting to external programs (the utility programs implementingusage policies that are usually distributed along with the driver itself).•The programmer can run a conventional debugger on the driver code withouthaving to go through contortions to debug a running kernel.•If a user-space driver hangs, you can simply kill it. Problems with the driverare unlikely to hang the entire system, unless the hardware being controlled isreally misbehaving.•User memory is swappable, unlike kernel memory.

An infrequently useddevice with a huge driver won’t occupy RAM that other programs could beusing, except when it is actually in use.•A well-designed driver program can still allow concurrent access to a device.An example of a user-space driver is the X server: it knows exactly what the hardware can do and what it can’t, and it offers the graphic resources to all X clients.Note, however, that there is a slow but steady drift toward frame-buffer-basedgraphics environments, where the X server acts only as a server based on a realkernel-space device driver for actual graphic manipulation.Usually, the writer of a user-space driver implements a server process, taking overfrom the kernel the task of being the single agent in charge of hardware control.Client applications can then connect to the server to perform actual communication with the device; a smart driver process can thus allow concurrent access tothe device.

This is exactly how the X server works.Another example of a user-space driver is the gpm mouse server: it performs arbitration of the mouse device between clients, so that several mouse-sensitive applications can run on different virtual consoles.Sometimes, though, the user-space driver grants device access to a single program.This is how libsvga works. The library, which turns a TTY into a graphics display,gets linked to the application, thus supplementing the application’s capabilities4522 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running Moduleswithout resorting to a central authority (e.g., a server).

This approach usually givesyou better performance because it skips the communication overhead, but itrequires the application to run as a privileged user (this is one of the problemsbeing solved by the frame buffer device driver running in kernel space).But the user-space approach to device driving has a number of drawbacks. Themost important are as follows:•Interrupts are not available in user space. The only way around this (on thex86) is to use the vm86 system call, which imposes a performance penalty.*•Direct access to memory is possible only by mmapping /dev/mem, and only aprivileged user can do that.•Access to I/O ports is available only after calling ioper m or iopl.

Moreover, notall platforms support these system calls, and access to /dev/port can be tooslow to be effective. Both the system calls and the device file are reserved to aprivileged user.•Response time is slower, because a context switch is required to transfer information or actions between the client and the hardware.•Worse yet, if the driver has been swapped to disk, response time is unacceptably long. Using the mlock system call might help, but usually you’ll need tolock several memory pages, because a user-space program depends on a lotof library code.

mlock, too, is limited to privileged users.•The most important devices can’t be handled in user space, including, but notlimited to, network interfaces and block devices.As you see, user-space drivers can’t do that much after all. Interesting applicationsnonetheless exist: for example, support for SCSI scanner devices (implemented bythe SANE package) and CD writers (implemented by cdr ecord and other tools). Inboth cases, user-level device drivers rely on the “SCSI generic” kernel driver,which exports low-level SCSI functionality to user-space programs so they candrive their own hardware.In order to write a user-space driver, some hardware knowledge is sufficient, andthere’s no need to understand the subtleties of kernel software. We won’t discussuser-space drivers any further in this book, but will concentrate on kernel codeinstead.One case in which working in user space might make sense is when you arebeginning to deal with new and unusual hardware.

This way you can learn tomanage your hardware without the risk of hanging the whole system. Once you’ve* The system call is not discussed in this book because the subject matter of the text is kernel drivers; moreover, vm86 is too platform specific to be really interesting.4622 June 2001 16:34http://openlib.org.uaBackward Compatibilitydone that, encapsulating the software in a kernel module should be a painlessoperation.Backward CompatibilityThe Linux kernel is a moving target — many things change over time as new features are developed. The interface that we have described in this chapter is thatprovided by the 2.4 kernel; if your code needs to work on older releases, you willneed to take various steps to make that happen.This is the first of many “backward compatibility” sections in this book. At the endof each chapter we’ll cover the things that have changed since version 2.0 of thekernel, and what needs to be done to make your code portable.For starters, the KERNEL_VERSION macro was introduced in kernel 2.1.90.

Thesysdep.h header file contains a replacement for kernels that need it.Changes in Resource ManagementThe new resource management scheme brings in a few portability problems if youwant to write a driver that can run with kernel versions older than 2.4. This sectiondiscusses the portability problems you’ll encounter and how the sysdep.h headertries to hide them.The most apparent change brought about by the new resource management codeis the addition of request_mem_r egion and related functions.

Their role is limitedto accessing the I/O memory database, without performing specific operations onany hardware. What you can do with earlier kernels, thus, is to simply not call thefunctions. The sysdep.h header easily accomplishes that by defining the functionsas macros that return 0 for kernels earlier than 2.4.Another difference between 2.4 and earlier kernel versions is in the actual prototypes of request_r egion and related functions.Kernels earlier than 2.4 declared both request_r egion and release_r egion as functions returning void (thus forcing the use of check_r egion beforehand). The newimplementation, more correctly, has functions that return a pointer value so thatan error condition can be signaled (thus making check_r egion pretty useless). Theactual pointer value will not generally be useful to driver code for anything otherthan a test for NULL, which means that the request failed.If you want to save a few lines of code in your drivers and are not concernedabout backward portability, you could exploit the new function calls and avoidusing check_r egion in your code.

Actually, check_r egion is now implemented ontop of request_r egion, releasing the I/O region and returning success if the requestis fulfilled; the overhead is negligible because none of these functions is evercalled from a time-critical code section.4722 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesIf you prefer to be portable, you can stick to the call sequence we suggested earlier in this chapter and ignore the return values of request_r egion andrelease_r egion.

Anyway, sysdep.h declares both functions as macros returning 0(success), so you can both be portable and check the return value of every function you call.The last difference in the I/O registry between version 2.4 and earlier versions ofthe kernel is in the data types used for the start and len arguments. Whereasnew kernels always use unsigned long, older kernels used shorter types. Thischange has no effect on driver portability, though.Compiling for Multiprocessor SystemsVersion 2.0 of the kernel didn’t use the CONFIG_SMP configuration option to buildfor SMP systems; instead, choice was made a global assignment in the main kernelmakefile. Note that modules compiled for an SMP machine will not work in auniprocessor kernel, and vice versa, so it is important to get this one right.The sample code accompanying this book automatically deals with SMP in themakefiles, so the code shown earlier need not be copied in each module.

However, we do not support SMP under version 2.0 of the kernel. This should not be aproblem because multiprocessor support was not very robust in Linux 2.0, andeveryone running SMP systems should be using 2.2 or 2.4. Version 2.0 is coveredby this book because it’s still the platform of choice for small embedded systems(especially in its no-MMU implementation), but no such system has multiple processors.Exporting Symbols in Linux 2.0The Linux 2.0 symbol export mechanism was built around a function called register_symtab. A Linux 2.0 module would build a table describing all of the symbolsto be exported, then would call register_symtab from its initialization function.Only symbols that were listed in the explicit symbol table were exported to thekernel.

If, instead, the function was not called at all, all global symbols wereexported.If your module doesn’t need to export any symbols, and you don’t want to declareeverything as static, just hide global symbols by adding the following line toinit_module. This call to register_symtab simply overwrites the module’s defaultsymbol table with an empty one:register_symtab(NULL);This is exactly how sysdep.h defines EXPORT_NO_SYMBOLS when compiling forversion 2.0.

This is also why EXPORT_NO_SYMBOLS must appear within init_module to work properly under Linux 2.0.4822 June 2001 16:34http://openlib.org.uaBackward CompatibilityIf you do need to export symbols from your module, you will need to create asymbol table structure describing these symbols. Filling a Linux 2.0 symbol tablestructure is a tricky task, but kernel developers have provided header files to simplify things. The following lines of code show how a symbol table is declared andexported using the facilities offered by the headers of Linux 2.0:static struct symbol_table skull_syms = {#include <linux/symtab_begin.h>X(skull_fn1),X(skull_fn2),X(skull_variable),#include <linux/symtab_end.h>};register_symtab(&skull_syms);Writing portable code that controls symbol visibility takes an explicit effort fromthe device driver programmer.

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