Compilation of the kernel and modules. Linux Kernel Config and Compilation Full Butt Test

Zharoznizhyuchі zasobi for children is recognized as a pediatrician. Allegedly, there are situations of inconspicuous help in case of fever, if the child is in need of giving it innocently. Todi fathers take on the versatility and consistency of fever-lowering drugs. Is it allowed to give children a breast? How can you beat the temperature of older children? What are the best ones?

If there is a need to install a tedious and reliable system based on Linux (whether it is technological processes, Web hosting, etc.), then it is often necessary to adjust the system core in such a rank, so that the whole system works more effectively and efficiently. The Linux kernel wants to be universal, it protects situations if it needs to be "tuned" for obvious reasons. That very architecture of the core of the transmission of its own performance. In such a rank, the Linux system administrators are people who are important to the nobility and intelligence of the main aspects of the Linux kernel configuration.

Linux Kernel Configuration Ways

For an hour, the development of Linux has steadily put together some of the main methods for configuring the kernel:

  • modifying parameters to tune the kernel;
  • kernel selection from output codes with required changes and / or additions to the text of kernel output codes;
  • dynamically connecting new components (functional modules, drivers) to the new kernel;
  • the transfer of special instructions to the kernel for an hour of cobbing and / or for vikoristovuchi zavantazhuvach (for example, GRUB).

Regardless of the specific situation, the success of the victorious way. But for the first time it is necessary to know, but for the best of all, the first is to configure the kernel parameters. The very same folding є compilation of the kernel from the output codes.

Kernel parameters

The Linux system kernel was broken up in such a rank, so it became possible for it to be as nasty as possible (in addition, as everything in UNIX and Linux systems) set up, adapting it to the necessary minds of exploitation and hardware refinement. And so, the whole process was very dynamic at the finished kernel. In other words, the system administrators can, at any moment of the hour, introduce corrective parameters, injecting into the robot the core itself, as well as the third components.

For the implementation of the development of the core and the programs of the Koristuvalnytsky Rivnya, there is a special interface for the implementation of information channels. Instructions are sent through the channels that set the values ​​for the kernel parameters.

Ale yak, everything in UNIX and Linux systems, configuring kernel parameters via information channels is tied to file system... To re-view the kernel configuration and keruvat in it, in the file system in the / proc / sys directory, look at the special files. Tse zvychaynі files, ale the stink of playing the role of the middle in providing the interface for dynamic interaction with the core. However, the documentation, which is very important, is about the description of specific parameters and their meaning to achieve a minimum. One of the dzherel, from which you can glean the actions of the central ones, the Documentation / sysent directory in the catalog with the kernel output codes.

For the sake of accuracy, look at a small butt, which will show you through the kernel parameter, adjust the maximum amount in one hour view files in the system:

$ Cat / рroc / sys / fs / file-max 34916 $ sudo sh -c "echo 32768> / proc / sys / fs / file-max"

Yak can be bachiti, to such a level you can get a quick sound and you won't be able to go even more foldable. This method is very handy, and there is no problem in restarting the system.

You can also choose a special utility sysctl... You will be allowed to edit the values ​​of the changes directly from the command row, for a list of pairs of the form of change = value from the file. At the stage of the cobbing of the utility, read the cob values ​​of the parameters specified in the file /etc/sysctl.conf... More detailed information about the utility sysctl can be found on the sides.

At the offensive tables, the parameters of the kernel are tuned up:

Catalog File / parameter appraisal
Z autoeject Automatically opening the CD tray when unmounting the CD-ROM attachment
F file-max maximum number of open files. For systems that can be processed with a great number of files, it is possible to change the value up to 16384
F inode-max The maximum number of open-critical index descriptors in one process. It is good for documents that display tens of thousands of file descriptors
Before
Before printk ratelimit Minimum interval between kernels, in seconds
Before printk_ratelimi_burst There are a few times, because they are guilty of being rejected, before the time when the minimum interval is less than the times printk becomes active
Before shmmax Maximum size of the living memory
N conf / default / rp_filter Includes the mechanism of re-routing the route to the output file
N icmp_echo_ Ignoring ICMP feeds for the destination 1
N icmp_echo_ Ignoring wide-area ICMP power supplies, especially for doorways 1.
N ip_forward Forwarding IP packets, which are meant for the road 1. For example, if the machine on Linux is running as a router, then the price will need to be set to equal 1
N ip_local_port_ A range of local ports, which can be seen when configuring a day. To increase the productivity of servers, so that there are a lot of different servers, the parameter needs to be expanded up to 1024-65000
N tcp_fin_timeout The interval for checking (in seconds) the final RN packet. To increase the productivity of servers, as they pass a lot of traffic, you need to set up a lot of low values ​​(close to 20)
N tcp_syncookies Detect attacks on SYN extensions. It is necessary to enable it if there is a DOS attack

Determination values: F - / proc / sys / fs, N - / proc / sys / net / ipv4, К - / proc / sys / kernel, С - / proc / sys / dev / cdrom.

$ Sudo sysctl net.ipv4.ip_forward = 0

As a result of the command prompt, IP packet forwarding will be enabled. Є One special feature for the command syntax: dot symbols in "net.ipv4.ip_forward", replace symbols with a slash in the path to the ip_forward file.

If you need a new version of the kernel?

In the present day, the Linux kernel is developing rapidly and boisterously. Most often, distribution kits do not include new versions of kernels in their systems. As a rule, all newfangled "fishes" are more familiar to fans of exoticism, entuzias, owners of new additions and installations, and simply addictive - that is.

For server machines, prote, fashion is unlikely to be significant, but new technologies can only be used to bring their reliability and efficiency into practice on test benches or on platforms. A skin-to-be-informed system administrator knows that one time he’s overworked over and over again, if it’s possible and guilty of good and without error, it’s not enough to unmistakably modernize the system. Even more robots are needed for many years (it is also necessary to pick up the core from the output codes, it’s easy to finish it) and service, to reach the busy road, oskolk, to deliver to the whole server without redundancy. (and even more without the "cold") reserve.

To that, be sure to know all the officials and assess who are interested in the health of their patches, because they do not pour systems into the robot, or even new drivers for attachments, which in Denmark the moment in the system is not going to be transferred soon.

If the decision of the new version of the kernel was taken by the gentry of this self-contained group, then it is necessary for the version to be stable. Previously, the Linux kernel version numbering system was organized in such a rank, where the paired version numbers meant stable release, unpaired - more "Syria". In Denmark, the principle of not just waiting for the moment of drinking from the information on the official website kernel.org.

Configuring kernel parameters

Config for the Linux kernel can be saved in the .config file. It is not enough to deal with manual operation and editing of a file, skins, in the first place: a complex syntax, which is far from being "human-readable", but in a different way: there are ways for automatic generation of kernel graphics configurations. list main teams for configuring the kernel collection:

  • make xconfig - Recommended to use the graphical middleware of KDE. Velmi Zruchniy іnstrument;
  • make gconfig - a short version for the victorian in the graphical environment of GNOME;
  • make menuconfig - given to the utility slides vikoristovuvati in pseudo-graphic mode. Vona is not so smart, like two in front, however, with its functions it is good to do it;
  • make config - the best non-manual "console" option, which can be set to the value of the kernel skin parameter. Do not allow changing the already set parameters.

Practically all options (with the blame of the rest) allow you to trim a short supplement on the skin parameter, carry out a request for a required parameter (or a configurable distribution), add additional components in the configuration, drive, and also show specific into the kernel, either as the module is locked up, as well as the module is added to the compilation option as the module is locked.

The make oldconfig command can appear even more crimson, it is intended for transferring the current configuration from the new version (zbirki) of the kernel to the new build. The command reads the configuration from the transferred file from the .config file with the old version, the form, as new parameters are available for the current download, and if you want to enable it or override it.

To display the configuration of the Linux kernel, you need to go to the directory with the release codes and run one of the commands for generating the configuration.

As a result of the robotic commands, a .conf file will be generated, a fragment instead of what we can step on:

# # Automatically generated file; DO NOT EDIT. # Linux / x86 4.20.7 Kernel Configuration # # # Compiler: gcc (Ubuntu 7.3.0-27ubuntu1 ~ 18.04) 7.3.0 # CONFIG_CC_IS_GCC = y CONFIG_GCC_VERSION = 70300 CONFIG_CLANG_VERSION = 0 CONFIG_IRQ_WORK = y CONFIG_BUILT CONFORTIME setup # CONFIG_INIT_ENV_ARG_LIMIT = 32 # CONFIG_COMPILE_TEST is not set CONFIG_LOCALVERSION = "" # CONFIG_LOCALVERSION_AUTO is not set CONFIG_BUILD_SALT = "" CONFIG_HAVE_KERNEL_GZIP = y CONFIG_HAVE_KERNEL_BZIP2 = y CONFIG_HAVE_KERNEL_LZMA = y CONFIG_HAVE_KERNEL_XZ = y CONFIG_HAVE_KERNEL_LZO = y CONFIG_HAVE_KERNEL_LZ4 = y CONFIG_KERNEL_GZIP = y # CONFIG_KERNEL_BZIP2 is not set # CONFIG_KERNEL_LZMA is not set # CONFIG_KERNEL_XZ is not set # CONFIG_KERNEL_LZO is not set # CONFIG_KERNEL_LZ4 is not set CONFIG_DEFAULT_HOSTNAME = "(none)" CONFIG_SWAP = y CONFIG_SYSVIPC = y CONFIG_SYSVIPC_SYSCTL = y CONFIG_POSIX_MQUEUE = y CONFIG_POSIX_MQUEUE_SYSCTL = y CONFIG_CROSS_MEMORY_ATTACH = y CONFIG_USELIB = y

Yak can be bachiti, in this code there is no gimmick for manual editing, just navigate the commentary on the cob of the .config file. The symbol "y" in the beginning, whether it is in the row, will be added to the core warehouse, "m" is the module. Decryptions or I will describe about the skin component, or the parameters in the.config file will not be revenged - from the power supply there is a follow-up to the documentation.

kernel compilation

There is a lot in the Linux kernel compilation - the main part of the configuration of the zbirka, some of them are needed by the nobility, as components of the key. I want to check the commands make xconfig, make gconfig, make menuconfig and without the default working configuration, which system will work on a large number of hardware platforms and configuration. Nutrition is only in the fact that you correctly install the kernel configuration without unnecessary and borrow resources of the components when you work.

Also, for a successful configuration and compilation of the kernel, the following events are required:

  • go to the directory with kernel output codes. Submit "wins" for the Linux kernel to be placed in the / usr / src directory, or you can link it from the kernel.org site to any hand;
  • viconati command make xconfig, make gconfig or make menuconfig;
  • viconate the make dep command (may not be valid for kernels version 2.6.x and more);
  • viconati the make clean command (for clearing everything that can be overwritten);
  • viconati make command;
  • viconati make modules_install command;
  • copy the file / arch / arch_name / boot / bzImage to / boot / vmlinuz. Here the / arch directory is located in the catalog with the output codes of the Linux kernel, name_architecture is the directory, which is the name of the current architecture (designated at the stage of the configuration). The selected binary image of the bzImage kernel can be used;
  • copy the file /arch/name_arch_tectury/boot/System.map to /boot/System.map;
  • make changes to the config files to be bridged /etc/lilo.conf (for LILO) or /boot/grub/grub.conf - for GRUB, as well as add additional configuration and settings for the new kernel.

Yaksho vi knew the mercy, be weasel, see a fragment of the text and natisnit Ctrl + Enter.

Special features of the modular program home recommendations s induce the program of the modular structure.

The connection of modules to the main programs is carried out in the order of the demotion of the USES, in the same order the blocks of the integration of modules, which can be connected to the main programs before the display of the programs.

The order of displaying modules can be added to access library data and software.

For example, if the modules with the names M1, M2 fit the same type A, change B and the program C, then if the USES models are connected to A, B, C in the whole PE, they will be equivalent to 2 modules.

If you want to characterize the correctness of the bits to those required by the same unit of additional plug-in modules, it is worthwhile to add a module to the module, and through the point of the object: МСА М1В М1.

Obviously, it’s easy to finish. great program on two parts (PE), so the main program + modules.

Skin reshaping PE in its memory segment and in its own disk file.

All the naked types, as well as the quiet ones who are guilty of being available, are available for the PE (the main program and the possible modules) should be added to the premium module with an empty viconuated part. At the same time, I do not follow the beasts, I respect those who do not like PE (for example, a module) are not vicious all the tsikh naked. In the іnіtsіаtsіі part of such a module, there can be included an operator that connects files with non-standard text files(ASSIGN) і і і і і і і і і і files, in order to provide them with the game before transferring the tribute (RESET і REWRITE).

The first group of programs, for example, a series of compact functions, are placed in 3 (according to) module;

When the software is distributed according to modules in a folding project, a special respect for the fault is included in the schedule and the moment of writing.

At the middle of the TR є koshty, you can compile the modules in different ways.

Compile Alt + F9 RUN Cntr + F9

Destination Memory

The modes are developed only in the way of communication and the main program.

Compile mode

Compiled is the main program or a module, which is located at the moment in the active window of the editor. As soon as there is a change to non-standard modules of a koristuvach, then the mode is visible from the back of the same disk files with extensions ___. Tpu for such a skin plug-in.



If the Destination is saved in the memory, then the files will be lost only in the memory, and the disk file will not be deleted.

However, it’s easier to compile tpu-files together with the compiler of all programs for additional modes, as you don’t need to set Disk for the destination option.

Make mode

When compiling in the whole mode, in front of (before compiling the main programs) for the skin module, the following should be changed:

1) Removing a disk tpu file; if it’s dumb, then it automatically flashes through the compilation of the module's output text, so that it’s pas-file

2) Reconciliation of the module known to the tpu-file, where the changes could have been made; the tpu file will automatically be closed again in the drop-down box

3) Inability of the interface section of the module: if there is a change, then all these modules will also be recompiled (these included pas-files), in which case the module is indicated in the USES proposition.

If there was no change in the cob texts of the modules, then the compiler of the robot would interconnect with the tpu -File and the victorious hour for compilation.

Build mode

On the view to the Make mode, the visibility of the output pas-files is automatically displayed; to carry out a compilation (recompilation) of the skin module and by the guarantor of all changes in the pas-file texts. It’s an extra hour of compilation of programs as a whole.

On the display in the compile mode, the Make and Build mode allows you to repair the compiled program of the modular structure from any given pas-file (which is called the first one), just as the file (or a part of the programs) is in the active editor. For the whole, in the compile point, select the Primary file option, press Enter and write down the original pas-file, and the compilation will be remembered by the file itself.

If the original file does not appear like that, then the compilation in the Make, Build and RUN modes can only be in the same way, as the main program is in the active window of the editor.

About: "For the motives of the re-translation" Linux Device Driver 2-nd edition. Transfer: Prince Oleksiy [Email protected] date the last snake: 03.08.2004 Distribution: http://lug.kmv.ru/index.php?page=knz_ldd2

Now let's fix the program! At the same time, the main provisions about the modules and about the software in the kernel will be covered.
Here we select and start-up a new module, the structure of which would look like a real modular driver.
At the same time, we concentrate on the head positions not on the specificity of real attachments.

All parts of the kernel, such as functions, changes, headers and macros, like guessing here, will be
described in detail in the book.

Hello world!

In the process of getting to know the original material written by Alessndro Rubini & Jonathan Corbet, the butt is not too far away, and the aiming is Hello world! To that, I want to read it, for my glance there is a larger version of the first module. I am encouraged that there are no problems with the installation of the kernel of 2.4.x versions. The propagation module and the method of its compilation allow vikoristovuvati in the kernels, as it is susceptible to, and does not accept version control. Read more and learn more about the details and terminology, I’ll open the vim at once and fix it!

================================================== // hello_knz.c file #include #include <1>Hello, world \ n "); return 0;); void cleanup_module (void) (printk ("<1>Good bye cruel world \ n ");) MODULE_LICENSE (" GPL "); =============================== =================

To compile such a module, you can choose to make a Makefile. Do not forget to put a tab character in front of the row to fix it with $ (CC) ....

================================================== FLAGS = -c -Wall -D__KERNEL__ -DMODULE PARAM = -I / lib / modules / $ (shell uname -r) / build / include hello_knz.o: hello_knz.c $ (CC) $ (FLAGS) $ (PARAM) - o [Email protected] $^ =================================================

There are two specialties here, in accordance with the code of the original Hello world, proponated by Rubini & Corbet. First, the module will be a mother version, and will be built from the kernel version. Tse reach the values ​​\ u200b \ u200bof the changing PARAM in the scenario of the compilation. Alternatively, now the module will be licensed in the GPL (validated to the MODULE_LICENSE () macro). If you can't kill it, then when you install the module in the kernel, you can beat it, roughly, it will start getting worse:

# Insmod hello_knz.o Warning: loading hello_knz.o will taint the kernel: no license See http://www.tux.org/lkml/#export-tainted for information about tainted modules Module hello_knz loaded, with warnings

Explainable now are the module compilation options (macro values ​​will be explained below):

-s- if this option is available, the gcc compiler will stop the process of compiling the file immediately after sending the file to the file, do not hesitate to try to open the binaries.

-Wall- the maximum value for the operation of the gcc robot.

-D- the value of macros. Those are the #define directives in the compiled files. Absolutely no difference, in any way to start, as vikoristoyutsya in this module, macros, for the additional #define in the source file, or for the additional option -D for the compiler.

-I- add-ons for jokes include-files. I have a bit of respect for the Victorian setting "uname -r";

At the offensive razdіlі brought the іnshy butt of the module. In the same place, the report explains the method of installation and vivantation from the kernel.

Original Hello world!

Now, the original code of the simple "Hello, World" module, promoted by Rubini & Corbet, is provided. The whole code can be compiled for kernels from 2.0 to 2.4. The whole butt, like all of them, is presented in the book, available on the O'Reilly FTP site (div. Chapter 1).

// hello.c file #define MODULE #include int init_module (void) (printk ("<1>Hello, world \ n "); return 0;) void cleanup_module (void) (printk ("<1>Goodbye cruel world \ n ");)

function printk () Designed in Linux kernels and practicalities as standard biblical functionality printf () in movi Сі. The kernel needs its own power, but it is not large in size, the function of vivedennya is to take place without the middle in the nucleus, and not in the libraries of the standard for koristuvach rivnya. The module can be used as a function printk () That is, when the module is locked up for an additional command insmod the module connects to the kernel and can access the published (exported) functions and change the kernel.

String parameter "<1>", Using the printk () function is the priority. In the original English dzherels, the term loglevel is used, which means the level of logging. given application mi vikoristovuєmo is a high priority for the occasion, when you see a small number. A high priority is given to ask yourself, because of the priority we will take for the candidates, you may not be able to get into the console, because the module is installed. Directly changing the kernel with the priority behind the ability to lay down the version of the running kernel, the version of the demon klogd, І your config. More details, a robot with a function printk () We can be explained in Chapter 4, "Technique of Improvement".

You can protest the module, for the help of the command insmod to install the module into the kernel and commands rmmod to see the module from the kernel. The bottom shows how the price can be changed. At the same entry point, init_module () will be matched when the module is installed into the kernel, and cleanup_module () when it is installed from the kernel. Remember that only the grants of Koristuvach can be added to Vivantazhuvati Modules.

The butt of the module, the guidance of the vishche, can be used only with the kernel, as it was selected with the reference "module version support". It's a pity that there are more distributions for the kernel with version control (this is discussed in the "Version control in modules" section of Chapter 11, "kmod and Advanced Modularization"). I want more old version of the package modutils Allowing such modules to be added to the kernel, selected with version control, is now unwise. Nagadaєmo, the modutils package reveals the set of programs, before entering the programs insmod and rmmod.

Manager: Check the version number and location of the modutils package from your distribution.

When you try to insert such a module into the kernel, so that version control will be applied, you can start to know about the pardon as soon as possible:

# Insmod hello.o hello.o: kernel-module version mismatch hello.o was compiled for kernel version 2.4.20 while this kernel is version 2.4.20-9asp.

In catalosis misc-modules butt from ftp.oreilly.com you will know the original butt by hello.c programs, as to take revenge on more than three rows, or maybe it is installed in the cores as it is on, so you don’t need version control. Yak bi was not there, it is strongly recommended that you change the kernel without adding version control. At the same time, it is recommended to take the original kernel dzherel on the site www.kernel.org

If you are a newcomer to the collection of kernels, then try to read the article, like Alessandro Rubini (one of the authors of the original book), posted it on http://www.linux.it/kerneldocs/kconf, and I am guilty of helping you in mastering the process.

Visit the text consoles of the command for the compilation and testing of the original butt-guided module.

Root # gcc -c hello.c root # insmod ./hello.o Hello, world root # rmmod hello Goodbye cruel world root #

It is always a matter of mechanism, which is your system for transferring rows at a time, directly to the mechanism, so that you can use the function printk (), May be seen. At the guided application, the module testing and testing, after being passed from the printk () function, appeared to be sent to the same console, and the commands for installing and launching the modules were sent to the same console. Tse butt of a book of knowledge from a text console. Yaksho vy vikonute command insmodі rmmod with programs xterm That, shvidshe for everything, do not beat anything at your terminal. Replace it, sometimes you can use one of the system logins, for example / Var / log / messages. The exact name of the file is stored in the distribution kit. Wonder at the hour of changing log files. Mechanism that is used to transfer information from the printk () function, descriptions in the section "How Messages Get Logged" in section 4 "Technics
goodness ".

For a glance at the view of the module in the file system logs / val / log / messages, manually use the system utilities tail, as for the changes, insert the last 10 rows transferred to the file. A simple utility option the option -f for launching will be used to utilize the file in the mode behind the remaining rows, so that when new rows of stench appear in the file, it will automatically be updated. To zupiniti vikonannya command in the whole view, you need to press Ctrl + C. Thus, to look at the remaining ten rows in the file of system logins, enter the command row next:

Root # tail / var / log / messages

Yak vi can bachiti, the writing of the module is not so neat, as you can zadatis. Naivazhcha chastina is a sense of intelligence, how practical is your setup and how to make a shvidcode module. The advanced chapters of knowledge are more about writing simple modules, and the specifics of the attachments are needed for the offensive chapters.

Features between kernel modules and add-ons

Dodatok has one point to enter, how to fix it and get it right away launched supplement in the operative memory of the computer. The entry point is described in the main () function. The completion of the main () function means the completion of the program. The module has a few input points, which are displayed when the module is installed and visible from the core, as well as when the intruder is processed, as a power supply. So, the point at the init_module () entry point is to ask for a module that is locked into the kernel. The cleanup_module () function will be matched when a module is invoked. One can learn from the points of entry into the module, which can be displayed when the power is supplied to the module.

The ability to secure and replace modules is two factors in the mechanism of modularization. The stench can be estimated in different keys. For a retailer, price means, first for everything, a change in the hour of release, so you can test the driver's functions without the tricky process of rewiring.

As a programmer, you know that a supplement can be used as a function, as it has not been announced in a supplement. At the stages of static or dynamic compositing, the addresses of such functions from general libraries begin. function printf () one of these functions, which is indicated in the library libc... The module, on the other side, of tying only with a core and can be used only for those functions that are exported by the core. The code of vikonuvatsya in the core cannot vikoristovuvat the names of the library. So, for example, the function printk (), Yaka vikoristovavasya in the butt hello.c, Is an analogue of the video function printf (), Available in supplements for koristuvach rivnya. function printk () It is displaced in the core and is guilty of the mother, if possible, the minimum size. To that, on the view of printf (), I might already be surrounded by a number of types of data, and, for example, I won’t accept numbers with a floating point.

Implementation of kernels 2.0 and 2.2 without a special type specifier Lі Z... Stink Booley was introduced only in kernel version 2.4.

Figure 2-1 shows the implementation of the mechanism of the wiklik function, such as the points of entry into the module. Likewise, on the whole tiny image of the mechanism of the inter-modality of the installed module with the core.

Small. 2-1. Linking the module to the kernel

One of the peculiarities of Unix / Linux operating systems is that they can be linked with kernel modules. As you already know, modules, when they are locked, are linked to the kernel, so everything that is for your module, the function is to be denuded in the header files of the kernel and is present in the kernel. Widget texts of modules nicoli not guilty to include special headings from the library of koristuvatsky spaciousness. For kernel modules, you can choose to use only functions that work as part of the kernel.

The entire kernel interface, descriptions in the header files, can be found in the directories include / linuxі include / asm all the middle cob kernel codes /usr/src/linux-x.y.z(X.y.z is your kernel version)). Most older distributions (based on libc version 5 or less) / Usr / include / linuxі / Usr / include / asm to see directories in the kernel sources. The symbolic powers give the power, if necessary, to use the kernel interface in the form of supplements.

Unimportant to those who have a library interface of the core now being shown to the core interface, in particular, in the context of the core processes, the need for the core interface is correct. However, it is a lot of efforts in the header files of the kernel to be introduced only to the very kernel and are not guilty of being available to the add-ons of the koristuvach. To the one who was taken aback #ifdef __KERNEL__ blocks. The axis of what your driver, like the one in the kernel code, is guilty of but compiled with a naked macro symbol __KERNEL__.

The role of additional headers in kernel files will be discussed down the line as needed.

Developers who work with great software projects (for example, such as the core), blame vrahovuvati and unicati "Zabrudneniya to the vastness of the men"... Qia problem with obviousness great number The functions and global changes of people are not very different (remembered). The programmer, who will be happy with such supplements, will take more than an hour to remember the "reserved" names and invent unique names for new elements. The number of names (ambiguities) can solve a wide number of problems, fixing the pardons when the module is locked, ending the unstable or unreasonable behavior of the program, as it can manifest itself in the corystics, as well as the victorious core, the confidential

The vendors cannot allow any such pardons when writing the kernel code, so that the smallest module itself will be linked to the kernel. We brush up on solutions for getting rid of the colossus of the names є, in Pershe, denuding your objects with programs yak static, And, in a different way, the victorian for the imenuvannya of global objects is unique, in the boundaries of the systems, prefix. In addition, as a developer of the module, you can control the areas of visibility of objects in your code, as described in the section "Kernel Linking Table".

Most (but not all) version of the command insmod Export all objects of the module, as long as they are not naked static For the reasons, that is, in the modules there are no special instructions for the whole rakhunok. To that, it is quite reasonable to expose additional components, if you don’t go exporting, yak static.

Vikoristannya unique prefix for local facilities in the middle of the module can be a good practice, so as I will ask for a favor. After an hour of testing your driver, you can know how to export additional objects to the kernel. If you have a unique prefix for a given name, you don’t want to make a colony in the space of the name of the kernel. Prefixes, how to be victorious in the core, for homeliness, vicarious to use the symbols of the lower register, and we will be satisfied with the whole thing.

There is also one more distinction between the core and the indications for the corystuvach by the processes of clearing in the mechanism of processing of grasses. The core of the control vikonannya to the process designated for the criminals, that the pardon in the process designated for the criminals is to produce a fault that is not shocking for the system: a segmentation fault. At the same time, you can be the owner of the vikoristany vіdladchik for vіdsthezhennya pardon y vіchіdnuyu code assigned for the corystuvach programs. The pardons are found in the core fatal - if not for the whole system, then, at least, tied to the flow of activity. At the razdіlі "Improvement of the grants of the system" Chapter 4 "Technics of the improvement" we can see the ways of cutting the kernels.

Core space and space of the core

The module to visit the so-called open spaces of the core, Todi yak dodatki pratsyuut v. Qia concept - the basis of the theory of operational systems.

One of the main features of the operating system of the field in the given koristuvach and the designation for the koristuvach programs of computer resources, most of which are represented outbuildings... The operational system is guilty not only of securing access to resources, but of control over the video and registration, in order to prevent a number of and unauthorized access. To add to the tsiogo, operating system You can set up independent operations for the program and be cleaned from unauthorized access to resources. date of the tsієї non-trivial zeal It is possible only in that case, if the processor will not take care of the system programs from the data of the koristuvach.

It is practically a skin-friendly processor in order to ensure such podil, for the realization of new privileges for the selected code (it is necessary not less than two equals). For example, the processors of architecture I32 may have a choice of equal privileges from 0 to 3. Moreover, the level of 0 may become a privilege. For such processors, there is a class of preferential instructions, which can be displayed only on preferable levels. Unix system and vicoristovuyut two equal processor privileges. As the processor is more than two years of privilege, then the vicarist will be the lowest and the best. The Unix Kernel is right on to the best friend privileiv, secure management of the possession and processes of the koristuvach.

If we are talking about open spaces of the coreі the space designated for the process to be fooled by the respect not only of the difference in favor of the selected code, but also of the large address.

Unix transfers from the vastness of the designated process to the kernel in two versions. In the first place, if the koristuvalnitsky supplement of the vicon is to the core (systemic wiklik), and, in a different way, it’s about the hour of servicing the equipment. Kernel code, which will be displayed when a system wikklicks work in the context of a process, Tobto pratsuyuchi in the interests of the wiklik in this process, you can access to the address space of the process. On the other hand, the code of vikonuvannya when servicing the device interchange є asynchronous, according to the process, and does not apply to any particular process.

Appointment of modules of the field in the extended functionality of the kernel. The module code is available in the kernel space. Please, the module is ok, insulting the manager, you mentioned earlier: the functions of the module are displayed as a part of the system wikkliks, and the actions are prompted for management.

Paralleling in the core

When programing annex drivers, on the display of the programmed supplements, it is especially worthwhile to feed about the parallelization of the selected code. As a rule, the supplement will be taken from the cob until the end of the last day, without worrying about the change of your otochenya. The kernel code is to blame for the urahuvannya of that, until one hour, one can win a spine of a beast.

There are no obvious reasons for paralleling the kernel code. Likewise, there are no problems running in Linux, and because of them you can turn to the code of your module overnight. Bagato attachments can wicklate the processor's hardware. Probes pererivan wiklikayutsya asynchronously і can be wiklicans at that moment, if your driver is engaged in wikonannyy power supply. Deyaki of software abstractions (such as kernel timers, as explained in Chapter 6 "Flow of Time") also run asynchronously. In addition, Linux can run on systems with symmetric Multiprocessors (SMP), as a result, your driver code can be simultaneously viewed on desktop processors in one hour.

For three reasons, the Linux kernel code, including driver codes, is guilty of being re-interchangeable, so it’s guilty of being built on the basis of more than one context given overnight. The structure of these guilty parties is broken down from the parallel distribution of decile streams. At its own heart, the kernel code is guilty of the mother of the building of a number of parallel streams, which are not possible. Writing such a code, which can be displayed in parallel and unique situations, in which the latter can lead to an unimportant problem of the system, in a lot of hours, and, perhaps, trickery. The leather butt of the driver in the ts_y kniz_ is written from the words of the moaning parallel vikonannya. If necessary, we will explain the peculiarities of the technique of writing such a code.

Naybіlsh zagalnaya pomorka, as to admit the programs of the field in them, but parallelism is not a problem, some of the deyakі segment code can not go to the "sleeping camp". Actually, the Linux kernel is not viable, with an important clue that you can’t rewrite the processor for an hour that is important to the kernel code. It will remain an hour, non-loadability will be added to the non-load-carrying capacity in most cases. On SMP systems, however, vivantation of the code is not required through parallel calculation.

As long as your code is being transferred, if it will not be vivantated, then it will not be correctly processed on SMP systems. Navi if you don’t know the system, її can ma htos іnshy, what kind of vicarist your code. Likewise, perhaps, in the future, in the core, there will be vikoristovuyuvatsya ability, that, to navigate one-process systems and mother will be right from the parallel everywhere. There are also options for the implementation of such kernels. In such a rank, an intelligent programmer will write the code for the kernel in the start-up, so it will work on the systems with SMP.

Approx. shifting: Vibachte, just the last two paragraphs, I don’t sound. It can be, tse is the result of a wrong transfer. I will tell you the original text.

A common mistake made by driver programmers is to assume that concurrency is not 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 important exception of
servicing interrupts, it will not take the processor away from kernel code that does not yield willingly. In past times, this nonpreemptive
behavior was enough 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 on SMP systems. Even if you do not have such a system,
others who run your code may 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 to deal with concurrency everywhere (some variants of the kernel already implement
it).

Information about the threading process

If the code of the kernel module does not vikonutsya last, as a supplement, altogether more animals to the kernel will vikonuyutsya, which is turned to the new, process. The kernel code can be recognized as a wiki process by turning up to a global wizard, which will apply to the structure struct task_struct, Pevnu, for kernels version 2.4, in file , Included in ... showman current vkazu on the current scho vikonutsya koristuvalnitsky process. When such systemic victories are victorious open () abo close (), Obov'yazkovo ісnuє process wiklikav їх. Kernel code, if necessary, can wipet specific information on wiping process through an indicator current... Attach a victorian of the tsiy indicator and you will find it in the section "Access control to the file attachment" in section 5 "Enhanced Char Driver Operations".

For this year's day, showman current not much of a global change, like in early versions of the kernel. The retailers optimized access to the structure, as they describe the flow process of moving it to the side of the stack. You can wonder at the details of the current implementation in the file ... You may not forgive the code you like there. May be on uvaz, that Linux is not SMP-based system, and global change simply will not work, if you will be right with no CPU. The details of the implementation will be left unavailable for other kernel subsystems, and the driver can be attached to the display current only through the interface .

From the point of view of the module, current similar to callout posilannya printk ()... Module can vikoristovuvati current everywhere, it is necessary. For example, the onset of the shmatok code is another identifier (process ID - PID) and the command and the wiki into the module to the process, which can be read through the structure fields struct task_struct:

Printk ("The process is \"% s \ "(pid% i) \ n", current-> comm, current-> pid);

The field current-> comm є ім'я command file spawned a threading process.

Compilation and pre-assignment of modules

The rest of the central chapter of assignments is written for the finished, if not atypical, module. That is, the module should not be located up to the same class described in the section "Classes of attachments and modules" in section 1 "Added to the driver of attachments". The application of the driver shown in the distribution will be called skull (Simple Kernel Utility for Loading Localities). You can use the scull module as a template for writing your own local code.

My vikoristovuєmo understanding of "local code" (local) to support your personal changes to the code, in the good old days of Unix (/ usr / local).

However, before this, it’s like the init_module () and cleanup_module () function, we’ll write a Makefile script, which we’ll use the make utility to make to induce a code-specific module.

Before Tim, as a preprocessor, it is necessary to process the inclusion of any headers with the #define directive and the values ​​of the macro symbol __KERNEL__. As in the past, in the kernel interface files there can be kernel-specific context values ​​visible only if the __KERNEL__ symbol is indicated in the preprocessing stage in the past.

An important symbol, which is indicated by the #define directive, is the MODULE symbol. I am guilty of the values ​​before turning on the interface (Viklyuchuyuchi drivers will be selected at once with the kernel). Drivers that go into the core will NOT be described in this book, so the MODULE symbol will be present in all our butts.

Whenever you select a module for an SMP system, you also need to have the __SMP__ macro symbol in front of the kernel interfaces included. In the version of the kernel 2.2, we will limit the item in the configuration of the kernel to the addition of a vibration between a single-processor and multi-processor system. To that, the inclusion of the advanced rows in the next rows of your module will be brought up to the adjustment of the bagatoprocessing system.

#include #ifdef CONFIG_SMP # define __SMP__ #endif

The developers of the module are also responsible for the importance of optimizations -O for the compiler, for that there are a lot of inline functions in the kernel header files. The gcc compiler does not offer inline extensions for functions until optimizations are not allowed. I called the extension of inline settings behind the additional -g and -O option to allow you, in general, to add the code of the inline functionality in the debugger. So, as the core is broadly vicious inline-functionality, it is even more important that the stink is expanded correctly.

Respect, however, that the victorian be-optimizatsii ryvnya-O2 is risen, because the compiler can be expanded and those functions, which are not described as inline. It can lead to problems, so that the code of some functions can be cleared up to know the standard stack of your wiklik. For inline-extensions, it is reasonable to insert the function code at the point of the wikliku to replace the wikklik function's instructions. Apparently, at the same time, since there is no wiklik function, there is no stack wiklik.

You can, you will need to reconsider, for the compilation of the modules you use the same compiler, which is the same compiler for picking up the kernel, in which case the module is transferred to install. Learn more about the original document in the file Documentation / Changes rosted in catalose dzherel kernels. The development of the core and the compiler, as a rule, are synchronized between groups of developers. There may be drops, if one of the same elements is opened in the first place. Deyaky distribution kits provide ultra-new versions of the compiler, which do not match the vibran kernel. I have a vipadku, stink, squeal, nadayut okremiy package (often titles kgcc) With a compiler, specially designed for
kernel compilations.

Nareshti, in order for you to remember the pardons, we will propose to you the option of compilation -Wall(All warning - all worn out). You can, for the satisfaction of all the times, you will need to change your special style of programming. When the kernel code is written, Linus Torvalds' style of coding is more vivid than vikoristovuvati style of proponation. So, document Documentation / CodingStyle, from the catalog of kernel dzherel, to complete the list of recommendations to all teams, who should refer to the programs of the kernel.

The set of compilations of the module, which were learned recently, are recommended to be changed in the winter CFLAGS your Makefile. For utilization make the whole thing is special, as I can see it from a false description.

Krim praporiv in the winter CFLAGS, Your Makefile may contain a meta, such as one common file. Such a meta is necessary only in that case, if the code of the module of distributions to a number of files in a dzherel, well, vzagal, not є ridkistu. Ob'ktnі files ob'nuyutsya command ld -r, Yaka is not a linking operation in a remote sensation, do not marvel at the linking operation ( ld). The result of the victorious command ld -rє і. option -r means " relocatable - relocation", That is, the command file will be moved to the address space, since the absolute addresses and functions are not set in the new one yet.

For the offensive application of representations, the minimal Makefile is necessary for the compilation of the module, which is stored in two files. If your module is stored in one jerel file, then from the aimed butt, you need to fix the meta to revenge the command ld -r.

# You can go to your kernel dzherel directory here, # or you can pass it as a parameter in the "make" wiklik KERNELDIR = / usr / src / linux include $ (KERNELDIR) /. Config CFLAGS = -D__KERNEL__ -DMODULE -I $ (KERNELDIR) / include \ -O -Wall ifdef CONFIG_SMP CFLAGS + = -D__SMP__ -DSMP endif all: skull.o skull.o: skull_init.o skull_clean.o $ (LD) - r $ ^ -o [Email protected] clean: rm -f * .o * ~ core

As soon as you know the damn thing about the make utility, then you can, you can see the rules for compiling * .c files in the * .o files. Because such rules are not necessary, the make utility, if necessary, will itself rewrite the * .c files in the * .o file. $ (CC)... With a lot of change $ (CFLAGS) vikoristovuyutsya for ordering compilations.

In a short time, if you want the module to be entangled into the kernel. We already said that for all of us we will be able to use the insmod utility, as I will tie all the unimportant symbols (function wicks and in.) Of the module from the symbol table of the running kernel. However, on the view of the linker (for example, such a yak ld), there is not a change in the module's disk file, but the linking of the module object to the operating memory, which is linked to the kernel. The insmod utility can accept command row options. You can admire the details through man insmod... You can, for example, designate a singing target and a string change of your module set value before linking the module to the kernel. In such a rank, if the module is correctly split, it can be adjusted at the stage of fixing. This way of configuring the module gives a lot of tediousness to the configuration at the stage of compilation. Configuring at the stage of pre-assignment is explained in the section "Manual and automatically configurable" for more details.

Deyakim readers will be able to find details of robotic utilities insmod. The insmod implementation is not based on some of the system wiklicks found in kernel / module.c. The sys_create_module () function creates a lot of memory in the kernel address space to create a module. The memory is shared with the additional function vmalloc () (div. Rozdil "vmalloc and Friends" in section 7 "Getting Hold of Memory"). The system wikelik get_kernel_sysms () rotates the kernel symbol table, as it will be vicoristan to display the real address of the objects when linking. The sys_init_module () function copies the general code of the module into the address space of the kernel and the wikclicks for the initialization of the module function.

If you wonder at the kernel code dzherel, then you will know the names of the system wikis there, which can be repaired from the sys_ prefix. Tsei prefix victories only for systemic victories. Some of the functions are not guilty of this. May the price be on the top of the page when the kernel code was processed with the help of the grep joke.

fallow version

If you don’t know anything more than that, it’s said here, then, better for everything, the modules you blame will be recompiled for the skin version of the nucleus, like the stench there will be linking. The skin module is responsible for the symbol, titles __module_kernel_version, The value of yakogo
Test the version of the streaming kernel with the insmod utility. Tsey the symbol of embroidery in the section .modinfo files in ELF (Executable and Linking Format). More details are explained in Chapter 11, "kmod and Advanced Modularization". Be weasel respect, you can download versions only for versions of the 2.2 and 2.4 kernels with the help of version control. In the kernel of version 2.0, the price is shown in a cheap way.

The compiler is to assign a symbol everywhere, if headers are included ... To that, in the hovering earlier, the hello.c application did not describe the symbol. This also means that if your module is stored with no files in the dzherel, you must include the file in your code only once. Vinyatka є vipadok vikoristannya viznachennya __NO_VERSION__, In which we can learn more.

The lower point is the value of the symbol described in the module.h file, and the kernel code 2.4.25.

Static const char __module_kernel_versio / PRE__attribute __ ((section (". Modinfo"))) = "kernel_version =" UTS_RELEASE;

If the module is modified due to the inconsistency of versions, it is possible to test the module by passing the insmod key into the row of parameters. -f(Force). This way of securing the module is not safe, nor is it ever successful. Explain the reasons for the possible misfortunes to complete it is important. It is possible that the module will not be locked up due to the lack of interconnection of the symbols during linking. In general, you should not forget about the pardon. The reasons for failure can be found in the change of robots or the structure of the nucleus. In general, the blocking of the module can lead to serious pardons for the period of vikonannya, as well as to the collapse of the system (system panic). Remaining will serve as a good incentive for the revision of the system and version control. Version inconsistency can be controlled more elegantly when you control versions in the kernel. This is discussed in detail in the "Version Control in Modules" section in Chapter 11 "kmod and Advanced Modularization".

If you want to compile your module for a particular kernel version, please include the header file from the kernel version itself. Have a description of the application Makefile for vysnachennya directory for the distribution of cich files vikoristovuvalasya zminna KERNELDIR... Such an individual compilation is not, with the presence of a kernel dzherel. Also, it is often the case that the appearance of the older versions of the kernel in the tree of directories. All aiming at the bottom of the butt of the modules vikoristovuyt zminnu KERNELDIR to add the distribution to the directory of the dzherel this version of the kernel, in which the linking of the selected module is transferred. To add a directory, you can use a system change, or transfer it through the parameters of the command line for the make utility.

When the module is locked, the insmod utility will use its own power to joke about the module's files, look at the version of the fallen catalogs and fix it from the points / Lib / modules... I wish the old version of the utility included a joke in a stream catalog, at once such behavior is unacceptable for reasons of failure (also problems, PATH). In such a rank, if you want to lock the module from the stream catalog, you can add it to the style ./module.o... This is how the module can be used for any version of the insmod utilities.

In some cases, you can access the kernel interfaces, as may be seen in versions 2.0.x and 2.4.x. In general, you will need to go into the macro to help it out, so I will start a threading version of the kernel. Danish macro of stitching into headers ... There is also a drop in the visibility of the interfaces with such victories. It can be broken either immediately along the description, or in the final section, in a special section for assigning fallowness versions. Vinos is a detail in the section around it, in some kind of vipadks, letting you not speed up the description according to the kernel version 2.4.x.

In headlines linux / version.h The values ​​of the onset macros linked to the values ​​of the kernel version.

UTS_RELEASE Macro, expanding in a row, will describe the version of the core of the streaming
cob tree codes. For example, the macro can be expanded to taku
row: "2.3.48" . LINUX_VERSION_CODE The whole macro expands in a binarized version of the kernel, according to
one byte per skin part of the number. For example, binarne
appended for version 2.3.48 bude 131888 (dozens
for hex 0x020330). Mozhlivo, bіnarne
yyavlenya will be given to you more than a string. Respect, take
the declaration of permission to describe no more than 256 options in the skin
parts of the number. KERNEL_VERSION (major, minor, release) This macro value is allowed by using "kernel_version_code"
from individual elements to the warehouse version of the core. by the way,
close up KERNEL_VERSION (2, 3, 48)
expand to 131888. The macro value can be adjusted manually when
Routine threaded version of the kernel with the necessary. We will be multiple times
vikoristovuvati tse macro value stretching out all the book.

Pointing to a file linux / version.h for kernel 2.4.25 (the text of the headers is hovered over).

#define UTS_RELEASE "2.4.25" #define LINUX_VERSION_CODE 132121 #define KERNEL_VERSION (a, b, c) (((a)<< 16) + ((b) << 8) + (c))

The version.h headers are included in the module.h file, so, as a rule, you don’t have to include version.h in your module code explicitly. On the other hand, you can make sure to include the version.h headers in module.h for a baked macro __NO_VERSION__... You will be vicoristovuvati __NO_VERSION__, For example, if you need to turn on in a number of files dzherel, which, for the duration, will be linked into one module. nudity __NO_VERSION__ before the included headers module.h zapobіgaє
automatic row description __module_kernel_version abo її equivalent in dzherel files. Mozhlivo, you shouldn't be surprised to be satisfied with the skarg linking at ld -r, Yakuyou will not be worthy of multiple descriptions of symbols in the linking tables. Name, if the code of the distribution module is on the number of files in the folder, if you include headers That is nudity __NO_VERSION__ to be afraid of all files except one. In the book, the butt of the module is pointed, __NO_VERSION__.

A large number of deposits connected with the version of the kernel, can be broken up due to additional logic, prompted by the directives of the preprocessor, with the macro values KERNEL_VERSIONі LINUX_VERSION_CODE... However, reversing the deposits of the versions can greatly speed up the readability of the module code for the distribution of the rough directives #ifdef... To that, singing to the most beautiful solutions є attracting the conversion of deposits into the okremiy header file. The axle of our butt includes headings sysdep.h, Yakiy vikoristovuєtsya for the distribution in new all macro-values, tied with changes in the deposition of versions.

The first version is stale, I would like to imagine being in a bare metal " make install"The scenario of the compilation of our driver. You could have cleaned up the instalation directory, which changed from one to the Victorian version of the kernel, vibrated on the basis of the version.h file. A fragment of the code from the file was displayed. Rules.make, Yakiy vikorystovuєtsya usіma Makefile kernel.

VERSIONFILE = $ (INCLUDEDIR) /linux/version.h VREION = $ (shell awk -F \ "" / REL / (print $$ 2) "$ (VERSIONFILE)) INSTALLDIR = / lib / modules / $ (VERSION) / misc

Witness respect, for the instalation of all our drivers, the misc directory is victorious. Repairing from the 2.4 kernel version, the catalog is recommended for the distribution of features for drivers. In addition, both old and new versions of the modutils package have the misc catalog in their own way for a joke.

Vikoristovuchi is given in the form of INSTALLDIR, the install meta in the Makefile can be seen by the next rank:

Install: install -d $ (INSTALLDIR) install -c $ (OBJS) $ (INSTALLDIR)

Occurrence of platforms

The skin computer platform has its own specialties, which are guilty of being insured by the core developers to achieve the highest productivity.

Kernel vendors may have more freedom in their choice and accept solutions / PCLASS = "western" and vendors of additional data. This same freedom allows you to optimize the code, you can use a maximum of skin specific platforms.

The module code is guilty of but compiled from the compiler options themselves, like the booleans when compiling the kernel. It should be applied until the registration of the same schemes of registration of the processor registers, and until the confirmation of one and the same optimization. file Rules.make Root in the roots of the tree dzherel kernels, including portable fallow trees, which are included in the Makefile compilation. All portable compilation scripts are called Makefile. platform and to take advantage of the values ​​of the changes for the utilization of the make for the current flow configuration of the kernel.

Іnshoyu tsіkаvoi specialty Makefile є support cross-platform or just cross-compilation. Tsei term vikoristovuyutsya if necessary compilation code for іnshoї platforms. For example, if you are using the i86 platform, look to open the code for the M68000 platforms. If you are trying to find a cross compilation, then you will need to replace your compilation tools ( gcc, ld, Ta ін.)
(For example, m68k-linux-gcc, m68k-linux-ld). Vikoristovuvaniyu prefixes can be made either by changing the $ (CROSS_COMPILE) Makefile, or by a command line parameter for utilizing make, or changing the system.

The SPARC architecture is a very special kind of theme, which is to blame for the breakdowns by a certain rank in the Makefile. The programs are intended for the program to run on SPARC64 (SPARC V9) platforms and binaries, as a rule, they are designed for SPARC32 (SPARC V8) platforms. In addition, the compiler will be able to run on SPARC64 (gcc) platforms and generate a generic code for SPARC32. On the other hand, the core is intended for robots on SPARC V9, it is guilty of revealing the code for SPARC V9; All GNU / Linux distributions designated for SPARC64 include a kind of cross-compiler, which you need to vibrate in the Makefile of the kernel compilation script.

I would like an additional list of deposits of all versions and platforms of the trocha, few descriptions here, altogether enough for the display of cross-compilation. To remove additional information, you can admire the Makefile of the compilation script and the kernel jerel file.

Kernel 2.6 features

An hour is not worth it. The new generation of the 2.6 kernel has appeared in a single flash. Unfortunately, the originals of this book do not look at a new core;

You can use the integrated middlewares, such as TimeSys' TimeStorm, to correctly form the key and compilation script for your module, depending on the required version of the kernel. If you choose to write everything independently, then you will get to know the deyak dodatkov information about the main ideas brought by the new core.

One feature of the 2.6 kernel is that you need to validate macros module_init () and module_exit () for explicitly reestablishing and finalizing the functions.

Macro-valued MODULE_LISENCE (), introduced in kernels 2.4 as well as necessary earlier, if you do not want to make additional changes when the module is locked. You can select the next steps to assign licenses for macro transmission: "GPL", "GPL v2", "GPL and additional rights", "Dual BSD / GPL" (select from BSD or GPL licenses), "Dual MPL / GPL "(Vibir mіzh Mozilla or GPL licenses) i
"Proprietary".

Bilsh suttєvim for the new kernel є a new scheme for compiling modules, which is not only the changes in the code of the module itself but in the Makefile of the script of this compilation.

So, the value of the MODULE macro symbol is no longer required in the module code or in the Makefile. If necessary, the new compilation scheme is itself to assign the macro symbols. Also, you do not know explicitly about the __KERNEL__ macros, or new ones, such as KBUILD_BASENAME and KBUILD_MODNAME.

Also, if you are not guilty of starting the optimization level when compiling (-O2 or other), your module will be compiled with this set of rules, including, in fact, optimizing, all of your cores will be compiled automatically. required set of rules.

For three reasons, the Makefile for compiling a module for the 2.6 kernel is a bit simpler. So, for the hello.c Makefile module, it will be the next rank:

Obj-m: = hello.o

However, in order to compile the module, you will need write access to the kernel dzherel tree, so there will be clock files and directories. That is why the command to compile the module up to the 2.6 kernel, to set itself from the stream directory, to revenge the module's dzherel code, is guilty of the following order:

# Make -C /usr/src/linux-2.6.1 SUBDIRS = `pwd` modules

Otzhe, maєmo dzherelo module hello-2.6.c For compilation in kernel 2.6:

//hello-2.6.c #include #include #include MODULE_LICENSE ("GPL"); static int __init my_init (void) (printk ("Hello world \ n"); return 0;); static void __exit my_cleanup (void) (printk ("Good bye \ n");); module_init (my_init); module_exit (my_cleanup);

Apparently, the Makefile is:

Obj-m: = hello-2.6.o

Wiklikє can use make to parse our Makefile with the available parameters:

# Make -C / usr / src / linux-2.6.3 SUBDIRS = `pwd` modules

The normal process of compilation goes through the next standard update:

Make: Enter the directory `/usr/src/linux-2.6.3" *** Warning: Overriding SUBDIRS on the command line can cause *** inconsistencies make: `arch / i386 / kernel / asm-offsets.s" CHK include / asm-i386 / asm_offsets.h CC [M] /home/knz/j.kernel/3/hello-2.6.o Building modules, stage 2. /usr/src/linux-2.6.3/ scripts / Makefile .modpost: 17: *** Uh-oh, you have stale module entries. You messed with SUBDIRS, /usr/src/linux-2.6.3/scripts/Makefile.modpost:18: do not complain if something goes wrong.MODPOST CC /home/knz/j.kernel/3/hello-2.6.mod.o LD [M] /home/knz/j.kernel/3/hello-2.6.ko make: Go from teki `/ usr / src /linux-2.6.3 "

The final result of the compilation will be the module file hello-2.6.ko, which can be inserted into the kernel.

Fatty respect, in the 2.6 kernel the module files may be suffix.ko, and not in the 2.4 kernel.

Kernel symbol table

We also talked about how to use the insmod vikorist table of public-symbols of the kernel when linking the module with the kernel. The table reveals the addresses of the global kernel facilities - functions and changes - which are required for the implementation of modular driver options. The kernel public symbol table can be read in text form from the / proc / ksyms file, so that your kernel will read the / proc file system.

In kernel 2.6, the / proc / ksyms file is renamed to / proc / modules.

When the module is locked, the symbols exported by the module will become a part of the kernel symbol tables, and you can look in / proc / ksyms.

New modules can be customized symbols exported by your module. So, for example, the msdos module relies on the symbols exported by the fat module, and the skin attachment USB will be used in the mode of reading the vicorist symbols in the usbcore and input modules. Such interconnection is realized after the last assigned modules and is called a stack of modules.

A stack of modules is hand-wicked when folding projects of modules are opened. Such an abstraction is easy for the driver code to attach to the hardware-depleted and hardware-independent parts. For example, the set of video-for-linux drivers is stored from the main module, which is the export of symbols for the low-root driver, which is the specifics of the victorious ownership. Welcome to your configuration, you will add the main video module and a module specific to your hardware part. The same rite is used to implement parallel ports and a wide class of attachments that can be connected, such as USB attachments. The stack of systems parallel to the port of readings in Fig. 2-2. The arrows show the interaction between the modules and the kernel software interface. Vzaєmodiya can work both on equal functions, as well as on equal structures of the given, kerovan functions.

Figure 2-2. Parallel port module stack

When you pick up stack modules, manually use the modprobe utilization. The functionality of the utility of modprobe is somewhat similar to the utility of insmod, but when the module is locked, the underlying deposits are reversed, and, if necessary, it is necessary to update the required modules before the necessary storage of the module stack. Thus, a single modprobe command can produce up to several insmod commands. You might say that the modprobe command is an intellectual shell over insmod. You can choose modprobe to replace insmod everywhere, behind a vignette of vypadkiv zavanazheniya vlastnyh modules from the stream catalog, so modprobe looks at only special catalogs for distributing modules, but you can’t satisfy the amount of depletion.

Podil modules on the part of additional help change the hour of development for the task of setting tasks. The price is similar to the podil with the mechanism of implementation and management policy, as discussed in section 1 "Introduced into driver add-ons".

Name the module to realize its functionality without requiring the export of symbols in the background. Export of symbols you will know in the same way as you can get rid of them. You may need to include a special directive for exporting non-static symbols, so in most of the implementation of the utilization modutils all the stinks are exported for umovchannym.

Linux kernel headers provide a convenient way to control the visibility of your symbols in a way that makes it difficult for you to use the kernel symbol tables. The mechanism of descriptions in a whole lot of pratsyuє in kernels is repaired from version 2.1.18. Kernel 2.0 is little callous
the visibility of symbols, such as descriptions in the book.

Since your module is not guilty of exporting symbols in the background, you can explicitly size the offensive macro-click in the module file:

EXPORT_NO_SYMBOLS;

There is a macro-click, which in the file linux / module.h expands into an assembler directive and can be values ​​in any point of the module. However, when the code is turned on, portability on the development kernels is necessary to change the macro-click in the initialization function of the module (init_module), so the same version of the same macro-value was sung by us in our sysdep.h file for the old version of the kernel.

From the side, if you need to export a part of the symbols from your module, then you need to use the macro symbol
EXPORT_SYMTAB... Tsey macrosimvol is guilty of buty values front include the module.h headers. Practices taken from home є
the value of the macro symbol through the prapor -D in the Makefile.

how macrosimvol EXPORT_SYMTAB It is indicated that individual symbols can be exported for an additional bet of macros:

EXPORT_SYMBOL (name); EXPORT_SYMBOL_NOVERS (name);

Be it from the tsikh two macros to make the symbol available outside the module. The visibility of the field in the fact that the macro EXPORT_SYMBOL_NOVERS export symbol without information about version (div. distribution 11 "kmod and Advanced Modularization"). For rejection of more lecture information
read the header file Wanting a victorious one is enough for a practical victorian
macros

Іnіcіalіzatsіya and completion of modules

As it is already misguided, the init_module () function restructures the functional components of the module in the kernel. Writing such a reconstruction, for the vicorist module by programs, there will be an access point to the entry into the module through the interface, which is sup- plied by the kernel.

Modules can reestablish functionless components in the role of those, during re-staging, they appear in the name of the module's functions. At the core function of the restoration, the indicator is transferred to the structure of the tribute, and the indicator is transferred to the function of realizing the proponated functionality.

At section 1 "Introduced into the driver of attachments", the classification of the main types of attachments has been guessed. You can register not only the guessed attachments there, even if they are, right up to software abstractions, such as, for example, files of the file system / proc and in. Everything that can be done in the kernel through the driver software interface can be registered as the driver.

If you want to know more about the types of reestablished drivers on the application of your kernel, you can implement the EXPORT_SYMBOL sequence noise in the kernel jerels and know the entry points promoted by different drivers. As a rule of the function of the re-establishment of vicorists register_,
that is the best way to go! register_ in the file / proc / ksyms for the additional utility grep. As I said, in kernel 2.6.x the / proc / ksyms file is replaced with / proc / modules.

Processing pardons in init_module

Whenever the installer is in the process of making a decision, be guilty of making a mistake before the zupinka of the module is entrusted. The grave can be found, for example, through the memory failure in the system when the structures of the donations have been raised. It's a pity, you can also trap, and good software code is to blame for such a situation.

Anything that has been registered or has been updated before the release of a pardon in the init_module () function needs to be said, for it is self-explanatory, because the Linux kernel does not have to do it in a way that does not If you didn’t see it, for it didn’t be able to see the Viconan restoration, then the kernel will get lost in an unstable mill, and when the module is re-locked
if you cannot repeat the restoration of the already restored elements, or you cannot skasuvati the previously restored restoration, because in the new instance of the init_module () function, you will not have the correct address of the registered functions. To update the coli-standard system, it will be necessary to carry out some small folding tricks, and more often it will be necessary to simply re-install the system.

Implementation of the renewal of the number of the system in the event of an update of the module, we shall reduce the rank of the update to the registration of the goto operator. Call up to the whole operator to be put in the edge negatively, і, navіt, out of hatred, but in the whole situation wіll appear even more corny. To that, in the kernel, the goto operator is often used for processing the grants of the module's initialization.

A simple step-by-step code, on the basis of the real functions of the re-strata and її cassuvannya, demonstrates such a method of processing of pardons.

Int init_module (void) (int err; / * registration takes a pointer and a name * / err = register_this (ptr1, "skull"); if (err) goto fail_this; err = register_that (ptr2, "skull"); if (err) goto fail_that; err = register_those (ptr3, "skull"); if (err) goto fail_those; return 0; / * success * / fail_those: unregister_that (ptr2, "skull"); fail_that: unregister_this (ptr1, " skull "); fail_this: return err; / * propagate the error * /)

At a number of applications, a test is carried out for the restoration of three components of the module. The operator goto vikoristovuyutsya when vyniknenna reestratsii and to produce before the reestablishment of the reestablished components before the zupinka zupinkeniya module.

With the lower butt, the validation of the goto operator does not speed up the reading of the code є the trick of "memorizing" the successful operation of the module and the prompt of cleanup_module () for the transmission of information in the form of information. The cleanup_module () function is designed to display a prompt and automatically trigger when a module is invoked. The value you turned on the init_module () function is guilty
to be a code of pardon of the module. In the Linux kernel, the pardon code is a negative number with no value added to the headers ... Add headers to your module in order to provide symbolic mnemonics for reserved pardon codes, such as -ENODEV, -ENOMEM, etc. Vikoristannya of such mnemonics is used to a good style of programming. However, it should be respected that the versions of the utilities from the modutils package are incorrectly rotated;
in general, a group of pardons of absolutely different nature can be rotated by the init_modules () function. In the remaining versions of the qia package
the prikre the pile of the bullet is corrected.

The code for the cleanup_module () function for a hover view can be, for example, like this:

Void cleanup_module (void) (unregister_those (ptr3, "skull"); unregister_that (ptr2, "skull"); unregister_this (ptr1, "skull"); return;)

If your initialization code and completion is foldable, there are no descriptions here, then the goto statement can be made important to read the text by the programs, so the completion code is due to repetitions in the init_module () function from the goto statements for transitions without For a reason to pick up more tricks when you pick up the cleanup_module () function from the init_module () function to transmit information about the successful update when the module is canceled.

The butt of such written functions init_module () and cleanup_module () is pointed below. In a number of applications, there are globally singing showers who carry information about the exchange of successful innovation.

Struct something * item1; struct somethingelse * item2; int stuff_ok; void cleanup_module (void) (if (item1) release_thing (item1); if (item2) release_thing2 (item2); if (stuff_ok) unregister_stuff (); return;) int init_module (void) (int err = -ENOMEM; item1 = allocate_thing (arguments); item2 = allocate_thing2 (arguments2); if (! item2 ||! item2) goto fail; err = register_stuff (item1, item2); if (! err) stuff_ok = 1; else goto fail; return 0; / * success * / fail: cleanup_module (); return err;)

Regardless of the folding of the initialization of your module, you can use one of the guided methods here to control the initialization of the module.

Trap for the module

The system is to replace the closure of the skin module in order to ensure that the possibility of a safe installation of the module is significant. The system requires information, that is why the module cannot be vivant, because it’s not in vain, because you can’t see the file system driver, because you can’t mount the file system, because you cannot vivant the module of a symbolic attachment vikoristovuє tsei pristіy. In the first place,
can lead to system crash - segmentation fault or kernel panic.

In the latest cores, the system can give you an automatic checker for the vicoriste module mechanism, which can be seen in the offensive distribution. Independently from the version of the kernel, you can manually control these files. So, the code that is transferred to the vicorisovuvati in the old versions of the kernel is guilty of the vicorisovuvati model of the vikoristovuvany module is prompted on the next three macros:

MOD_INC_USE_COUNT Zbіlshu chiller victoriannya of the flow module MOD_DEC_USE_COUNT Zmenshu lichilnik vicoristannya of the flow module MOD_IN_USE Turned right as soon as the lock of the given module went to zero

Macro values ​​in , І stink is manipulated by a special internal structure, given direct access to any neglect. On the right, the internal structure and the way of managing data can change from version to version, at that time, as the called interface of the macros become invisible.

Respect, you don’t need to change MOD_IN_USE in the code of the cleanup_module () function, so that the conversion will be automatically checked before the cleanup_module () wiki into the sys_delete_module () system wiki, which is the value in kernel / module.c.

Correct control of the module's controller is critical for the stability of the system. Remember, the core can be updated automatically at any hour. Often there is a grave in the programmable modules of the field in the wrong control of the caster. For example, if the power is on, the code of the module will be activated when the processing is completed. It is such a programmer for transferring, giving a detector of values ​​for collecting statistics of the module's victorian, at that time, for the best part, it is, in fact, the detector of the flowing occupancy of the module, so that the filler of several processes is the victorian code of the module. In such a rank, when it is processed, it will be fed to the module, guilty viclicati MOD_INC_USE_COUNT be-like diy, i MOD_DEC_USE_COUNT pislya їkh vikonannya.

You can situations, for whatever, for any reasonable reasons, if you cannot vivantage the module, you can use the control of the camera on your victorian. Such a situation is often seen at the stages of the module's development. For example, the process can be interrupted when trying to name a NULL indicator, or you cannot vivant such a module until you turn the indicator on the indicator to zero. One of the possible solutions to such a problem at the stage of the improvement of the module is MOD_INC_USE_COUNTі MOD_DEC_USE_COUNT in the empty code. It is better to fix the field in the left ioctl () wiklik primusovo threw the switch of the victorian module to zero. We can see it in the "Using the ioctl Argument" section in section 5 "Enhanced Char Driver Operations". Apparently, in the driver's ready-for-victorian, there is a deceitful manipulation of the clerk to be guilty of buty, protest, at the stage of goodness, the stench allows you to spare the hour of the salesman and just let it be tolerated.

You can find the stream value of the system file for the skin module in the third field of the skin entry in the / proc / modules file. Tsey file to take revenge on the information about the modules that have been locked at the moment - one row per skin module. The first field of the row is to take revenge on the name of the module, the other field - the size of the borrowings by the module in the memory, and the third field - the exact value of the vikoristannya. Qiu information, in a formatted view,
can be edited with wiklik utility lsmod. Below the butt is pointed to the / proc / modules file:

Parport_pc 7604 1 (autoclean) lp 4800 0 (unused) parport 8084 1 lockd 33256 1 (autoclean) sunrpc 56612 1 (autoclean) ds 6252 1 i82365 22304 1 pcmcia_core 41280 0

Here we have a number of modules that are entangled in the system. A stack of modules is shown in the square arches in the field of plots (residual field of the row). The middle of this can be connected, where the modules parallel to the port communicate through the stack of modules, as shown in Fig. 2-2. The autoclean is used for kerovan modules kmod or kerneld. See section 11 "kmod and Advanced Modularization"). Prapor (unused) means that the module is not victorious at a given moment. In the 2.0 core, the size field rendered information not in bytes, but in the sides, the size for larger platforms was set to 4KBt.

vivantation of the module

For another module vivant, please use the rmmod utility. Vivantation of the module is more simple than the vivantation of the lower stowage, when it is displayed, it is dynamically linked to the core. When a module is invoked, the system wikelike delete_module () will be displayed, which will display the wikelike of the cleanup_module () function, the module will be invoked in the same way that the visitor will bring zero to the robot.

As already mentioned, in the cleanup_module () function, you can see the display of the initialization operation when the module is locked by the cleanup_module () function. Also, the exported symbols of the module are automatically seen.

Explicit function of completion and initiation

As already said, when the module is locked, the core of the wiklick is the init_module () function, and when the module is locked, it is cleanup_module (). However, in the current versions of the kernel, the function often lacks the name. By fixing it from the kernel 2.3.23, there was a possibility of explicitly assigning the name for the function of locking and unlocking the module. Infection, also explicitly assigned names for cich functions є we recommend the style of the program.

Guided butt. If you want to open the initialization function of your module with the my_init () function, and the final one with the my_cleanup () function, replace init_module () and cleanup_module () as soon as possible, then you need to insert two macros.
file dzherel module code):

