Kernel Module - FrankBau/meta-marsboard-bsp GitHub Wiki

A loadable kernel module (LKM) is a file (with extension .ko for "kernel object") containing code that will be executed in Linux kernel mode. In many cases a kernel module is a driver, i.e. it controls a piece of hardware (a LED, a servo motor,...) and exposes an API (applications programmer interface) to other software running in user mode.

A loadable kernel module is not integrated in the kernel, but can be loaded and unloaded during runtime which greatly simplifies the development process.

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

Prerequisites:

Open a bitbake shell 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: [Hello World](Kernel Module 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.