Skip to content

kernel module

Frank Bauernöppel edited this page Mar 19, 2017 · 2 revisions

A Linux kernel module is a piece of code that is executed in kernel mode. This is in contrast to a user mode application. A kernel module can be compiled and linked into the kernel, or, it can be compiled and linked as a separate file, a loadable kernel module (LKM), which can be loaded and unloaded during runtime. This is very convenient during development, because a number of load/unload cycles can be executed without (re-)booting.

Compiling a Kernel Module

The Linux Kernel comes with its own build system kbuild. For starting, you don't need to know much about it, because many build tasks are wrapped by make targets. So you should never invoke the compiler directly.

Compilation can be done either on the target (where the module will be installed and run) or on a separate build host (cross-compilation).

Using a separate build host has many advantages:

  • a build host has usually larger disk space, more memory, and more CPU power so building is faster
  • a running kernel module may easily crash the whole target system which hinders the build process

There is already plenty of general documentation about building kernel modules. So we will focus on cross-compilation of kernel modules in Yocto Project.

We will also build the modules out-of-tree, i.e. the module sources and build artefacts are contained in a separate directory out of the kernel source tree.

Finally, the compilation process needs access to kernel header files and linker information for linking, so some preparation steps are needed:

Compiling a Kernel Module under Yocto Project

Open a bitbake shell on the build host and enter a bitbake command:

bitbake -c devshell virtual/kernel

This will open a new shell in the top level directory of the Linux kernel sources. If you enter ls you will see something like:

COPYING        Kbuild       Makefile        arch    drivers   include  kernel  net      security  ubuntunize
CREDITS        Kconfig      README          block   firmware  init     lib     samples  sound     usr
Documentation  MAINTAINERS  REPORTING-BUGS  crypto  fs        ipc      mm      scripts  tools     virt

and, if you enter make you will get a lot of help information.

Next, we will compile our first module: Kernel Module 1 - Hello World.

Further reading

Please always check, that the online resources are for a compatible kernel version. There is much stuff around for 2.4 and 2.6. kernels, which may or may not work with current kernels.

Clone this wiki locally