Module_init (my_init); module_exit (my_cleanup);

Respect, you will include headers in your module for vikorystannya qih .

The success of this style of polygon is in the fact that the skin function of the initialization and completion of the modules in the core can be unique in its own way, which is also useful in the application. Moreover, the victoriancy of these functions will help you to improve the improvement right away because you implement the code of your driver from the viewer of the module, or else you can go to it directly into the kernel. Apparently, the macro value module_init and module_exit is not required, as long as your functions for initialization and completion may have reserved names, so init_module () and cleanup_module (), respectively.

As soon as you get to know the kernel of version 2.2 or more, you can slightly change the form described for the function of initialization and completion. for example:

Static int __init my_init (void) (....) static void __exit my_cleanup (void) (....)

Victorian attribute __init before the completion of the initialization, the initialization of the function will be taken from the memory. However, the process is correct only for the drivers inserted into the kernel, and will be ignored for the modules. Also, for drivers installed in the kernel, the attribute __exit It is designed to ignore the whole function with a symbolic attribute. For modules of warrants, there will also be projections.

Vikoristannya attributes __init__initdata for a description of the tribute) you can change the number of memory vikoristovuvana core. badge of ensign __init The initialization of the function of the module did not bring any vigodi or shkodi. Controlling in this way is not yet implemented for modules, if you want, you can, it will be broken down into the future.

