Building Kernel Modules - 5.6 | 5. Linux Kernel Modules | Embedded Linux
Students

Academic Programs

AI-powered learning for grades 8-12, aligned with major curricula

Professional

Professional Courses

Industry-relevant training in Business, Technology, and Design

Games

Interactive Games

Fun games to boost memory, math, typing, and English skills

Building Kernel Modules

5.6 - Building Kernel Modules

Enroll to start learning

You’ve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.

Practice

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to Kernel Module Code Structure

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Today, we will discuss how to build kernel modules. Let's start with the basic structure. Every kernel module must have at least an initialization function and an exit function. Can anyone tell me what these functions do?

Student 1
Student 1

The initialization function runs when the module is loaded, right?

Teacher
Teacher Instructor

Exactly! It’s where we register functionalities. And what about the exit function?

Student 2
Student 2

That's used to clean up before unloading the module.

Teacher
Teacher Instructor

Correct! Think of the initialization function as the welcome mat and the exit function as the goodbye wave. This makes it easier to remember their roles.

Student 3
Student 3

How do we define these functions in code?

Teacher
Teacher Instructor

Great question! You define them in C with `static int __init` for initialization and `static void __exit` for exit. Let's look at this example of a simple module:

Teacher
Teacher Instructor

`static int __init example_init(void) { printk(KERN_INFO "Hello, Kernel!\n"); return 0; }` and the exit function as `static void __exit example_exit(void) { printk(KERN_INFO "Goodbye, Kernel!\n"); }`. These functions print messages when loaded or unloaded.

Teacher
Teacher Instructor

Can anyone summarize what we've learned about the module functions?

Student 4
Student 4

The init function welcomes the module, and the exit function says goodbye!

Teacher
Teacher Instructor

Well put! Remember, these functions are essential for the module's lifecycle.

Creating a Makefile

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now that we have our kernel module code, let’s talk about compiling it. Who knows what we need to compile a module?

Student 1
Student 1

We need a Makefile to define how to build it!

Teacher
Teacher Instructor

Exactly! A Makefile specifies how to compile our module. Here’s a simple Makefile example: `obj-m += example.o`. What do you think this line does?

Student 2
Student 2

It tells the compiler that `example.o` is the object file we want to build.

Teacher
Teacher Instructor

Great! And then we have the rules for building and cleaning up. The command to build pulls in the kernel build system. Do you remember how we do that?

Student 3
Student 3

`make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules`?

Teacher
Teacher Instructor

That's right! This command invokes the kernel's build system for our module’s directory. Let's focus on the clean rule. Why do we need it?

Student 4
Student 4

To remove unnecessary files after compilation!

Teacher
Teacher Instructor

Exactly! A good practice to keep our workspace tidy. With this understanding, let’s move on to building a kernel module!

Building and Loading the Module

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now, let’s go through the actual steps to build our kernel module. What’s our first step?

Student 1
Student 1

We need to write our module code and save it.

Teacher
Teacher Instructor

Yes! We would save it as `example.c`. What comes next?

Student 2
Student 2

Then we create our Makefile!

Teacher
Teacher Instructor

Correct! After that, we run the `make` command. What does this command do?

Student 3
Student 3

It compiles our module code into a `.ko` file!

Teacher
Teacher Instructor

Exactly! Once we have the `.ko` file, which command do we use to load the module into the kernel?

Student 4
Student 4

`insmod mymodule.ko`?

Teacher
Teacher Instructor

Right! Now, if we want to unload the module, what command would we use?

Student 1
Student 1

`rmmod mymodule`!

Teacher
Teacher Instructor

Perfect! You all grasped the build and load process well. Remember these commands as we continue exploring kernel modules.

Introduction & Overview

Read summaries of the section's main ideas at different levels of detail.

Quick Overview

This section provides an overview of how to build kernel modules, detailing the source code structure and necessary steps for compilation.

Standard

The section outlines the process involved in creating kernel modules for the Linux kernel, including writing source code, creating a Makefile, and compiling the module. It emphasizes the structure of the source code and the specific commands needed for building the modules successfully.

Detailed

Building Kernel Modules

Building kernel modules involves several key steps that allow developers to create extensions for the Linux kernel. This section covers the necessary source code structure, the use of a Makefile, and detailed commands to compile the modules effectively.

Key Components of Kernel Module Code

The basic structure of a kernel module is defined in C and typically includes:
- Initialization Function: A function that registers the module’s functionalities when loaded. For example:

Code Editor - c
  • Exit Function: A function to deregister functionalities when the module is unloaded. For example:
Code Editor - c
  • Module Metadata: Information about the module, which includes using macros like MODULE_LICENSE, MODULE_AUTHOR, and MODULE_DESCRIPTION.

Creating a Makefile

To compile the kernel module, a Makefile is required. This file typically contains:

obj-m += example.o
all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

