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

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

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

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

When writing kernel code, the preferred coding style is undoubtedly Linus’sown style. Documentation/CodingStyle is amusing reading and a mandatory lessonfor anyone interested in kernel hacking.All the definitions and flags we have introduced so far are best located within theCFLAGS variable used by make.In addition to a suitable CFLAGS, the makefile being built needs a rule for joiningdifferent object files. The rule is needed only if the module is split into differentsource files, but that is not uncommon with modules.

The object files are joinedby the ld -r command, which is not really a linking operation, even though it usesthe linker. The output of ld -r is another object file, which incorporates all thecode from the input files. The –r option means “relocatable;” the output file isrelocatable in that it doesn’t yet embed absolute addresses.The following makefile is a minimal example showing how to build a modulemade up of two source files.

If your module is made up of a single source file, justskip the entry containing ld -r.# Change it here or specify it on the "make" command lineKERNELDIR = /usr/src/linuxinclude $(KERNELDIR)/.configCFLAGS = -D_ _KERNEL_ _ -DMODULE -I$(KERNELDIR)/include \-O -Wallifdef CONFIG_SMPCFLAGS += -D_ _SMP_ _ -DSMPendifall: skull.oskull.o: skull_init.o skull_clean.o$(LD) -r $ˆ -o $@clean:rm -f *.o *˜ coreIf you are not familiar with make, you may wonder why no .c file and no compilation rule appear in the makefile shown. These declarations are unnecessarybecause make is smart enough to turn .c into .o without being instructed to, usingthe current (or default) choice for the compiler, $(CC), and its flags, $(CFLAGS).2322 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesAfter the module is built, the next step is loading it into the kernel.

As we’vealready suggested, insmod does the job for you. The program is like ld, in that itlinks any unresolved symbol in the module to the symbol table of the running kernel. Unlike the linker, however, it doesn’t modify the disk file, but rather an inmemory copy. insmod accepts a number of command-line options (for details, seethe manpage), and it can assign values to integer and string variables in your module before linking it to the current kernel.

Thus, if a module is correctly designed,it can be configured at load time; load-time configuration gives the user more flexibility than compile-time configuration, which is still used sometimes. Load-timeconfiguration is explained in “Automatic and Manual Configuration” later in thischapter.Interested readers may want to look at how the kernel supports insmod: it relieson a few system calls defined in ker nel/module.c.

The function sys_cr eate_moduleallocates kernel memory to hold a module (this memory is allocated with vmalloc ;see “vmalloc and Friends” in Chapter 7). The system call get_ker nel_syms returnsthe kernel symbol table so that kernel references in the module can be resolved,and sys_init_module copies the relocated object code to kernel space and calls themodule’s initialization function.If you actually look in the kernel source, you’ll find that the names of the systemcalls are prefixed with sys_. This is true for all system calls and no other functions; it’s useful to keep this in mind when grepping for the system calls in thesources.Version DependencyBear in mind that your module’s code has to be recompiled for each version ofthe kernel that it will be linked to.

Each module defines a symbol called _ _module_kernel_version, which insmod matches against the version number ofthe current kernel. This symbol is placed in the .modinfo Executable Linkingand Format (ELF) section, as explained in detail in Chapter 11. Please note thatthis description of the internals applies only to versions 2.2 and 2.4 of the kernel;Linux 2.0 did the same job in a different way.The compiler will define the symbol for you whenever you include<linux/module.h> (that’s why hello.c earlier didn’t need to declare it).

Thisalso means that if your module is made up of multiple source files, you have toinclude <linux/module.h> from only one of your source files (unless you use_ _NO_VERSION_ _, which we’ll introduce in a while).In case of version mismatch, you can still try to load a module against a differentkernel version by specifying the –f (“force”) switch to insmod, but this operationisn’t safe and can fail. It’s also difficult to tell in advance what will happen. Loading can fail because of mismatching symbols, in which case you’ll get an error2422 June 2001 16:34http://openlib.org.uaCompiling and Loadingmessage, or it can fail because of an internal change in the kernel.

If that happens,you’ll get serious errors at runtime and possibly a system panic—a good reason tobe wary of version mismatches. Version mismatches can be handled more gracefully by using versioning in the kernel (a topic that is more advanced and is introduced in “Version Control in Modules” in Chapter 11).If you want to compile your module for a particular kernel version, you have toinclude the specific header files for that kernel (for example, by declaring a different KERNELDIR) in the makefile given previously. This situation is not uncommonwhen playing with the kernel sources, as most of the time you’ll end up with several versions of the source tree. All of the sample modules accompanying thisbook use the KERNELDIR variable to point to the correct kernel sources; it can beset in your environment or passed on the command line of make.When asked to load a module, insmod follows its own search path to look for theobject file, looking in version-dependent directories under /lib/modules.