Pidvdennya pidsumkiv

Also, as a result of the submitted material, we can show the following version of the "Hello world" module:

Code to dzherel file module ============================================= #include #include #include static int __init my_init_module (void) (EXPORT_NO_SYMBOLS; printk ("<1>Hello world \ n "); return 0;); static void __exit my_cleanup_module (void) (printk ("<1>Good bye \ n ");); module_init (my_init_module); module_exit (my_cleanup_module); MODULE_LICENSE (" GPL "); ======================== ====================== Makefile for module compilation ========================= ==================== CFLAGS = -Wall -D__KERNEL__ -DMODULE -I / lib / modules / $ (shell uname -r) / build / include hello.o: ===============================================================================

To be honest, when writing the Makefiles, they were keen to please about the utility of GNU make independently by way of formulating an object file on the basis of a changeable CFLAGS and an explicit compiler in the system.

Vikoristannya resources

A module cannot visually display its operation without registering system resources, such as memory, port input / output, memory input / output, transfer lines, as well as DMA channels.

Yak a programmer, who is also guilty of being aware of the dynamic memory of keruvans. The management of dynamic memory in the core is not the least of the principles of their ideas. Your program can be made to remember the vicorist function kmalloc ()і zvіlniti її, for help kfree ()... These functions are even more similar to what you know malloc () and free (), for the same reason, an additional argument is passed to the kmalloc () function - the priority. Name the acceptance priority of the value GFP_KERNEL or GFP_USER. GFP є acronym for "get free page" - take a free page. Dynamic memory management in the core is detailed in section 7 "Getting Hold of Memory".

There is a list of drivers in any of the buildings that need an explicit change in the port of the introduction / vivod, memory of the introduction / vivod and the line change. Just like that, the kernel module can provide easy access to all resources. I would like the system memory to be able to get the audio up-to-date, the memory of the input / output, port and the line of change to play a special role and support the application. For the butt, the driver needs a port, as it is not
everything, as well as that which is needed for the management of the add-ons. Ale the driver cannot vikoristovuvat the resource until quiet feast, as long as he does not change, but the stench does not vikoristovuvat kimos shche.

The area of ​​memory to locate peripheral attachments is called a memory input / output, for that purpose it is simply called memory.

Porti and memory of introduction / delivery

The robot of the mobile driver is already very well stocked for reading and writing ports and memory for input / output. Porti and memory of the introduction / vivedennya ob'єdnanі by the foreign name - region (or region) entered / vivodu.

Unfortunately, it is not on the skin of the tire architecture that it is possible to clearly see the region of introduction / implementation of the skin extension, and it is possible for the driver to allow the adjustment of the proper area, or, perhaps, to write down the operation of the simple reading / reading. Qia problem especially
go to the ISA bus, as it is possible to use it to install simple attachments in a personal computer, and is even popular in the industrial world in the implementation of PC / 104 (div. distributed "PC / 104 and PC / 104 +" chapters 15 ).

If it would not be a vikoristovuvalasya bus for connecting a hardware attachment, the driver of the attachment is guilty of guaranteeing exclusive access to its region of introduction / vivedennya for the installation of a variety of drivers. If the module, if you zvratayuchis until you attach it to make a record in the attachment, then you can get fatal traces of it.

Linux vendors have implemented a mechanism for powering / making regions of the introduction / making the head order for the installation of colossus and outbuildings. The whole mechanism has long been victorious for ports introduced / vivod and recently used for the mechanism of resource management. Respect that this mechanism is an abstraction program and does not expand on hardware capabilities. For example, unauthorized access to ports entered / vivodu on the same device is not a wikkick, be it similar to a "segmentation fault", since the hardware does not deal with the video and authorization of its resources.

Information about the registered resources is available in text form in the files / proc / ioports and / proc / iomem. The information is presented in Linux, which can be repaired from the 2.3 kernel. Nagadaєmo, this book is assigned to the kernel 2.4, and respect for the complexity will be presented in the final release.

spoil

The following is shown as type in the / proc / ioports file:

0000-001f: dma1 0020-003f: pic1 0040-005f: timer 0060-006f: keyboard 0080-008f: dma page reg 00a0-00bf: pic2 00c0-00df: dma2 00f0-00ff: fpu 0170-0177: ide1 01f0-01f7 : ide0 02f8-02ff: serial (set) 0300-031f: NE2000 0376-0376: ide1 03c0-03df: vga + 03f6-03f6: ide0 03f8-03ff: serial (set) 1000-103f: Intel Corporation 82371AB PIIX4 ACPI 1000- 1003: acpi 1004-1005: acpi 1008-100b: acpi 100c-100f: acpi 1100-110f: Intel Corporation 82371AB PIIX4 IDE 1300-131f: pcnet_cs 1400-141f: Intel Corporation 82371AB PIIX4 ACPI 1800-18ff: PCI CardBus # 02 1c00 - 1cff: PCI CardBus # 04 5800-581f: Intel Corporation 82371AB PIIX4 USB d000-dfff: PCI Bus # 01 d000-d0ff: ATI Technologies Inc 3D Rage LT Pro AGP-133

A skin row of a file is displayed in a sixteen-inch view of a range of ports connected with a driver or an attachment with a viper. In early versions of the kernel, the file is in the same format, except that the port architecture was not rendered.

The file can be used to unify the number of ports when a new extension is added to the system. It is especially useful when manually adjusting the jumper (jampers). For a wide variety of people, you can easily marvel at the list of victorious ports and vibrate a wide range for an add-on. I would like to see more modern attachments not to pick up the manual adjustments, so it’s not less, it doesn’t seem to pick up when other gray components are prepared.

However, it is even more important, since the data structure is tied to the / proc / ioports file and is accessible via a software path. To that, if the driver will attach a vison for the introduction of information, you can learn about the range of ports for the introduction / production. This means that if it is necessary to scan for a port in the jokes of a new outbuilding, the driver, in order to eliminate the recording situation in the port, occupied by other people's outbuildings.

Vidomo, scho scanned tires ISA є risikovannyu zavdannyam. To that, the driver's actions, extended with the official Linux kernel, are unique for such a scan when the module is locked. Tim himself, the stench is unique to the rizik of the running system for the recording in the port, victorious to their possessions. Happily, the current architecture of the tires is not easy to deal with to the number of problems.

The software interface is available for access to the registration of the input / output and is stored in the next three functions:

Int check_region (unsigned long start, unsigned long len); struct resource * request_region (unsigned long start, unsigned long len, char * name); void release_region (unsigned long start, unsigned long len);

function check_region () You can get a wiklican to change the occupancy of a given range of ports. Vona turned the negative pardon code (such as -EBUSY or -EINVAL) with negative messages.

function request_region () The display of the address assigned to the range is rotated, in case of success, a non-null indicator. The driver doesn’t need to take a zberigati or vicoristovuvati turns the indicator. Everything you need to change, change it to NULL. The code, which is guilty of only 2.4 kernel (anyway), does not require the check_region () function. I don’t need to think about it this way.
It’s impossible to use the check_region () and request_region () functions between the wiklicks. If you want to save some confusion with older versions of the kernel, the check_region () wiki before request_region () is required.

function release_region () guilty of being a viclikan with a sound driver earlier than victorious ports.

The indicator's reference value is rotated by the request_region () function;

There are three functions, in operation, є .

The butt is pointed at the bottom of the victorian after the victories, so that it is stuck for the restoration of the ports. The butt of captures with the code of the initial driver skull. (The code of the function skull_probe_hw () is not indicative here, so you should have to revenge the hardware-stored code.)

#include #include static int skull_detect (unsigned int port, unsigned int range) (int err; if ((err = check_region (port, range))< 0) return err; /* busy */ if (skull_probe_hw(port,range) != 0) return -ENODEV; /* not found */ request_region(port,range,"skull"); /* "Can"t fail" */ return 0; }

In this application, the availability of the required range of ports will be changed. If the port is inaccessible, then it is not possible to access the equipment.
Determination of porting in the annex can be specified from the hour of scanning. The request_region () function is not guilty, in this application,
end up in failure. The kernel cannot lock more than one module at a time, because the number of victorious ports cannot be
maє.

Whether it is a port of the introduction / vivod, the driver is guilty of being responsible. Our skull driver is robbed in the cleanup_module () function:

Static void skull_release (unsigned int port, unsigned int range) (release_region (port, range);)

The mechanism for supplying / generating resources is similar to the mechanism for restoring / deregistering modules and being implemented on the basis of the goto operator victorious scheme described in the file.

memory

Information about the memory of the input / output is available through the file / proc / iomem. Below is a typical butt of such a file for a personal computer:

00000000-0009fbff: System RAM 0009fc00-0009ffff: reserved 000a0000-000bffff: Video RAM area 000c0000-000c7fff: Video ROM 000f0000-000fffff: System ROM 00100000-03feffff: System RAM 00100000-0022c557: Kernel code 0022c558-0024455f: Kernel data 20000000 2fffffff: Intel Corporation 440BX / ZX - 82443BX / ZX Host bridge 68000000-68000fff: Texas Instruments PCI1225 68001000-68001fff: Texas Instruments PCI1225 (# 2) e0000000-e3ffffff: PCI Bus # 01 e4000000-e7ffffff: PCI Bus # 01 e4000000-eff : ATI Technologies Inc 3D Rage LT Pro AGP-133 e6000000-e6000fff: ATI Technologies Inc 3D Rage LT Pro AGP-133 fffc0000-ffffffff: reserved

The value of the range address is shown in the sixteenth entry. For dermal range Ares indications yogo vlasnik.

The restoration of access to the memory of the introduction / vivod is similar to the restoration of the ports of the introduction / vivod and is prompted in the core by the same mechanism.

To deny and enable the necessary range of memory address entered / vivod, the driver is guilty of vicoristovuvati such wiklici:

Int check_mem_region (unsigned long start, unsigned long len); int request_mem_region (unsigned long start, unsigned long len, char * name); int release_mem_region (unsigned long start, unsigned long len);

Call the driver of the vidomy range the address of the memory entered / vivod, the code for the given resource can be changed, depending on the butt for the range of ports:

If (check_mem_region (mem_addr, mem_size)) (printk ("drivername: memory already in use \ n"); return -EBUSY;) request_mem_region (mem_addr, mem_size, "drivername");

Rospodil resources in Linux 2.4

The threading mechanism of the resource distribution of the buv introductions in the Linux 2.3.11 kernels will prevent the dull access to the management of system resources. The Danish mechanic is briefly described in a whole lot. However, the function of the basic resource distribution (such as request_region () and іn.) Has yet to be implemented in the view of macros and to be used in order to preserve the confusion with the early versions of the kernel. Most of the vapors do not need any nobility about the real mechanics of the rozpodilu, but it can be a little tricky when there are more folding drivers.

The resource management system is implemented in Linux with a lot of resources in a single-minded manner. The global resources of the system (for example, porting / vivodu) can be added to the bottom - for example, they can be added to any slot of the hardware bus. Singing drivers, also, when bazhanny, can add resources on the basis of their logical structure.

The range of visual resources is described through a struct resource structure, which is stripped of headings :

Struct resource (const char * name; unsigned long start, end; unsigned long flags; struct resource * parent, * sibling, * child;);

The global (root) range of resources expands every hour. For example, the structure of resources, which describes the port of the introduction / vivod, is the offensive rank:

Struct resource ioport_resource = ("PCI IO", 0x0000, IO_SPACE_LIMIT, IORESOURCE_IO);

Here is a description of the resource with PCI IO, which covers the range of address from zero to IO_SPACE_LIMIT. The value of the change lies in the form of victorious platforms and possibly 0xFFFF (16-bit address space, for architectures x86, IA-64, Alpha, M68k and MIPS), 0xFFFFFFFF (32-bit, for SPARC space) 0xFFFFFFFFFFFFFFFF (64-bit, SPARC64).

Resource ranges can be linked to an additional allocate_resource () wiklik. For example, before the hour of PCI bus innovation, for the region the address of the bus is a new resource, which is designated as a physical extension. If the kernel code is running on the PCI bus for the designated ports and memory, then there is a new resource only for all regions and distributions behind other wikkicks ioport_resource () or iomem_resource ().

The driver can simply request a subset of a certain resource (lease a part of a global resource) and indicate how it can be used. To store the resource, click on the request_region () wiki, which will turn the indicator to a new struct resource structure, which will describe the supply of the resource, or NULL in case of pardon. Qia structure є part of the global resource tree. As you already spoke, when the resource was rejected, the driver did not know the value of the indicator.

The reader can look at the details of the resource management diagram in the kernel / resource.c file, which was added in the kernel directory. However, there will be a lot of development in the future to reach the victories' knowledge.

The spherical mechanism has generated resources to bring a subset of resources. On one side, I am clearly aware of the structure of the given nucleus. Once again, I'm going to screw up the / proc / ioports file:

E800-e8ff: Adaptec AHA-2940U2 / W / 7890 e800-e8be: aic7xxx

Adaptec e800-e8ff range A large part of the range by requesting the aic7xxx driver.

With the help of such management of resources, there was a subset of the address space in the range, as they represent the real interconnection of the possession. The resource manager cannot see the same address range, but it can fix the installation of a non-functional driver.

Automatic and manual configuration

The parameters required by the driver can be changed from the system to the system. For example, the driver is guilty of the nobility about input / output addresses and memory ranges. For well-organized bus interfaces, this is not a problem. However, in one, you will need to pass the parameters to the driver, so that you can help him know the power, or allow / fence the deyaky function.

Tsi parameters, which are injected onto the robot driver, lie down in the attachment. For example, it can be the version number installed by the annex. Obviously, such information is necessary for the driver for the correct robot with attachments. The value of such parameters (driver configuration) is to achieve
cunningly zavdannya, how to be victorious at the initialization of the driver.

Namely, there are two ways for rejecting the correct value of this parameter - either it is the correct value of the given parameter - either explicitly, or the driver is independent, based on the experience of possession. I want the autodetection of the attachment to be insane;
For a koristuvach, the configuration is easier to implement. The driver retailer is guilty of realizing the autoconfiguration of the driver everywhere, every now and then, all at once, the driver is guilty of the mechanism of manual configuration. Obviously, manually, the mother has a higher priority for autoconfiguration. At the cob stages of development, start, implement only manual transfer of parameters to the driver. Autoconfiguring, if possible, add more.

Driver's bagato, in the middle of its configurable parameters, the parameters are changed by the driver's operating parameters. For example, IDE drivers to the interface (Integrated Device Electronics) allow the control of DMA operations. So, if your driver is good, autodetection of possession is possible, if you want to control the functionality of the driver.

Values ​​of parameters can be passed in the process of blocking the module with the commands insmod or modprobe. The rest of the hour it became possible to read the values ​​of the parameters from the config file (link /etc/modules.conf). Yak parameters can be passed in whole and string values. Thus, if you need to change the value of the skull_ival parameter and the string value of the skull_sval parameter, you can send the last hour of the module with the additional parameters of the insmod command:

Insmod skull skull_ival = 666 skull_sval = "the beast"

However, the first insmod command can change the values ​​of the module parameters, the module is responsible for making the parameters available. The parameters are stripped of the additional macro-value MODULE_PARM, as indicated in the module.h headers. Macro MODULE_PARM accepts two parameters: іm'ya change і row, which is the first type. Given the macro-values, it was spaced out behind the boundaries of any functions, and invite them to grow on the cob to a file to write the changes. So, there are two guessed parameters that can be denuded in the following way:

Int skull_ival = 0; char * skull_sval; MODULE_PARM (skull_ival, "i"); MODULE_PARM (skull_sval, "s");

At this moment, five types of module parameters are available:

  • b - one-byte value;
  • h - (short) two-byte value;
  • i - the whole;
  • l - dovge tsіle;
  • s - row (char *);

For some string parameters, in modules, the indicator (char *) is guilty of denunciations. The insmod command generates memory for the transferred rows and necessary values. For the additional macro MODULE_PARM, you can format an array of parameters. In general, the whole number, which is transferred to the letter type, is a dovzhin massiv. When two whole numbers are specified with a dash, the stench appears to be the smallest and maximum number of transmitted values. For more detailed robotic intelligence of the given macro-values, return to the file headers .

For example, do not have an array of parameters in the future, but not less than two, and not less than a choter with a number of values. Todi vin can be described in the following order:

Int skull_array; MODULE_PARM (skull_array, "2-4i");

In addition, in the programmer's toolbox there is a macro value MODULE_PARM_DESC, as it allows you to post comments before the parameters of the module are transferred. Some comments are saved in the object file of the module and may be looked at for additional help, for example, the objdump utilities, or for additional automated tools in the administration of the system. Pointingly, the butt of the given macro-value:

Int base_port = 0x300; MODULE_PARM (base_port, "i"); MODULE_PARM_DESC (base_port, "The base I / O port (default 0x300)");

Bazhano, all the parameters of the module have little value for the changes. Zmіna qih value for the help insmod can only be used for every consumer. The module can be overridden by explicitly defining parameters by overriding the current values ​​with the values ​​for the substitutions. You can then implement the mechanism of autoconfiguration on the basis of such a scheme. If the value of the parameters may be the value for the options, then the Autoconfiguration will be displayed. In іnshomu vypadku - vikoristoyutsya current values. In order for the scheme of the procedure to be given, it is necessary that the values ​​for the suggestions did not indicate any of the possible real changes of the system. Todi can be allowed, but such a meaning cannot be installed by the user in manual configuration.

The offensive butt will show how the skull viroblya driver will autodetect the address space of the ports I will attach. At the guided attachment, in the auto-designation, the visor will be able to look at the powerless attachments, at that hour, when manually configured, the driver is interconnected with one attachment. The skull_detect function has also been introduced earlier in the section describing the introduction / vivod ports. The implementation of the skull_init_board () function is not rendered, so yak won
to carry out equipment-fallow іnіtsіalіzatsіyu.

/ * * Port ranges: the device can reside between * 0x280 and 0x300, in steps of 0x10. It uses 0x10 ports. * / #Define SKULL_PORT_FLOOR 0x280 #define SKULL_PORT_CEIL 0x300 #define SKULL_PORT_RANGE 0x010 / * * the following function performs autodetection, unless a specific * value was assigned by insmod to "skull_port_base" * / static int skull_port_base = 0; / * 0 forces autodetection * / MODULE_PARM (skull_port_base, "i"); MODULE_PARM_DESC (skull_port_base, "Base I / O port for skull"); static int skull_find_hw (void) / * returns the # of devices * / (/ * base is either the load-time value or the first trial * / int base = skull_port_base? skull_port_base: SKULL_PORT_FLOOR; int result = 0; / * loop one time if value assigned; try them all if autodetecting * / do (if (skull_detect (base, SKULL_PORT_RANGE) == 0) (skull_init_board (base); result ++;) base + = SKULL_PORT_RANGE; / * prepare for next trial * / ) while (skull_port_base == 0 && base< SKULL_PORT_CEIL); return result; }

Since the configuration changes are only available in the middle of the driver (as it is not published in the kernel symbol table), the programmer can simply simplify the life of the driver not to the vicious preference in the middle of our skull. For koristuvach, ts prefixes mean trochs, and їх visibility will ask for a set of commands from the keyboard.

For the sake of further descriptions, we provide a description of three macro values ​​that allow you to change the contents of the comments in the object file.

MODULE_AUTHOR (name) Rows up the row from the author's name in the object file. MODULE_DESCRIPTION (desc) The row is expanded from the initial description to the module in the object file. MODULE_SUPPORTED_DEVICE (dev) I will expand the row, with the description of the add-on module added by the module. Linux has a tedious and great API for additional, but only one lack. A kernel driver is required for interoperability with the possession and access to the privileged information in the system.

Linux kernel module - the process of compiling binary code, which can be inserted directly into the Linux kernel, right in the 0 circle, and the internal and most stolen ring of commands displayed in the x86-64 processor. Here the code will be copied absolutely without any alterations, but then on the name of the system and access to any resources of the system.

Chi is not for mere mortals

Writing a Linux kernel module is not busy for people with weak nerves. Zmіnyuchi the core, see rizikuєte vratiti danі. The kernel code does not have the same standard code, as in the latest Linux add-ons. If you grab a pardon, then hang up the whole system.

The situation is overwhelmed by the fact that the problem does not necessarily manifest itself all at once. If the module is in the system immediately after being locked, then it is the most beautiful scenario. Chim more there is a code, it is more risik of endless cycles and turns of memory. If you do not care, then the problem will become step by step build-up in the world of robotic machine. The important structure of the given buffer and the rewrite of the buffer can be overwritten.

It is possible in the main forgetting of the traditional paradigms of the development of documents. As long as the module is installed and updated, you will write the code that responds to the system pods, and not the code according to the last template. With robots with a core, you write the API, not the add-ons themselves.

You also have no access to the standard library. If the kernel wants to do something like a printk function (to serve as a substitute for printf) and kmalloc (which is similar to malloc), in the main you need to use one of them. Before that, after vivantage of the module, I will have to clean it up after myself. There are no collection of smittya.

necessary components

First of all, I’m going to turn over to the obviousness of all the necessary tools for a robot. Naygolovnishhe, a Linux machine is required. I know, the price is unsuitable! If I want to be a Linux distribution, in all applications I have a vicious Ubuntu 16.04 LTS, so in the development of other distributions you can easily change the installation commands.

In other words, a physical machine is required, or a virtual machine. Especially I vvazhayu for beautifully stylish on virtual machines, please select yourself. Rajah will not vikoristovuvati your main car through the loss of tribute, if you make a pardon. I seem to say "if", and not "like", then I would like to move the car through the process. Your remaining changes in the code can still be found in the write buffer at the time of the kernel panic, so your messages can be processed. Testing in virtual machines

First of all, if you want some of the nobility C. The robust middle ground C ++ is too big for the kernel, so you need to write on a clean bare C. For the interaction with the possessions, do not get the knowledge of the assembler.

Installing the middle of the outlet

On Ubuntu, you need to run:

Apt-get install build-essential linux-headers-`uname -r`
Install the available tools and kernel headers required for this stock.

Put on the bottom of the allowance, so you praise the z-pid of the zvychay koristuvach, and not the root, but you have more sudo privileges. Sudo is required to lock the kernel modules, but I want to try it out as far as possible outside the root.

fix

Proceed to writing the code. Pidgotuєmo our middle:

Mkdir ~ / src / lkm_example cd ~ / src / lkm_example
Launch the love editor (in my vim) and open the lkm_example.c file like this:

#include #include #include MODULE_LICENSE ("GPL"); MODULE_AUTHOR ("Robert W. Oliver II"); MODULE_DESCRIPTION ("A simple example Linux module."); MODULE_VERSION ("0.01"); static int __init lkm_example_init (void) (printk (KERN_INFO "Hello, World! \ n"); return 0;) static void __exit lkm_example_exit (void) (printk (KERN_INFO "Goodbye, World! \ n");) module_init (lkm_example_init ); module_exit (lkm_example_exit);
We have designed the simplest and most flexible module, which can be readily presented on the following part:

  • The include has re-secured header files that are needed to distribute the Linux kernel.
  • At MODULE_LICENSE you can set a different value, from the license of the module. To re-view the list, run:

    Grep "MODULE_LICENSE" -B 27 / usr / src / linux-headers-`uname -r` / include / linux / module.h

  • We will set up init and exit as static functions, which rotate whole numbers.
  • Beastly respect for victorian printk replace printf. Also printk parameters are displayed as printf. For example, Prapor KERN_INFO for the denunciation of the priority of logging for a particular row should be applied without Komi. The kernel is sorted out with multiple speeches in the middle printk function to save stack memory.
  • In the file, you can check module_init and module_exit and enable the function of entailing and invoicing. All this gives you the power of a great number of functions.
However, we cannot compile the file yet. Makefile required. There is enough of such a basic stock. Beastly respect, so make even vibaglivy to glades and tabam, so re-concatenate, how vicorist tabi replace the probes de nibble.

Obj-m + = lkm_example.o all: make -C / lib / modules / $ (shell uname -r) / build M = $ (PWD) modules clean: make -C / lib / modules / $ (shell uname -r ) / build M = $ (PWD) clean
As soon as make is launched, it is the fault of our module successfully compiled. The resulting file will be lkm_example.ko. As soon as you look like pardons, turn them over, so that the paws in the output code are set correctly, and not vaguely in the UTF-8 code.

Now you can use the module and convert it. To run mo:

Sudo insmod lkm_example.ko
If everything is fine, then you won't beat anything. The printk function will not write output to the console, but to the kernel log. For a peek, you need to run:

Sudo dmesg
You are guilty to patch the row "Hello, World!" with a mіtkoy hour on the cob. This means that our kernel module has been locked and successfully written down in the kernel log. We can also change how the module is in memory:

Lsmod | grep "lkm_example"
To view the launcher mo:

Sudo rmmod lkm_example
As soon as I know to run dmesg, then post "Goodbye, World!" In the journal. You can run lsmod again and change it, so the module is vivant.

Yak bachite, the procedure for testing trocha will be automatic, you can automate the procedure by adding:

Test: sudo dmesg -C sudo insmod lkm_example.ko sudo rmmod lkm_example.ko dmesg
in the Makefile, and then run:

Make test
for testing the module and converting the views to the kernel log without the need to run the command.

Now we have a more functional and absolutely trivial kernel module!

Let's dig a trochie glibshe. If you want the modules of the core of the building, all the views of the buildings, the interaction with the supplements is one of the most popular options for the installation.

Oskіlki dodatki zabonono to re-look the memory in the vastness of the kernel, for interaction with them the API is brought up. If I want technically, there are ways of such interaction, the best way is to attach the file to the file.

Ymovirno, earlier and more, I can see the attachment files. Commands to change / dev / zero, / dev / null and similarly change the add-ons "zero" and "null", which rotate the values.

Our application has a "Hello, World". If the function is not even worse for add-ons, all one thing demonstrates the process of interaction with add-ons through an attachment file.

Axis re-listing:

#include #include #include #include #include MODULE_LICENSE ("GPL"); MODULE_AUTHOR ("Robert W. Oliver II"); MODULE_DESCRIPTION ("A simple example Linux module."); MODULE_VERSION ("0.01"); #define DEVICE_NAME "lkm_example" #define EXAMPLE_MSG "Hello, World! \ n" #define MSG_BUFFER_LEN 15 / * Prototypes for device functions * / static int device_open (struct inode *, struct file *); static int device_release (struct inode *, struct file *); static ssize_t device_read (struct file *, char *, size_t, loff_t *); static ssize_t device_write (struct file *, const char *, size_t, loff_t *); static int major_num; static int device_open_count = 0; static char msg_buffer; static char * msg_ptr; / * This structure points to all of the device functions * / static struct file_operations file_ops = (.read = device_read, .write = device_write, .open = device_open, .release = device_release); / * When a process reads from our device, this gets called. * / Static ssize_t device_read (struct file * flip, char * buffer, size_t len, loff_t * offset) (int bytes_read = 0; / * If we're at the end, loop back to the beginning * / if (* msg_ptr = = 0) (msg_ptr = msg_buffer;) / * Put data in the buffer * / while (len && * msg_ptr) (/ * Buffer is in user data, not kernel, so you can not just reference * with a pointer. The function put_user handles this for us * / put_user (* (msg_ptr ++), buffer ++); len--; bytes_read ++;) return bytes_read;) / * Called when a process tries to write to our device * / static ssize_t device_write (struct file * flip, const char * buffer, size_t len, loff_t * offset) (/ * This is a read-only device * / printk (KERN_ALERT "This operation is not supported. \ n"); return -EINVAL; ) / * Called when a process opens our device * / static int device_open (struct inode * inode, struct file * file) (/ * If device is open, return busy * / if (device_open_count) (return -EBUSY;) device_open_count + +; try_module_get (THIS _MODULE);< 0) { printk(KERN_ALERT “Could not register device: %d\n”, major_num); return major_num; } else { printk(KERN_INFO “lkm_example module loaded with device major number %d\n”, major_num); return 0; } } static void __exit lkm_example_exit(void) { /* Remember - we have to clean up after ourselves. Unregister the character device. */ unregister_chrdev(major_num, DEVICE_NAME); printk(KERN_INFO “Goodbye, World!\n”); } /* Register module functions */ module_init(lkm_example_init); module_exit(lkm_example_exit);

Polished butt test

Now our butt can be robbed more, it’s not just a change in the case of a lock and a lock, so the test procedure is less than a suvor. The Makefile is changed only for the module hitching, without yogo vivantage.

Obj-m + = lkm_example.o all: make -C / lib / modules / $ (shell uname -r) / build M = $ (PWD) modules clean: make -C / lib / modules / $ (shell uname -r ) / build M = $ (PWD) clean test: # We put a - in front of the rmmod command to tell make to ignore # an error in case the module is not loaded. -sudo rmmod lkm_example # Clear the kernel log without echo sudo dmesg -C # Insert the module sudo insmod lkm_example.ko # Display the kernel log dmesg
Now, when you run make test, change the appearance of the major number for the attachment. We automatically assign a kernel to our application. However, the number is required for the opening of the new annex.

Take a number, change it as a result of the make test, and select it for the file attachment, so that you can set up a connection with our kernel module from the open space of a koristuvach.

Sudo mknod / dev / lkm_example with MAJOR 0
(In general, replace MAJOR with the values, we will deny it in the result of the make test or dmesg)

The c parameter in the mknod command tells mknod to open the symbolic attachment file.

Now we can correct it instead of the attachment:

Cat / dev / lkm_example
Or navigate through the dd command:

Dd if = / dev / lkm_example of = test bs = 14 count = 100
You can also edit the access to the file from the data files. It is not necessary to compile additional components - navigate from Python, Ruby and PHP scripts є access to the data.

If we finished with an add-on, I saw my yo and vivantage module:

Sudo rm / dev / lkm_example sudo rmmod lkm_example

visnovok

I am grateful, you are honored with our empty spaces in the vastness of the core. If you want to show primitive butts, and structures can be used for the stem of the power modules, so that the structure can be even more folded.

Just remember that in the open space of the core everything is for your perspective. There, for your code, there is no need for another chance. If you are working on a project for a client, plan a submission in advance, otherwise it will take an hour to improve. The kernel code is guilty of being ideal, as much as possible, in order to guarantee the integrity and reliability of the systems on which they run.

Get ready for the project - please, thank you!
Read also
Sberbank (as well as Oschadbank) Sberbank (as well as Oschadbank) Solution of license problems for Autocad Chi does not start autocad windows 7 Solution of license problems for Autocad Chi does not start autocad windows 7 Instructions for registering the PIN code of the CryptoPro, before the hour of signing up some documents - Instructions - AT Instructions for registering the CryptoPro PIN code, before the hour of signing up some documents - Instructions - AT "PEK-Torg"