Kernel module Programming
First, the preparatory work
Virtual machines: VMware Workstation 12
Operating system: Ubuntu
Current kernel version: Linux-headers-4.4.0-22-generic
Ii. Knowledge of kernel modules
A module is a standalone program that can be compiled separately, but not run independently. It is linked to the kernel at run time as part of the kernel running in kernel space, which is different from the process running in user space. A module typically consists of a set of functions and data structures that implement a file system, a driver, or a function on top of another kernel.
Related directives for kernel modules:
View Kernel version
Uname–a
After the module is compiled, put the module into the kernel.
1. Ko
To view the output of a program
Dmesg
Uninstalling the module
1
Third, the compilation to form a new kernel
According to the school sister's code:
Makefile
1 obj-m:=1. O2 current_path:=$ (shell pwd)3 linux_kernel_path: =/usr/src/linux-headers-4.4. 0-generic4all:5 make-c $ (linux_kernel_path) M=$ (current_path) modules6clean:7 make-c $ (linux_kernel_path) m= $ (Current_path) Clean
Line 1th: Generating the target module for the 1 module
Line 2nd: The current path where the module is located
Line 3rd: Linux_kernel_path back to write your own kernel version corresponding to the kernel source package address.
Make-c $ (Linux_kernel_path) indicates that jumping to the kernel source directory reads where the makefile,m=$ (Current_path) indicates that the current makefile is returned to the current directory to continue execution.
Line 5th: module compilation
Line 7th: Cleanup
1.c
1#include <linux/kernel.h>2#include <linux/module.h>3#include <linux/init.h>4#include <linux/sched.h>5 6 Static structTask_struct *pcurrent;7 Static int__init Print_init (void)8 {9PRINTK (Kern_info"Print Current Task info\n");TenPrintk"pid\ttgid\tprio\tstate\n"); One for_each_process (pcurrent) { APrintk"%d\t",pcurrent->pid); -Printk"%d\t",pcurrent->tgid); -Printk"%d\t",pcurrent->prio); thePrintk"%ld\n",pcurrent->State ); - } - return 0; - } + - Static void__exit Print_exit (void) + { APRINTK (Kern_info"finished\n"); at } - Module_init (print_init); -Module_exit (Print_exit);
Line 1th:linux/kernel.h contains common kernel functions.
Line 2nd:linux/module.h is a necessary header file that must be included in the kernel module code.
Line 3rd: linux/init.h contains macros _init and _exit, which allow the kernel to free up memory.
Line 12th: The function of PRINTK is similar to printf in C, which is defined by the kernel.
Make generate 1.ko files, etc., in Insmod 1.ko the module into the kernel, and finally DMESG to see the output of the compiled program
Iv. problems encountered
The basic problems encountered in making this step are caused by an error in the. c file.
Another problem is that an error occurs when the module is loaded before it is loaded, and then the module is unloaded and then loaded.
Kernel module programming of Linux kernel design and analysis