This Makefile outlines the object file, build process, and cleaning commands.

Steps to Build a Kernel Module

  1. Write the kernel module code in a file (named example.c for instance).
  2. Create a Makefile in the same directory.
  3. Execute the make command to compile the module.
  4. Upon successful compilation, a .ko file is generated, which can be inserted into the kernel using insmod.

Understanding these processes is fundamental for developing kernel modules that enhance Linux functionality without needing to modify the core kernel.

Youtube Videos

Linux Device Driver Development: From Basics to Implementation 🐧💻
Linux Device Driver Development: From Basics to Implementation 🐧💻
Linux Device Drivers Development Course for Beginners
Linux Device Drivers Development Course for Beginners
Understanding the Structure of a Linux Kernel Device Driver - Sergio Prado, Toradex
Understanding the Structure of a Linux Kernel Device Driver - Sergio Prado, Toradex

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Basic Kernel Module Code Overview

Chapter 1 of 3

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

To build a kernel module, you typically need to write the module’s source code, create a Makefile, and use make to compile the module. Here’s an overview of how to build a kernel module.

Basic Kernel Module Code (example.c):

#include 
#include 
static int __init example_init(void)
{
    printk(KERN_INFO "Hello, Kernel!\\n");
    return 0;
}
static void __exit example_exit(void)
{
    printk(KERN_INFO "Goodbye, Kernel!\\n");
}
module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple kernel module");

Detailed Explanation

To create a kernel module, you start by writing the code that defines the module's behavior and functionality. The provided example shows two key functions: example_init for module initialization and example_exit for cleanup upon removal. These functions use printk to log messages, which can be seen in the kernel logs. Additionally, the module's metadata is defined at the end, which is essential for the kernel to recognize details about your module.

Examples & Analogies

Think of this code as the recipe for a cake. The example_init function is like the step where you preheat the oven and prepare the ingredients, while example_exit is when you clean up the kitchen after baking. The metadata acts like a label on the cake, telling everyone who made it and what type it is.

Makefile for Building the Module

Chapter 2 of 3

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

Makefile to Build the Module:

obj-m += example.o
all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

Detailed Explanation

The Makefile is a crucial file that automates the build process of the kernel module. The line obj-m += example.o indicates that you want to compile example.o into a kernel module. The all target specifies the command to compile the module using the kernel's build system, while the clean target removes any compiled files, allowing for a fresh build.

Examples & Analogies

Consider the Makefile as a set of instructions for putting together furniture. Just like assembly instructions tell you what parts to use and how to put them together, the Makefile guides the build system on how to compile your module. The clean command is like clearing your workspace after you're done assembling to keep everything tidy.

Steps to Build the Module

Chapter 3 of 3

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

Steps to Build the Module:
1. Save the kernel module code into a file (e.g., example.c).
2. Create a Makefile with the contents provided above.
3. Run the following commands to build the kernel module:

   make
  1. Once the module is compiled, you will get a .ko file, which can be loaded using insmod.

Detailed Explanation

To build your kernel module, you first save your code into a file named example.c. Then, you create a Makefile with the necessary instructions for building it. Running the make command compiles your module, generating a .ko file, which is the final output ready to be loaded into the kernel using the insmod command. This process allows the kernel to use your custom functionality defined in the module.

Examples & Analogies

Building a kernel module can be likened to cooking a dish. First, you write down your recipe (code) on a notepad (file), prepare your cooking tools (Makefile), and then follow the cooking steps (commands) to finish the dish. The result is like having your meal ready on the table (the .ko file) that you can serve (load into the kernel) whenever you're ready to eat.

Key Concepts

  • Kernel Module Code Structure: Comprises an initialization function, exit function, and module metadata.

  • Makefile: Essential for compiling kernel modules, defines build and clean rules.

  • Compiling Modules: Involves executing the 'make' command after setting up module code and Makefile.

Examples & Applications

Creating a simple kernel module involves writing an example.c file with the init and exit functions defined.

A Makefile is generated to compile this code, allowing into creating the kernel module in a .ko format.

Memory Aids

Interactive tools to help you remember key concepts

🎵

Rhymes

To build a module, it's easy to say, write the code and then make it play.

📖

Stories

Once upon a time, a coder wanted to add fun features to the kernel. With an init function, it welcomed visitors, and an exit function waved goodbye every time it left.

🧠

Memory Tools

Remember I-EXIT: Initialization first, exit later!

🎯

Acronyms

IMMEDIATE

Initialization

Module

Insert

Get

Exit

Done

All Typical Extensions.

Flash Cards

Glossary

Kernel Module

A piece of code that can be loaded into the kernel to extend its functionality.

Makefile

A file that defines rules for building and managing compilation of kernel modules.

Initialization Function

A function that is executed when the module is loaded into the kernel.

Exit Function

A function that is executed when the module is removed from the kernel.

Reference links

Supplementary resources to enhance your learning experience.