Linux Kernel Tour __linux

Source: Internet
Author: User
Tags data structures system log

The kernel module is a socket provided externally by the Linux kernel, which is known as the dynamic loadable kernel module (Loadable Kernel module,lkm), and is referred to as a module. The Linux kernel provides a modular mechanism because it itself is a single kernel (monolithic kernel). One of the biggest advantages of a single kernel is the high efficiency, because all the content is integrated, but its disadvantage is that scalability and maintainability is relatively poor, the modular mechanism is to make up for this flaw.

One, what is a module

A module is a stand-alone program that can be compiled separately, but not run independently. It is linked to the kernel as part of the kernel running in the kernel space at runtime, which is different from the process running in user space. A module is usually composed of a set of functions and data structures to implement a file system, a driver, or other functions on the top of the kernel.

Second, the preparation of a simple module

Both the module and the kernel are running in the kernel space, and the module programming is the kernel programming in a sense. Because of each change in the kernel version, some of the function names change accordingly, so module programming is closely related to the kernel version. The following example is for the 2.6 kernel

1. Program examples

Hellomod.c

Hello World driver for Linux 2.6
 #include <linux/module.h>
 #include <linux/kernel.h>
 # Include <linux/init.h>
* Required header file/


static int __init lkp_init (void)
{
printk ("<1>hello, world! From the kernel space...\n ");
return 0;
}


static void __exit lkp_cleanup (void)
{
printk ("<1>goodbye, world! Leaving kernel space...\n ");
 
}
 Module_init (lkp_init);
 Module_exit (lkp_cleanup);
 Module_license ("GPL");


. Description
Line 4th:
All modules are to be module.h with the header file, which must be included in the file.
Line 5th:
The header file kernel.h contains the common kernel functions.
Line 6th:
The header file Init.h contains macros _init and _exit that allow you to free the memory that the kernel occupies.
It is recommended that you explore the code and comments in this file.
第9-12 Line:
This is the initialization function for the module, which must contain such things as code to compile, initialization data structure, and so on.
Line 11th uses the PRINTK () function, which is defined by the kernel and functions like printf () in the C library.
It outputs the information to be printed to the terminal or System log. The <1> in the string is the level of the output,
Indicates immediate output at the terminal.
第15-18 Line:
This is the exit and cleanup function for the module. Here you can do all the cleanup work associated with terminating the driver.
Line 20th:
This is the entry point for driver initialization. For a built-in module, the kernel calls the entry point at boot time;
For loadable modules, it is invoked when the module is inserted into the kernel.
Line 21st:
For loadable modules, the kernel calls the Module_cleanup () function here, and for the built-in modules,
It doesn't do anything.
Line 22nd:
Hint that there may not be a GNU Public License. Several macros were developed in the 2.4 version of the kernel (see modules.h for details).

function Module_init () and Cleanup_exit () are the most basic and necessary two functions in module programming.
Module_init () registers the new features provided by the module to the kernel,
Cleanup_exit () logs out all the functionality provided by the module.

Module programming belongs to the kernel programming, therefore, in addition to knowledge of the kernel related to understand, but also need to understand the knowledge related to the module.

1. Comparison of application and kernel modules
To deepen understanding of the kernel modules, table one gives a comparison between the application and the kernel module program.
Table one application vs Kernel module program comparison

C Language Application Kernel Module Program
Working with functions LIBC Library Kernel functions
Running space User space Kernel space
Run permissions Ordinary users Super User
Entry function Main () Module_init ()
Export function Exit () Module_exit ()
Compile Gcc–c Makefile
Connection Gcc Insmod
Run Run directly Insmod
Debugging Gdb Kdbug, KDB,KGDB, etc.

As we can see from table one, the kernel module program cannot call a function in the LIBC library, which runs in kernel space and only the superuser can run on it. In addition, the module program must use the Module_init () and Module-exit () functions to tell the kernel "I'm Here" and "I'm Gone".

2. Kernel symbol table (if you have difficulty understanding the following 2nd to 4th, you can cross it)

As mentioned earlier, the Linux kernel is a monolithic structure, like a sphere, and a module is a plug-in inserted into the kernel. Although the kernel is not an installable module, Linux also sees the kernel as a "parent" module for the sake of convenience. So how do modules interact with modules, and a common approach is to share variables and functions. But not every variable and function in the module can be shared, the kernel only puts the main variables and functions in each module in a specific section, these variables and functions are collectively referred to as symbols. To the lower which symbols can be shared. The Linux kernel has its own rules. For the kernel-specific parent module, the symbols that can be "moved out" are defined in KERNEL/KSYMS.C, such as the symbols defined by the process management subsystem that can be "removed" as follows:

