Kernel Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system.
For example, one type of models is the device driver, which allows the kernel to access hardware connected to the system.
How to write simple kernel Module?
This is the first step for any kernel programmer. If you are writing any new application in kernel then starts with simple kernel module.
Any kernel module must have two functions. one is init_module(__init) and cleanup_module (or __exit).
init_module: Initialize the module(i.e. Load the module) e.g: register interrupt handler, add system call
cleanup_module: Undoes whatever init_module did so module can be unloaded safely.
All Modules need two header files: include <linux/module.h> , include <linux/kernel.h>
Module should specify License( Called as Module Licensing). This can be Specified with MOD_LICENSE() macro.
If an unlicensed module loaded, kernel tainted: hellomod: module license ‘unspecified’ taints kernel
Options found in linux/module.h
GPL
Dual BSD/GPL
Proprietary
Simple Example of a Module:
#include <linux/module.h>
#include <linux/kernel.h>
int init_module( void )
{
printk( “<1>Hello, everyone!\n” );
return 0; // SUCCESS
}
void cleanup_module( void )
{
printk( “<1>Goodbye everyone\n” );
}
MODULE_LICENSE(“GPL”);
Module Makefile < The file name(hello.c) and .ko(Hello.ko) name should be different >
obj-m += Hello.o
Hello-objs := hello.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
How to Load or UnLoad the Module
Load Module in to Kernel < Modules can be Loaded and unLoaded with root Login only>
root# insmod Hello.ko
unLoad (remove) Module from Kernel
root# rmmod Hello
Find the Module
root# lsmod | grep Hello
How to check printk messages in Linux Machine
root# cd /var/log/
root# vi messages