bharath
bharath

Reputation: 31

How does loading of kernel module work in linux?

Trying to understand internals of kernel module.

What happens when kernel module is loaded? Is the module run as a different process or part of the kernel code? I.e. where are the text segment and data segment allocated for the loaded module?

Upvotes: 3

Views: 1384

Answers (1)

user123
user123

Reputation: 2884

A module doesn't run in itself it is loaded and the code will run when you call the open/read/write functions of the module which will be presented to user mode as a file.

For x86-64, the kernel is loaded above 0xffff_ffff_8000_0000. The kernel modules will thus get memory allocated somewhere around that.

You can look at the System.map file on the boot partition in the /boot directory to see where the different kernel functions are.

When you call open from C++ on a kernel module's file, you call a thin wrapper in libstdc++ which makes a syscall in the kernel. The syscall will call the open function of your module then return to the caller. It will thus make a small context switch in the kernel. The code is located in the last 2GB of the canonical virtual address space.

The kernel modules are relocatable executables. They will be relocated somewhere in the virtual address space in the kernel's area (upper 2GB). They can land anywhere in the physical address space.

Kernel modules are relocated using the System.map file by the insmod program. The insmod program will call the init function of your module as sudo. Once the module is loaded, nothing runs until you call the open function of the module's file from a user mode process which involves a syscall. The module is simply present in memory somewhere and ready to be called. All functions you call from the module are dynamically linked with the kernel using the System.map file.

Upvotes: 2

Related Questions