Hello World
Topics in this section,
# |
Version |
---|---|
Freebsd |
14.1.0 |
In this program, you are going to learn
How to write a sample kernel module ?
How to write Makefile to compile driver module ?
How to check if module is loaded successfully ?
How to check if module is unloaded successfully ?
How to check prints from kernel modules ?
Create directory using mkdir command
test:~$ pwd
/home/test/
test:~$ mkdir basic_device_drivers
test:~$ cd basic_device_drivers
test:~$ mkdir hello_world
test:~$ cd hello_world
test:~$ pwd
/home/test/basic_device_drivers/hello_world
1#include <sys/types.h>
2#include <sys/systm.h> /* uprintf */
3#include <sys/errno.h>
4#include <sys/param.h> /* defines used in kernel.h */
5#include <sys/module.h>
6#include <sys/kernel.h> /* types used in module initialization */
7
8/*
9 * Load handler that deals with the loading and unloading of a KLD.
10 */
11
12static int
13hello_loader(struct module *m, int what, void *arg)
14{
15 int err = 0;
16
17 switch (what) {
18 case MOD_LOAD: /* kldload */
19 uprintf("Hello KLD loaded.\n");
20 break;
21 case MOD_UNLOAD:
22 uprintf("Hello KLD unloaded.\n");
23 break;
24 default:
25 err = EOPNOTSUPP;
26 break;
27 }
28 return(err);
29}
30
31/* Declare this module to the rest of the kernel */
32
33static moduledata_t hello_mod = {
34 "hello",
35 hello_loader,
36 NULL
37};
38
39DECLARE_MODULE(hello_world, hello_mod, SI_SUB_KLD, SI_ORDER_ANY);
1SRCS=hello.c
2KMOD=hello_world
3
4.include <bsd.kmod.mk>
1$ pwd
2basic_device_drivers/hello_world
3
4
5$ ls
6hello.c Makefile
7
8
9$ make
10
11$ ls
12.depend.hello.o export_syms hello.c hello.o hello_world.ko i386 machine Makefile opt_global.h x86
Load the module using kldload
1$ kldload ./hello_world.ko
2Loaded ./kthread_module.ko, id=8
Run kldstat command to check the loaded modules
1$ kldstat
2Id Refs Address Size Name
3 1 29 0xffffffff80200000 1f6c698 kernel
4 2 1 0xffffffff8216d000 7850 cryptodev.ko
5 3 1 0xffffffff82176000 772c70 zfs.ko
6 4 1 0xffffffff83218000 3220 intpm.ko
7 5 1 0xffffffff8321c000 2178 smbus.ko
8 6 1 0xffffffff8321f000 3360 uhid.ko
9 7 1 0xffffffff83223000 3360 wmt.ko
10 8 1 0xffffffff83227000 209c hello_world.ko
Run dmesg command to check the kernel logs
1$ dmesg
2Hello KLD loaded.
Unload the module using kldunload
1$ kldunload -v ./hello_world.ko
2Unloading hello_world.ko, id=8
Run kldstat command to check the loaded modules
1$ kldstat
2Id Refs Address Size Name
3 1 27 0xffffffff80200000 1f6c698 kernel
4 2 1 0xffffffff8216d000 7850 cryptodev.ko
5 3 1 0xffffffff82176000 772c70 zfs.ko
6 4 1 0xffffffff83218000 3220 intpm.ko
7 5 1 0xffffffff8321c000 2178 smbus.ko
8 6 1 0xffffffff8321f000 3360 uhid.ko
9 7 1 0xffffffff83223000 3360 wmt.ko
Run dmesg command to check the kernel logs
1$ dmesg
2Hello KLD unloaded