Notes on creating device drivers and kernel modules
- Linux Device Drivers, 3rd Edition. The free PDF version of this O'Reilly book by Greg Kroah-Hartman, et al, available here.
- Syscalls, Kernel vs. User Mode and Linux Kernel Source Code
- Linux kernel driver writing tutorial (USB) by Greg Kroah-Hartman
Refer to my KernelGlosssaryConcept document.
Refer to my separate KernelDirectoriesAndFiles document
You use insmod to load a kernel module
sudo insmod mykrnlmod.koAssumes you are in the directory for mykrnlmod.o, otherwise provide the path
You use rmmod to unload a kernel module
sudo rmmod mykrnlmodNote: no extension is used here, as it was with insmod. You also do not need to provide a path if you are not in the directory.
Adds and removes modules from the kernel. Provides more options than insmod and rmmod. Used in /etc/init.d/kmod to load kernel modules from /etc/modules (although mine was empty, so it may not do this anymore)
The dmesg command allows you to see messages written inside the kernel ring/space. Very useful for viewing the output of your module.
To display the messages:
dmesgTo display the messages and then clear all existing messages:
sudo dmesg -cList modules, their size, how many times it's used and by what
lsmod | sort | less#!/bin/bash
#
# find_all_modules.sh
# From Chapter 7 of Linux Kernel in a Nutshell
#
for i in `find /sys/ -name modalias -exec cat {} \;`; do
/sbin/modprobe --config /dev/null --show-depends $i ;
done | rev | cut -f 1 -d '/' | rev | sort -uThe compile process needs access to the kernel source tree. This is best done with a make file that has a reference to this directory. Here is an example of a simple make file to do this:
obj-m += mykrnlmod.o
KDIR=/home/<username>/source/kernel/linux-4.14
all:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
rm -rf *.o *.ko *.mod.* *.symvers *.order
This code simply prints a message on loading, and another message on unloading, they can be viewed using the dmesg command.
// mykrnlmod.c
//
// Displays an initialization message upon loading the module, and an exit
// message when unloading the module. These messages are viewed by the
// 'dmesg' command without parameters. To clear the kernel messages use
// 'sudo dmesg -c', which will display them before clearing them.
//
// Load with 'sudo insmod mykrnlmod.ko'
// Unload with 'sudo rmmod mykrnlmod'
#include <linux/module.h>
#include <linux/init.h>
static int my_init(void) {
printk(KERN_INFO "mykernlmod: module loaded at 0x%p\n", my_init);
return 0;
}
static void my_exit(void) {
printk(KERN_INFO "mykernlmod: module unloaded from 0x%p\n", my_init);
}
module_init(my_init);
module_exit(my_exit);
MODULE_AUTHOR("Traeven");
MODULE_LICENSE("GPL v2");