Introduction to Linux kernel module programming

Source: Internet
Author: User

Topic: program structure of the Linux kernel module-module load function (required), module unload function (required), module license statement (required), module parameter (optional ), module export symbol (optional), module author's and other information declaration (optional)

A Linux kernel module consists of the following parts.
1. The module Loading Function "specified by module_init ()" (required)
When the kernel module is loaded using the insmod and modprobe commands, the module's loading function is automatically executed by the kernel to complete the initialization of this module.
LINUX module loading functions are declared in the format of _ init. The typical statement is as follows ::
Static int _ init initialization_function (void)
{
/* Initialization Code */
}
Module_init (initialization_function );
The module loading function must be specified in the form of module_init (function name. It returns an integer value. If Initialization is successful, 0 should be returned. If initialization fails, an error code should be returned. In the Linux kernel, the error code is a negative value defined in <Linux/errno. h>, including-enodev,-enomem, and other symbolic values. Returning the corresponding error code is a good habit. Only in this way can the application use perror and other methods to convert them into meaningful error message strings.
In the 2.6 kernel, you can use "request_module (const char * FMT ,...) the function is used to load the kernel module (Note: The previous modules are implemented through insmod and modprobe). The driver developer can call ::
Request_module (module_name );
Or
Request_module ("char-Major-% d", Major (Dev), minor (Dev ));
To load other kernel modules.
In the Linux kernel, all Functions Represented As _ init are stored during connection. init. in the text section, all the _ init functions are in the Section. initcall. init also saves a function pointer. during initialization, the kernel will call these _ init functions through these pointers and release the init section (. init. text ,. initcall. init ).
//////////////////////////////////////// ////////////////////////////
2. The module uninstallation function "specified by module_exit ()" (required)
When you run the rmmod and modprobe-r commands to uninstall the kernel module, the unmount function of the module is automatically executed by the kernel to complete the function opposite to the function loaded by the module.
Linux Kernel Modules are generally indicated by _ exit in functions. The typical form of uninstalling a function is as follows ::
Static void _ exit cleanup_function (void)
{
/* Release code */
}
Module_exit (cleanup_function );
The module uninstallation function is executed when the module is uninstalled. No value is returned. It must be specified in the form of "module_exit (function name.
In general, the module unmount function must implement the opposite functions of the module load function, as shown below ::
1> If the module load function registers XXX, the module unload function should deregister xxx;
2> If the module records the dynamically applied memory of the function, the module function should release the memory.
3> If the module load function requests the occupation of hardware resources (such as interruptions, DMA channels, I/O ports, and I/O memory), the module unload function should release these hardware resources.
4> the module loading function is generally used to enable hardware, and the module uninstallation function usually needs to disable hardware.

Like _ init, __exit can also use the corresponding function to automatically recycle memory after running. Actually, __init and _ exit are both macros,
They are defined ::
# DEFINE _ init _ attribute _ (_ Section _ (". init. Text ")))
And
# Ifdef Module
# DEFINE _ exit _ attribute _ (_ Section _ (". Exit. Text ")))
# Else
# DEFINE _ exit/_ attribute _ used ____ attribute (_ Section _ (". Exit. Text ")))
# Endif
//////////////////////////////////////// /////////////////////////////
3. Module license statement "module_license (" Daul BSD/GPL ")" (required)
The module license declares the permission to describe the kernel module. If the license is not declared, the module will receive a warning of kernel contamination when it is loaded.
In the linux2.6 kernel, acceptable licenses include "GPL", "GPL V2", "GPL and additional rights", "dual BSD/GPL", "dual MPL/GPL", and "proprietary"

In most cases, kernel modules should follow the GPL compatibility permission. The most common kernel module in linux2.6 is the module_license ("dual BSD/GPL") Statement declaration module using BSD/GPL dulicense.

//////////////////////////////////////// //////////////////////////////
4. Module parameters (optional)
"Module parameter" is "the value that can be passed to the module when the module is loaded", which corresponds to "all variables" in the module itself ".
We can use "module_param (parameter name, parameter type, read/write permission)" to define a parameter for the module. For example, the following code defines an integer parameter and a character pointer parameter.
Static char * book_name = "A Brief Introduction to Linux device drivers ";
Static int num = 4000;
Module_param (Num, Int, s_irugo );
Module_param (book_name, CHARP, s_irguo );

When loading the kernel module, you can pass parameters to the kernel module,
The format is "sudo insmod/modprobe Module name (for example, Linux. Ko) parameter name = parameter value". If it is not passed, the parameter uses the default value defined in the module.

When passing parameters to the kernel module, the parameter types can be byte, short, ushort, Int, and uint ), long, ulong (unsigned long), CHARP (character pointer), bool, or invbool (Boolean inverse ), when the module is compiled, the types declared in module_param are compared with the types defined in the variables to determine whether they are consistent.

After the module is loaded, the directory named after this module appears under the/sys/Module Directory. When "parameter read/write permission" is 0, it indicates that "the parameter does not exist in the file nodes of the sysfs File System ", if the command line parameter "parameter read/write permission" is not 0 for this module, the parameters directory appears under the directory of this module, contains a series of "file nodes named by Parameters ". At the same time, the permissions of these files are passed into module_param () "parameter read/write permissions", and the content of the file is the parameter value.

In addition, the module can also have an array of parameters in the form of "module_param_array (array name, array type, number leader, parameter read/write permission)", in 2.6.0 ~ 2.6.10: Assign the variable name of the array to the group leader. From version 2.6.10, assign the pointer of the variable to the group leader ", if you do not need to save the number of actually entered array elements, you can set "number leader" to null.

When running the insmod and modprobe commands, use commas to separate the input array elements.
Example ::
# Include <Linux/init. h>
# Include <Linux/module. h>
Module_license ("dual BSD/GPL ");

Static char * book_name = "dissecting Linux Device driber ";
Static int num = 4000;

Static int _ init book_init (void)
{
Printk (kern_info "book name: % s/n", book_name );
Printk (kern_info "book num: % s/n", num );
Return 0;
}

Static void _ exit book_exit (void)
{
Printk (kern_info "book module exit/N ");
}

Module_init (book_init );
Module_exit (book_exit );

Module_param (Num, Int, s_irugo );
Module_param (book_name, CHARP, s_irugo );

Module_author ("chenbaihu ");
Module_version ("V1.0 ");
Module_description ("A simple module for testing module Params ");
Compile this module. The makefile is ::
OBJ-M: = module_param.o
Kernel_path =/usr/src/kernels/2.6.29.6-217.2.16.fc11.i686.pae
// Kernel path
ALL:
Make-C $ (kernel_path) M = $ (PWD) Modules
Clean:
Make-C $ (kernel_path) M = $ (PWD) clean
Then, run the make command to compile and generate the module_param.ko file.
Load this module.
Solution 1 ::
When the "sudo insmod module_param.ko" command is run, the result is ::
Book name: Dissecting Linux Device driber
Book num: 4000
Solution 2 ::
When the "sudo insmod module_param.ko num = 5000" command is run, the result is ::
Book name: Dissecting Linux Device driber
Book num: 5000 // The parameter is passed in.
Enter/sys/module/module_param/and enter the tree command ::
.
| -- Holders
| -- Initstate
| -- Notes
| -- Parameters
| -- Book_name // module parameter file
| '-- Num // module parameter file
| -- Refcnt
| -- Sections
| '-- _ Param
| -- Srcversion
'-- Version
//////////////////////////////////////// //////////////////////////////
5. Module export symbol (optional)
The kernel module can export symbols (symbol, corresponding to functions or variables), so that other modules can use the variables and functions in this module.

The "/proc/kallsyms" file of linux2.6 corresponds to the kernel symbol table, which records the memory address of the symbol and symbol.
The module can use the following macro to export the symbols to the kernel symbol table ::
Export_symbol (symbol name );
Export_symbol_gpl (name-compliant); // only used for the GPL permission module.
Export compliance can be used by other modules. You can declare the following before using it.

Symbol export in the kernel module (example )::
# Include <Linux/init. h>
# Include <Linux/module. h>
Module_license ("Daul BSD/GPL ");

Int add_integar (int A, int B)
{
Return A + B;
}
Int sub_integer (int A, int B)
{
Return A-B;
}

Export_symbol (add_integar); // export the Function
Export_symbol (sub_integer); // export the Function
After compilation, sudo insmod export_symbol.ko adds this module to the kernel.
You can find add_integae/sub_integer information from "/proc/kallsyms.
Run the "cat/proc/kallsyms | grep integar" command to view the following results ::
F99f8048 R _ ksymtab_add_integar [export_symbol]
F99f805c R _ kstrtab_add_integar [export_symbol]
F99f8000 t add_integar [export_symbol]

6. Module author and other information (optional)
Module_autor ("author information ");
Module_description ("module description ");
Module_version ("version information ");
Module_alias ("alias information ");
Module_device_table ("device table information ");
For USB, PCI, and other device drivers, a module_device_table is usually created, indicating the list of devices supported by the driver.

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.