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

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

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

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

Although older modutils allowed loading nonversioned modules to versioned kernels, this is no longer possible. To solve the problem withhello.c, the source in the misc-modules directory of the sample code includes afew more lines to be able to run both under versioned and nonversioned kernels.However, we strongly suggest you compile and run your own kernel (without version support) before you run the sample code.*root# gcc -c hello.croot# insmod ./hello.oHello, worldroot# rmmod helloGoodbye cruel worldroot#According to the mechanism your system uses to deliver the message lines, youroutput may be different. In particular, the previous screen dump was taken from atext console; if you are running insmod and rmmod from an xter m, you won’t seeanything on your TTY.

Instead, it may go to one of the system log files, such as/var/log/messages (the name of the actual file varies between Linux distributions).The mechanism used to deliver kernel messages is described in “How MessagesGet Logged” in Chapter 4.As you can see, writing a module is not as difficult as you might expect. The hardpart is understanding your device and how to maximize performance. We’ll godeeper into modularization throughout this chapter and leave device-specificissues to later chapters.Kernel Modules Versus ApplicationsBefore we go further, it’s worth underlining the various differences between a kernel module and an application.Whereas an application performs a single task from beginning to end, a moduleregisters itself in order to serve future requests, and its “main” function terminatesimmediately. In other words, the task of the function init_module (the module’s* If you are new to building kernels, Alessandro has postedhttp://www.linux.it/ker neldocs/kconf that should help you get started.anarticleat1622 June 2001 16:34http://openlib.org.uaKernel Modules Versus Applicationsentry point) is to prepare for later invocation of the module’s functions; it’s asthough the module were saying, “Here I am, and this is what I can do.” The second entry point of a module, cleanup_module, gets invoked just before the module is unloaded.

It should tell the kernel, “I’m not there anymore; don’t ask me todo anything else.” The ability to unload a module is one of the features of modularization that you’ll most appreciate, because it helps cut down developmenttime; you can test successive versions of your new driver without going throughthe lengthy shutdown/reboot cycle each time.As a programmer, you know that an application can call functions it doesn’tdefine: the linking stage resolves external references using the appropriate libraryof functions. printf is one of those callable functions and is defined in libc.

A module, on the other hand, is linked only to the kernel, and the only functions it cancall are the ones exported by the kernel; there are no libraries to link to. Theprintk function used in hello.c earlier, for example, is the version of printf definedwithin the kernel and exported to modules.

It behaves similarly to the originalfunction, with a few minor differences, the main one being lack of floating-pointsupport.*Figure 2-1 shows how function calls and function pointers are used in a module toadd new functionality to a running kernel.Because no library is linked to modules, source files should never include theusual header files. Only functions that are actually part of the kernel itself may beused in kernel modules. Anything related to the kernel is declared in headersfound in include/linux and include/asm inside the kernel sources (usually foundin /usr/src/linux). Older distributions (based on libc version 5 or earlier) used tocarry symbolic links from /usr/include/linux and /usr/include/asm to the actualkernel sources, so your libc include tree could refer to the headers of the actualkernel source you had installed.

These symbolic links made it convenient for userspace applications to include kernel header files, which they occasionally need todo.Even though user-space headers are now separate from kernel-space headers,sometimes applications still include kernel headers, either before an old library isused or before new information is needed that is not available in the user-spaceheaders. However, many of the declarations in the kernel header files are relevantonly to the kernel itself and should not be seen by user-space applications. Thesedeclarations are therefore protected by #ifdef _ _KERNEL_ _ blocks.

That’s whyyour driver, like other kernel code, will need to be compiled with the_ _KERNEL_ _ preprocessor symbol defined.The role of individual kernel headers will be introduced throughout the book aseach of them is needed.* The implementation found in Linux 2.0 and 2.2 has no support for the L and Z qualifiers.They have been introduced in 2.4, though.1722 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesModuleinsmodKernel Properinit_module()register_capability()capabilities[]printk()......rmmodcleanup_module()unregister_capability()KEYOne functionDataMultiple functionsFunction callData pointerFunction pointerAssignment to dataFigur e 2-1.

Linking a module to the kernelDevelopers working on any large software system (such as the kernel) must beaware of and avoid namespace pollution. Namespace pollution is what happenswhen there are many functions and global variables whose names aren’t meaningful enough to be easily distinguished.

The programmer who is forced to deal withsuch an application expends much mental energy just to remember the “reserved”names and to find unique names for new symbols. Namespace collisions can create problems ranging from module loading failures to bizarre failures—which, perhaps, only happen to a remote user of your code who builds a kernel with adifferent set of configuration options.Developers can’t afford to fall into such an error when writing kernel codebecause even the smallest module will be linked to the whole kernel.

The bestapproach for preventing namespace pollution is to declare all your symbols asstatic and to use a prefix that is unique within the kernel for the symbols you1822 June 2001 16:34http://openlib.org.uaKernel Modules Versus Applicationsleave global. Also note that you, as a module writer, can control the external visibility of your symbols, as described in “The Kernel Symbol Table” later in thischapter.*Using the chosen prefix for private symbols within the module may be a goodpractice as well, as it may simplify debugging. While testing your driver, you couldexport all the symbols without polluting your namespace. Prefixes used in the kernel are, by convention, all lowercase, and we’ll stick to the same convention.The last difference between kernel programming and application programming isin how each environment handles faults: whereas a segmentation fault is harmlessduring application development and a debugger can always be used to trace theerror to the problem in the source code, a kernel fault is fatal at least for the current process, if not for the whole system.

We’ll see how to trace kernel errors inChapter 4, in the section “Debugging System Faults.”User Space and Kernel SpaceA module runs in the so-called ker nel space, whereas applications run in userspace. This concept is at the base of operating systems theory.The role of the operating system, in practice, is to provide programs with a consistent view of the computer’s hardware. In addition, the operating system mustaccount for independent operation of programs and protection against unauthorized access to resources.

This nontrivial task is only possible if the CPU enforcesprotection of system software from the applications.Every modern processor is able to enforce this behavior. The chosen approach isto implement different operating modalities (or levels) in the CPU itself. The levelshave different roles, and some operations are disallowed at the lower levels; program code can switch from one level to another only through a limited number ofgates.

Unix systems are designed to take advantage of this hardware feature, usingtwo such levels. All current processors have at least two protection levels, andsome, like the x86 family, have more levels; when several levels exist, the highestand lowest levels are used. Under Unix, the kernel executes in the highest level(also called supervisor mode), where everything is allowed, whereas applicationsexecute in the lowest level (the so-called user mode), where the processor regulates direct access to hardware and unauthorized access to memory.We usually refer to the execution modes as ker nel space and user space.

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

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

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

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