/* Process Management * *

Export_symbol (Do_mmap_pgoff);

Export_symbol (DO_MUNMAP);

Export_symbol (DO_BRK);

Export_symbol (EXIT_MM);

...

Export_symbol (schedule);

Export_symbol (jiffies);

Export_symbol (Xtime);

...

You may already be familiar with these variables and functions. Where the macro definition export_symbol () itself means "remove symbol." Why do you say "move out"? Because these symbols are inherently symbols inside the kernel, this macro is placed in a public place so that other modules loaded into the kernel can refer to them.

In fact, just knowing the names of these symbols is not enough, and it's important to know that their address in the kernel address space makes sense. Therefore, the following structure is defined in the kernel to describe the symbol of the module:

struct Module_symbol

{

unsigned long value; /* The address of the symbol in the kernel address space * *

const char *name; /* Symbol Name * *

};

We can read all the kernel module "move out" symbols from the/proc/ksyms file, which forms the kernel symbol table in the following format:

memory address symbol name [owning module]

In module programming, you can retrieve the corresponding address from this file according to the symbol name, and then access the address directly to obtain kernel data. The third column "owning module" refers to the module name in which the symbol is located, which is empty for symbols that are removed from the parent module of the kernel.

After the module is loaded, the kernel symbol of the module output can be viewed through/proc/kallsyms under the/proc/ksyms and 2.6 cores under the 2.4 kernel.

3. Module dependencies

As mentioned earlier, the kernel symbol table records the symbols and corresponding addresses that all modules can access. When a new module is loaded into the kernel, some of its stated symbols are registered in the table, and the symbols may be referenced by other modules, which leads to the problem of module dependencies.

A module A refers to the symbol removed by another module B, we say module B is referenced by module A, or module a relies on module B. If you want to link module A, you must first link module B. This interdependent relationship between modules is called modular dependency.

4. Module Reference counter

To ensure that the module is unloaded securely, each module has a reference counter. Increments the counter when the operation involved in the module is performed, decreasing the counter at the end of the operation, and when module B is referenced by module A, the reference count of module B is incremented, the reference ends, and the counter is decremented. When can I uninstall this module? Of course, only when this counter value is 0, for example, when a file system is installed on the system can not unload it, when the file system is no longer used, the reference counter is 0, so you can uninstall.

Four Module compilation

The most important software development tool in Linux is GCC. GCC is the GNU C and C + + compiler. However, in large development projects, there are typically dozens of to hundreds of source files, which can be inconvenient if you manually type the GCC command to compile each time. Therefore, people usually use the Make tool to automate compilation work. This automatic compilation can greatly simplify the development effort and avoid unnecessary recompilation. These include: If you modify only a few source files, recompile the source files only, and if a header file is modified, recompile all the source files that contain the header file.

1. Compile tool make

In fact, the Make tool completes and automatically maintains the compilation work through a file called Makefile. Makefile needs to be written in a syntax that explains how to compile each source file and connect to build an executable file, and define dependencies between source files. The following is a makefile template for the 2.6 kernel modules (see Makefile's notation)

# Makefile2.6
Obj-m + = hellomod.o # generate target file for Hellomod module
Current_path: = $ (shell pwd) #模块所在的当前路径
Linux_kernel: = $ (Shell uname-r) #Linux内核源代码的当前版本
Linux_kernel_path: =/usr/src/linux-headers-$ (Linux_kernel) #Linux内核源代码的绝对路径
All
Make-c $ (Linux_kernel_path) m=$ (current_path) modules #编译模块了
Clean
Make-c $ (Linux_kernel_path) m=$ (current_path) Clean #清理

Note: To type a tab before each command (for example, make command) (press TAB key)

With makefile, executing the Make command automatically forms the associated suffix. O and. ko files.
Here, the module is ready to be inserted into the kernel:
such as: $insmod Hellomod.ko

Of course, to be a system member to insert the module.

After successful insertion, you can view it through the DMESG command, and the last few lines of the screen are the output of your program: hello,world! From the kernel ...


When the module is no longer needed, it can be removed by the Rmmod command, for example

$rmmod Hellomod

The

Modutils is a software package that manages kernel modules. You can get the Modutils (modutils-x.y.z.tar.gz) source code wherever you get the kernel source code, and then choose the highest level patch.x.y.z equal to or less than the current kernel version, which will have insomod in the/sbin directory after installation. Rmmod, ksyms, Lsmod, modprobe and other utility programs. Of course, normally when we load the Linux kernel, modutils is already loaded.
1. The Insmod command
invokes the INSMOD program to insert the module that needs to be inserted into the kernel in the form of the target code. When inserting, Insmod automatically invokes the Init_module () function to run. Note that only Superuser can use this command in the form of
# Insmod  [path] modulename.c
2. The Rmmod command
invokes the RMMOD program to remove modules that have been inserted into the kernel from the kernel. Rmmod automatically runs the Cleanup_module () function, which has the command format:
#rmmod   [path] modulename.c
3. The lsmod command
calls the LSMOD program to display the module information that is being used in the current system. In fact, the function of this program is to read the information in file/proc/modules in the/proc file system in the form of
#lsmod
4. The ksyms command
ksyms This program to display information about kernel symbols and module symbol tables. Similar to Lsmod, its function is to read another file/proc/kallsyms in the/proc file system.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.