Wednesday, December 29, 2010

How to write kernel model

1. install kernel-devel on CentOS 5.5 (kernel-dev on Ubuntu)
$ yum update // upgrade your kernel to latest kernel version
$ yum install kernel-devel // install kernel development library at /lib/module/
This is the source code header for current Linux kernel. You could check if they match each other.
$ uname -r
$ ls /lib/moudle/

2. write hello.c and Makefile 
hello.c:

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

static int hello_init(void)
{
    printk("\nhello, world\n");
    return 0;
}
static void hello_exit(void)
{
    printk("Goodbye, crule world\n");
}
module_init(hello_init);
module_exit(hello_exit);

Makefile:
# Comment/uncomment the following line to disable/enable debugging
#DEBUG = y
# Add your debugging flag (or not) to CFLAGS
ifeq ($(DEBUG),y)
  DEBFLAGS = -O -g # "-O" is needed to expand inlines
else
  DEBFLAGS = -O2
endif
CFLAGS += $(DEBFLAGS) -I$(LDDINCDIR)
ifneq ($(KERNELRELEASE),)
# call from kernel build system, change to you filename
obj-m    := hello.o
else
# remember to set right kernel directory
#KERNELDIR ?= /lib/modules/$(shell uname -r)/build
KERNELDIR ?= /lib/modules/2.6.18-194.26.1.el5/build
PWD       := $(shell pwd)
default:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) LDDINCDIR=$(PWD)/../include modules
endif
clean:
    rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions
depend .depend dep:
    $(CC) $(CFLAGS) -M *.c > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif

3.  install module, test, remove module
$tail -f /var/log/message // you will see message "hello word!" when install module
$insmod hello.ko // install module
$lsmod | grep hello // you will see module has been installed
$rmmod hello // remove the module

4. Addition info
LDD book: http://lwn.net/Kernel/LDD3/
Example source code: http://examples.oreilly.com/9780596005900/
BIOSren pdf tutorial: http://linux.chinaunix.net/bbs/viewthread.php?tid=1042600&extra=page%3D1%26amp%3Bfilter%3Ddigest

In example source code:  examples/sample/ directory is the sample example.

No comments: