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

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

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

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

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

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

Theseterms encompass not only the different privilege levels inherent in the two modes,but also the fact that each mode has its own memory mapping—its own addressspace — as well.* Most versions of insmod (but not all of them) export all non-static symbols if they findno specific instruction in the module; that’s why it’s wise to declare as static all thesymbols you are not willing to export.1922 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesUnix transfers execution from user space to kernel space whenever an applicationissues a system call or is suspended by a hardware interrupt. Kernel code executing a system call is working in the context of a process — it operates on behalf ofthe calling process and is able to access data in the process’s address space.

Codethat handles interrupts, on the other hand, is asynchronous with respect to processes and is not related to any particular process.The role of a module is to extend kernel functionality; modularized code runs inkernel space. Usually a driver performs both the tasks outlined previously: somefunctions in the module are executed as part of system calls, and some are incharge of interrupt handling.Concurrency in the KernelOne way in which device driver programming differs greatly from (most) application programming is the issue of concurrency. An application typically runssequentially, from the beginning to the end, without any need to worry aboutwhat else might be happening to change its environment.

Kernel code does notrun in such a simple world and must be written with the idea that many things canbe happening at once.There are a few sources of concurrency in kernel programming. Naturally, Linuxsystems run multiple processes, more than one of which can be trying to use yourdriver at the same time. Most devices are capable of interrupting the processor;interrupt handlers run asynchronously and can be invoked at the same time thatyour driver is trying to do something else. Several software abstractions (such askernel timers, introduced in Chapter 6) run asynchronously as well.

Moreover, ofcourse, Linux can run on symmetric multiprocessor (SMP) systems, with the resultthat your driver could be executing concurrently on more than one CPU.As a result, Linux kernel code, including driver code, must be reentrant—it mustbe capable of running in more than one context at the same time. Data structuresmust be carefully designed to keep multiple threads of execution separate, and thecode must take care to access shared data in ways that prevent corruption of thedata.

Writing code that handles concurrency and avoids race conditions (situationsin which an unfortunate order of execution causes undesirable behavior) requiresthought and can be tricky. Every sample driver in this book has been written withconcurrency in mind, and we will explain the techniques we use as we come tothem.A common mistake made by driver programmers is to assume that concurrency isnot a problem as long as a particular segment of code does not go to sleep (or“block”). It is true that the Linux kernel is nonpreemptive; with the importantexception of servicing interrupts, it will not take the processor away from kernel2022 June 2001 16:34http://openlib.org.uaKernel Modules Versus Applicationscode that does not yield willingly.

In past times, this nonpreemptive behavior wasenough to prevent unwanted concurrency most of the time. On SMP systems,however, preemption is not required to cause concurrent execution.If your code assumes that it will not be preempted, it will not run properly onSMP systems. Even if you do not have such a system, others who run your codemay have one. In the future, it is also possible that the kernel will move to a preemptive mode of operation, at which point even uniprocessor systems will have todeal with concurrency everywhere (some variants of the kernel already implementit).

Thus, a prudent programmer will always program as if he or she were workingon an SMP system.The Current ProcessAlthough kernel modules don’t execute sequentially as applications do, mostactions performed by the kernel are related to a specific process. Kernel code canknow the current process driving it by accessing the global item current, apointer to struct task_struct, which as of version 2.4 of the kernel isdeclared in <asm/current.h>, included by <linux/sched.h>. The currentpointer refers to the user process currently executing. During the execution of asystem call, such as open or read, the current process is the one that invoked thecall. Kernel code can use process-specific information by using current, if itneeds to do so.

An example of this technique is presented in “Access Control on aDevice File,” in Chapter 5.Actually, current is not properly a global variable any more, like it was in thefirst Linux kernels. The developers optimized access to the structure describing thecurrent process by hiding it in the stack page. You can look at the details of current in <asm/current.h>. While the code you’ll look at might seem hairy, wemust keep in mind that Linux is an SMP-compliant system, and a global variablesimply won’t work when you are dealing with multiple CPUs.

The details of theimplementation remain hidden to other kernel subsystems though, and a devicedriver can just include <linux/sched.h> and refer to the current process.From a module’s point of view, current is just like the external reference printk.A module can refer to current wherever it sees fit. For example, the followingstatement prints the process ID and the command name of the current process byaccessing certain fields in struct task_struct:printk("The process is \"%s\" (pid %i)\n",current->comm, current->pid);The command name stored in current->comm is the base name of the programfile that is being executed by the current process.2122 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesCompiling and LoadingThe rest of this chapter is devoted to writing a complete, though typeless, module.That is, the module will not belong to any of the classes listed in “Classes ofDevices and Modules” in Chapter 1.

The sample driver shown in this chapter iscalled skull, short for Simple Kernel Utility for Loading Localities. You can reusethe skull source to load your own local code to the kernel, after removing thesample functionality it offers.*Before we deal with the roles of init_module and cleanup_module, however, we’llwrite a makefile that builds object code that the kernel can load.First, we need to define the _ _KERNEL_ _ symbol in the preprocessor before weinclude any headers. As mentioned earlier, much of the kernel-specific content inthe kernel headers is unavailable without this symbol.Another important symbol is MODULE, which must be defined before including<linux/module.h> (except for drivers that are linked directly into the kernel).This book does not cover directly linked modules; thus, the MODULE symbol isalways defined in our examples.If you are compiling for an SMP machine, you also need to define _ _SMP_ _before including the kernel headers.

In version 2.2, the “multiprocessor or uniprocessor” choice was promoted to a proper configuration item, so using these linesas the very first lines of your modules will do the task:#include <linux/config.h>#ifdef CONFIG_SMP# define _ _SMP_ _#endifA module writer must also specify the –O flag to the compiler, because many functions are declared as inline in the header files. gcc doesn’t expand inline functions unless optimization is enabled, but it can accept both the –g and –O options,allowing you to debug code that uses inline functions.† Because the kernel makesextensive use of inline functions, it is important that they be expanded properly.You may also need to check that the compiler you are running matches the kernelyou are compiling against, referring to the file Documentation/Changes in the kernel source tree.

The kernel and the compiler are developed at the same time,though by different groups, so sometimes changes in one tool reveal bugs in the* We use the word local here to denote personal changes to the system, in the good oldUnix tradition of /usr/local.† Note, however, that using any optimization greater than –O2 is risky, because the compiler might inline functions that are not declared as inline in the source.

This may be aproblem with kernel code, because some functions expect to find a standard stack layoutwhen they are called.2222 June 2001 16:34http://openlib.org.uaCompiling and Loadingother. Some distributions ship a version of the compiler that is too new to reliablybuild the kernel. In this case, they will usually provide a separate package (oftencalled kgcc) with a compiler intended for kernel compilation.Finally, in order to prevent unpleasant errors, we suggest that you use the –Wall(all warnings) compiler flag, and also that you fix all features in your code thatcause compiler warnings, even if this requires changing your usual programmingstyle.

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