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

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

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

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

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

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

For this reason,our top-level Rules.make includes a platform-specific file that complements themakefiles with extra definitions. All of those files are called Makefile.platform and assign suitable values to make variables according to the current kernelconfiguration.Another interesting feature of this layout of makefiles is that cross compilation issupported for the whole tree of sample files.

Whenever you need to cross compilefor your target platform, you’ll need to replace all of your tools (gcc, ld, etc.) withanother set of tools (for example, m68k-linux-gcc, m68k-linux-ld ). The prefix tobe used is defined as $(CROSS_COMPILE), either in the make command line orin your environment.The SPARC architecture is a special case that must be handled by the makefiles.User-space programs running on the SPARC64 (SPARC V9) platform are the samebinaries you run on SPARC32 (SPARC V8). Therefore, the default compiler runningon SPARC64 (gcc) generates SPARC32 object code. The kernel, on the other hand,must run SPARC V9 object code, so a cross compiler is needed.

All GNU/Linux distributions for SPARC64 include a suitable cross compiler, which the makefilesselect.Although the complete list of version and platform dependencies is slightly morecomplicated than shown here, the previous description and the set of makefileswe provide is enough to get things going. The set of makefiles and the kernelsources can be browsed if you are looking for more detailed information.The Kernel Symbol TableWe’ve seen how insmod resolves undefined symbols against the table of publickernel symbols.

The table contains the addresses of global kernel items—2722 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running Modulesfunctions and variables—that are needed to implement modularized drivers. Thepublic symbol table can be read in text form from the file /pr oc/ksyms (assuming,of course, that your kernel has support for the /pr oc filesystem — which it reallyshould).When a module is loaded, any symbol exported by the module becomes part ofthe kernel symbol table, and you can see it appear in /pr oc/ksyms or in the outputof the ksyms command.New modules can use symbols exported by your module, and you can stack newmodules on top of other modules.

Module stacking is implemented in the mainstream kernel sources as well: the msdos filesystem relies on symbols exported bythe fat module, and each input USB device module stacks on the usbcor e andinput modules.Module stacking is useful in complex projects. If a new abstraction is implementedin the form of a device driver, it might offer a plug for hardware-specific implementations. For example, the video-for-linux set of drivers is split into a genericmodule that exports symbols used by lower-level device drivers for specific hardware. According to your setup, you load the generic video module and the specific module for your installed hardware. Support for parallel ports and the widevariety of attachable devices is handled in the same way, as is the USB kernel subsystem.

Stacking in the parallel port subsystem is shown in Figure 2-2; the arrowsshow the communications between the modules (with some example functionsand data structures) and with the kernel programming interface.Port sharingand deviceregistrationLow-leveldeviceoperationsparport_pcparportlpKernel API(Messageprinting, driverregistration,port allocation,etc.)Figur e 2-2.

Stacking of parallel port driver modulesWhen using stacked modules, it is helpful to be aware of the modpr obe utility.modpr obe functions in much the same way as insmod, but it also loads any othermodules that are required by the module you want to load. Thus, one modpr obecommand can sometimes replace several invocations of insmod (although you’llstill need insmod when loading your own modules from the current directory,because modpr obe only looks in the tree of installed modules).2822 June 2001 16:34http://openlib.org.uaInitialization and ShutdownLayered modularization can help reduce development time by simplifying eachlayer. This is similar to the separation between mechanism and policy that we discussed in Chapter 1.In the usual case, a module implements its own functionality without the need toexport any symbols at all.

You will need to export symbols, however, wheneverother modules may benefit from using them. You may also need to include specific instructions to avoid exporting all non-static symbols, as most versions(but not all) of modutils export all of them by default.The Linux kernel header files provide a convenient way to manage the visibility ofyour symbols, thus reducing namespace pollution and promoting proper information hiding.

The mechanism described in this section works with kernels 2.1.18and later; the 2.0 kernel had a completely different mechanism, which is describedat the end of the chapter.If your module exports no symbols at all, you might want to make that explicit byplacing a line with this macro call in your source file:EXPORT_NO_SYMBOLS;The macro expands to an assembler directive and may appear anywhere withinthe module. Portable code, however, should place it within the module initialization function (init_module), because the version of this macro defined in sysdep.hfor older kernels will work only there.If, on the other hand, you need to export a subset of symbols from your module,the first step is defining the preprocessor macro EXPORT_SYMTAB. This macromust be defined befor e including module.h.

It is common to define it at compiletime with the –D compiler flag in Makefile.If EXPORT_SYMTAB is defined, individual symbols are exported with a couple ofmacros:EXPORT_SYMBOL (name);EXPORT_SYMBOL_NOVERS (name);Either version of the macro will make the given symbol available outside the module; the second version (EXPORT_SYMBOL_NOVERS) exports the symbol with noversioning information (described in Chapter 11).

Symbols must be exported outside of any function because the macros expand to the declaration of a variable.(Interested readers can look at <linux/module.h> for the details, even thoughthe details are not needed to make things work.)Initialization and ShutdownAs already mentioned, init_module registers any facility offered by the module. Byfacility, we mean a new functionality, be it a whole driver or a new softwareabstraction, that can be accessed by an application.2922 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesModules can register many different types of facilities; for each facility, there is aspecific kernel function that accomplishes this registration. The arguments passedto the kernel registration functions are usually a pointer to a data structure describing the new facility and the name of the facility being registered.

The data structure usually embeds pointers to module functions, which is how functions in themodule body get called.The items that can be registered exceed the list of device types mentioned inChapter 1. They include serial ports, miscellaneous devices, /pr oc files, executabledomains, and line disciplines. Many of those registrable items support functionsthat aren’t directly related to hardware but remain in the “software abstractions”field.

Those items can be registered because they are integrated into the driver’sfunctionality anyway (like /pr oc files and line disciplines for example).There are other facilities that can be registered as add-ons for certain drivers, buttheir use is so specific that it’s not worth talking about them; they use the stackingtechnique, as described earlier in “The Kernel Symbol Table.” If you want to probefurther, you can grep for EXPORT_SYMBOL in the kernel sources and find theentry points offered by different drivers.

Most registration functions are prefixedwith register_, so another possible way to find them is to grep for register_in /pr oc/ksyms.Error Handling in init_moduleIf any errors occur when you register utilities, you must undo any registrationactivities performed before the failure. An error can happen, for example, if thereisn’t enough memory in the system to allocate a new data structure or because aresource being requested is already being used by other drivers.

Though unlikely,it might happen, and good program code must be prepared to handle this event.Linux doesn’t keep a per-module registry of facilities that have been registered, sothe module must back out of everything itself if init_module fails at some point. Ifyou ever fail to unregister what you obtained, the kernel is left in an unstablestate: you can’t register your facilities again by reloading the module because theywill appear to be busy, and you can’t unregister them because you’d need thesame pointer you used to register and you’re not likely to be able to figure out theaddress. Recovery from such situations is tricky, and you’ll be often forced toreboot in order to be able to load a newer revision of your module.Error recovery is sometimes best handled with the goto statement.

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