KernelStuff

Linux Kernel programming made easy – from system calls to drivers and modules, all in one place

Download as .zip Download as .tar.gz View on GitHub

Learn Kernel Programming

Linux kernel programming is a specialized area that involves writing code that interacts directly with the operating system’s kernel. This guide provides an overview of key concepts, practices, and resources for getting started in Linux kernel development.

Table of Contents

Kernel Basics

What is Kernel Module

A kernel module is a piece of code that can be dynamically loaded into or unloaded from the kernel. It allows for kernel extension and modification without needing to recompile or reboot the system.

What is a Device Driver

A device driver is software that enables the operating system (OS) to interact with hardware devices. The device driver acts as a mediator between three key components:

	==================
	=     User       = ---------
	==================        |
	      |                   |
	      |                   |
	      |                   |
	==================        |
	=     Kernel     = Via Device File
	==================        |
	      |                   |
	      |  Device Driver    |
	      |                   |
	==================        |
	=    Hardware     = -------
	==================

Kernel Modules vs Device Driver

Although kernel modules can include device drivers, they serve a broader purpose. A kernel module is a more general concept that refers to any piece of code that can be loaded into the kernel. Device drivers are one specific use case of kernel modules.

Kernel modules are used for:

  1. Device drivers - Managing hardware devices
  2. File systems - Managing data storage
  3. System calls - Enabling kernel-user communication
  4. Network drivers - Implementing networking protocols like TCP/IP
  5. TTY line disciplines - Managing terminal devices

Module Types

  1. In-Tree Modules: Modules included in the official Linux kernel source code.
  2. Out-of-Tree Modules: Modules developed independently of the kernel source and compiled separately.

Modules generally start as “out-of-tree” and become “in-tree” when accepted into the official kernel.

Kernel modules are typically installed in:

/lib/modules/<kernel_version>

Basic Commands

insmod vs modprobe

insmod

modprobe

How modprobe Calculates Dependencies

modprobe relies on depmod to calculate module dependencies. These dependencies are stored in the /lib/modules/$(uname -r)/modules.dep file.

Example of dependencies listed in modules.dep:

kernel/drivers/adm8211.ko: kernel/net/cfg80211.ko kernel/drivers/eeprom_93cx6.ko

When running modprobe adm8211, cfg80211 and eeprom_93cx6 are loaded first, followed by adm8211. To remove the modules, they are unloaded in reverse order.

To update the dependencies, run:

depmod -a