Althougholder versions of the program looked in the current directory, first, that behavior isnow disabled for security reasons (it’s the same problem of the PATH environmentvariable). Thus, if you need to load a module from the current directory youshould use . /module.o, which works with all known versions of the tool.Sometimes, you’ll encounter kernel interfaces that behave differently between versions 2.0.x and 2.4.x of Linux. In this case you’ll need to resort to the macrosdefining the version number of the current source tree, which are defined in theheader <linux/version.h>.

We will point out cases where interfaces havechanged as we come to them, either within the chapter or in a specific sectionabout version dependencies at the end, to avoid complicating a 2.4-specific discussion.The header, automatically included by linux/module.h, defines the followingmacros:UTS_RELEASEThe macro expands to a string describing the version of this kernel tree. Forexample, "2.3.48".LINUX_VERSION_CODEThe macro expands to the binary representation of the kernel version, onebyte for each part of the version release number. For example, the code for2.3.48 is 131888 (i.e., 0x020330).* With this information, you can (almost) easily determine what version of the kernel you are dealing with.KERNEL_VERSION(major,minor,release)This is the macro used to build a “kernel_version_code” from the individualnumbers that build up a version number.

For example, KERNEL_VERSION(2,3,48) expands to 131888. This macro is very useful when you* This allows up to 256 development versions between stable versions.2522 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running Modulesneed to compare the current version and a known checkpoint. We’ll use thismacro several times throughout the book.The file version.h is included by module.h, so you won’t usually need to includeversion.h explicitly. On the other hand, you can prevent module.h from includingversion.h by declaring _ _NO_VERSION_ _ in advance.

You’ll use_ _NO_VERSION_ _ if you need to include <linux/module.h> in severalsource files that will be linked together to form a single module—for example, ifyouneedpreprocessormacrosdeclaredinmodule.h.Declaring_ _NO_VERSION_ _ before including module.h prevents automatic declaration ofthe string _ _module_kernel_version or its equivalent in source files whereyou don’t want it (ld -r would complain about the multiple definition of the symbol). Sample modules in this book use _ _NO_VERSION_ _ to this end.Most dependencies based on the kernel version can be worked around with preprocessor conditionals by exploiting KERNEL_VERSION and LINUX_VERSION_CODE.

Version dependency should, however, not clutter driver code withhairy #ifdef conditionals; the best way to deal with incompatibilities is by confining them to a specific header file. That’s why our sample code includes a sysdep.h header, used to hide all incompatibilities in suitable macro definitions.The first version dependency we are going to face is in the definition of a “makeinstall” rule for our drivers. As you may expect, the installation directory,which varies according to the kernel version being used, is chosen by looking inversion.h. The following fragment comes from the file Rules.make, which isincluded by all makefiles:VERSIONFILE = $(INCLUDEDIR)/linux/version.hVERSION = $(shell awk -F\" ’/REL/ {print $$2}’ $(VERSIONFILE))INSTALLDIR = /lib/modules/$(VERSION)/miscWe chose to install all of our drivers in the misc directory; this is both the rightchoice for miscellaneous add-ons and a good way to avoid dealing with thechange in the directory structure under /lib/modules that was introduced rightbefore version 2.4 of the kernel was released.

Even though the new directorystructure is more complicated, the misc directory is used by both old and new versions of the modutils package.With the definition of INSTALLDIR just given, the install rule of each makefile,then, is laid out like this:install:install -d $(INSTALLDIR)install -c $(OBJS) $(INSTALLDIR)2622 June 2001 16:34http://openlib.org.uaThe Kernel Symbol TablePlatform DependencyEach computer platform has its peculiarities, and kernel designers are free toexploit all the peculiarities to achieve better performance in the target object file.Unlike application developers, who must link their code with precompiledlibraries and stick to conventions on parameter passing, kernel developers candedicate some processor registers to specific roles, and they have done so. Moreover, kernel code can be optimized for a specific processor in a CPU family to getthe best from the target platform: unlike applications that are often distributed inbinary format, a custom compilation of the kernel can be optimized for a specificcomputer set.Modularized code, in order to be interoperable with the kernel, needs to be compiled using the same options used in compiling the kernel (i.e., reserving the sameregisters for special use and performing the same optimizations).

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

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

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

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