Skip to content

Latest commit

 

History

History
executable file
·
134 lines (90 loc) · 3.55 KB

File metadata and controls

executable file
·
134 lines (90 loc) · 3.55 KB

Overview

Notes on creating device drivers and kernel modules

Reference

Books

YouTube Videos

Terminology and Concepts

Refer to my KernelGlosssaryConcept document.

Important Directories and Files

Refer to my separate KernelDirectoriesAndFiles document

Tools

insmod

You use insmod to load a kernel module

sudo insmod mykrnlmod.ko

Assumes you are in the directory for mykrnlmod.o, otherwise provide the path

rmmod

You use rmmod to unload a kernel module

sudo rmmod mykrnlmod

Note: 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.

modprobe

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)

dmesg

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:

dmesg

To display the messages and then clear all existing messages:

sudo dmesg -c

lsmod

List modules, their size, how many times it's used and by what

lsmod | sort | less

custom shell script to list module files *.ko

#!/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 -u

Compiling the Module

The 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

Examples

Simple Example

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");