Linux Kernel module development part-1

Linux kernel module is a piece of code that runs in Linux kernel space, kernel modules can access system hardware, peripheral registers, etc. Kernel modules are used to prevent building entire kernel every time modification is done to code. Kernel modules also used when there is need to interact with kernel data structures like network stack etc.

In this article, we will use Raspberry-Pi as target embedded Linux board to run the kernel modules and ubuntu host for developing and cross compiling.

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>


MODULE_LICENSE ("GPL");
MODULE_AUTHOR ("c2plabs.com");
MODULE_DESCRIPTION("Simple kernel module  example");
MODULE_VERSION ("1.0");


static int simple_init (void)
{

	printk (KERN_ALERT "This is init for simple module \n");
	return 0;
}

static void simple_exit (void)
{
	printk(KERN_ALERT "This is exit for simple module \n");
}	

module_init (simple_init);
module_exit (simple_exit);

Linux Kernel modules are built with Linux kernel header files as a reference as they use kernel APIs which are linked when they are inserted into the kernel using insmod command. Linux kernel uses Kernel Build System which is also called kbuild, so when we write Makefile for compiling Linux kernel module it should adhere to the kbuild system. A detailed description of kbuild is available in the kernel documentation.

Makefile for simple_module:

obj-m := simple_module.o

KDIR :=/home/c2plabs/rpi/linux_src/linux

PWD := $(shell pwd)

default:
	$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

clean: 
	$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) clean

In the above Makefile

obj-m: specifies generate simple_module.ko from simple_module.c file.

KDIR: Path of Kernel headers. #in this case we are doing cross compile for Raspberry Pi. So we have to provide the path of Linux source running on Raspberry Pi.

In case of native Linux host, KDIR is

KDIR := /lib/modules/$(shell uname -r)/build

default target is used to generate kernel module which is a simple_module.ko file. clean target is used to remove previous kernel module file and intermediatory generated files.

For cross-compiling use below command

bash#make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-

Copy this module simple_module.ko to target Raspberry Pi using scp etc.. Do insmod simple_module.ko for inserting module. Debug messages (printk) of kernel module can be viewed using dmesg command.

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *