Linux Device driver Second article: How a simple Hello World driver is implemented

Source: Internet
Author: User
Tags echo 7

The previous article introduced the concept of Linux drive, and the basic classification of device drivers under Linux and the basis and difference of each classification, this article describes how to write a simple test driver like Hello World. and the only function of this driver is to output Hello world.

Before writing a specific instance, let's take a look at an important function of the debug program under the Linux kernel PRINTK and several important concepts.

PRINTK is a C-like printf, which is a function of outputting printing information in the kernel. The importance of driving debugging in the future is self-evident, the following first to do a brief introduction.

Level of PRINTK

There are 8 levels in the log level, and the log level of PRINTK is defined as follows (in include/linux/kernel.h):
#define KERN_EMERG 0/* Emergency message, prompted before the system crashes, indicates that the system is not available */
#define Kern_alert 1/* reports that action must be taken immediately */
#define Kern_crit 2/* critical condition, usually involving severe hardware or software operation failure */
#define KERN_ERR 3/* error condition, driver common Kern_err to report hardware errors */
#define Kern_warning 4/* warning conditions to warn of possible problems.
#define Kern_notice 5/* Normal but important conditions for reminding */
#define Kern_info 6/* Prompt information, such as when the driver starts, print hardware information */
#define KERN_DEBUG 7/* Debug Level message */

The default level for PRINTK statements that do not specify a log level is: Default_ Message_loglevel (This default level is generally <4> that is, with kern_warning at one level), defined in kernel/ Can be found in printk.c. Turn on all log information during driver debugging use echo 7 >/proc/sys/kernel/printk, relative to turn off the log using echo 0 >/PROC/SYS/KERNEL/PRINTK .

Here are a few more important concepts that can be understood first, and will be mentioned in the subsequent articles.

Kernel Space and user space

The Linux system is divided into two levels. The kernel runs at the highest level and can do all the work. While the application runs at the lowest level, the processor controls direct access to the hardware and unauthorized access to the memory. Kernel space and user space not only have different priority levels, but also have different memory mappings and have their own address space. See memory management for details.

Applications can only switch from user space to kernel space through system calls or interrupts, where system calls are soft interrupts (0x80 interrupt). The system code that executes the system call runs in the context of the process, which represents the calling process and therefore has access to all the data in the process address space. The kernel code and processes that handle hardware interrupts are asynchronous and independent of any particular process.

concurrency in the kernel

Kernel programming differs from common application programming where concurrency is handled. Most applications, in addition to multithreading, are usually executed sequentially and do not need to be concerned about changing the environment in which other things happen. The kernel code is not so, at the same time, there may be multiple processes using access to the same module.

Kernel programming takes into account the cause of concurrency problems: 1.linux is typically running multiple concurrent processes, and there may be multiple processes using our drivers at the same time. 2. Most devices can interrupt the processor while the interrupt handler is asynchronous and may be called when the driver is trying to handle other tasks. 3. Some code similar to kernel timers is running asynchronously. 4. Running on symmetric multiprocessor (SMP), more than one CPU is running the driver. 5. Kernel code can be preempted.

Current process

The kernel code can gain access to the current process by accessing the global entry. The current pointer points to the process that is currently running. During the execution of Open, read, and other system calls, the current process refers to the process that invokes these system calls. The kernel code can get the information related to the current process through the present pointer.

functions with "__" in the kernel: The kernel API functions have this name, which is usually the underlying function of some interfaces and should be used with caution. In essence, the double underline here is to tell the programmer: call carefully, otherwise the consequences are at your own risk. Taking __init as an example, __init indicates that the function is only used during initialization. After the module is loaded, the module loader throws out the initialization function, which frees up the memory used by the function and makes it available. Note that you do not use the __init, __initdata tags on functions (or data structures) that you still want to use after you end the initialization. Here is a summary of the online excerpt, as follows.

__init, __initdata and other attribute flags, is to put this property's code into the target file's. Init.text section, the data is put into the. Init.data section-This process provides a xxx.lds link script for the relevant target platform to guide LD completion by compiling the kernel.
For code and data compiled into module, the function of the __init property is executed when the module is loaded;
For statically programmed code and data, when the kernel boots, the Do_basic_setup () function calls the Do_initcalls () function, which is responsible for the execution of all. Init section functions.
After initialization is complete, the memory of the function or data identified with these keywords is freed.
1) All functions identified as __init are placed in the. Init.text section, in this section, where the order of the functions is related to the order of the links and is indeterminate.
2) All __init functions in the section. A function pointer is also saved in the Initcall.init, and the kernel invokes these __init function pointers through these function pointers at initialization time, and after the entire initialization is complete, Release the entire init section (including. Init.text,.initcall.init, etc.), and note that the order of these functions in the kernel initialization process is only related to the order of the function pointers here, and the functions described in 1 are independent of the order in the. Init.text section.

Let's look at how a driver's Hello World program is implemented:

#include <linux/init.h> #include <linux/module.h>module_license ("Dual BSD/GPL"), Static int Hello_init ( void) {        printk (kern_alert "Hello, world\n");        return 0;} static void Hello_exit (void) {        printk (kern_alert "Goodbye, cruel world\n");} Module_init (Hello_init); Module_exit (Hello_exit);

The compilation of the kernel module is somewhat different from the compilation of the application, and the compilation command for this Hello World module is:

Make-c/xxx/xxx/kernel_src/ m=$ (PWD) modules

Where/xxx/xxx/kernel_src/is already configured to compile the kernel source path, Ubuntu under the general /lib/modules/$ (shell uname-r)/build directory.

This function has only two functions, one is hello_init, executed at insmod time, this is the initialization function of the module, and the other is hello_exit, executed at Rmmod, is the function to be executed when the module is unloaded. The only function of this module is to output Hello,world at the time of Insmod, and output Goodbye,cruel world when rmmod.

when writing an application, we are generally composed of multiple source files, and this time the compilation must not continue to use the command line to compile, it is necessary to use the makefile. Similarly, the driver module compilation also needs to use the makefile, below is one in compiles contains the multiple source code file The driver module to refer to the makefile file.

Ifndef cross_compileexport cross_compile? =arm-none-linux-gnueabi-endifarch? = Armsrc_dir: =/home/XXX/XXXOBJ_DIR  : = $ (src_dir)/objpwd: = $ (shell pwd) linux_src? =/home/xxx/kernelcfg_inc =-i$ (src_dir)-i$ (dir_a)-i$ (dir_b) cfg_ FLAGS + =-o2extra_cflags  + $ (c_flags) $ (cfg_inc) $ (cfg_inc) Obj-m: = Mymodule.omymodule-objs: = A.omymodule-objs + = b . Omymodule-objs + = C.omodules: @make arch=$ (ARCH)-C $ (LINUX_SRC) m=$ (PWD) Modulesclean: @echo "Cleaning ..." rm-f mymodule . Ko mymodule.o mymodule.mod.* modules.order module.symversrm-f $ (MYMODULE-OBJS)

The first time to get blog update reminders, as well as more technical information sharing, welcome to the personal public platform: Programmer Interaction Alliance (Coder_online)

1. help you solve Linux device driver questions directly

2. First time access to more than ten industry technical articles

3. To ask questions in the article, the first time to reply to you, to help you patiently answer

4. Let you and the original author become very good friends, expand their network resources

Sweep the QR code below or search number Coder_online can be followed, we are able to communicate online.

Linux Device driver Second article: How a simple Hello World driver is implemented

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.