SlideShare a Scribd company logo
Introduction to kernel modules
•

Objectives
• Understanding Kernel modules
• Writing a simple kernel module
• Compiling the kernel module
• Loading and unloading of modules
• Kernel log
• Module dependencies
• Modules vs Programs
Kernel modules
•
•
•
•
•
•

Linux kernel has the ability to extend at runtime the set of features
offered by the kernel.
This means that you can add functionality to the kernel while the system
is up and running.
Modules are pieces of code that can be loaded and unloaded into the
kernel upon demand.
For example, one type of module is the device driver, which allows the
kernel to access hardware connected to the system.
Without modules, we would have to build monolithic kernels and add
new functionality directly into the kernel image.
Besides having larger kernels, this has the disadvantage of requiring us to
rebuild and reboot the kernel every time we want new functionality.
Module utilities
•

•
•
•

•

modinfo <module_name>
• Gets information about the module: parameters, license, descriptions
and dependencies
insmod <module_name>.ko
• Load the given module. Full path of module is needed
rmmod <module_name>
• Unloads the given module
lsmod <module_name>
• Displays the list of modules loaded.
• Check /proc/modules file
modprobe
• Loads the kernel modules plus any module dependencies
Write simple module
#include <linux/module.h>
#include <linux/kernel.h>
static int __init hello_init(void)
{
printk(“Hello :This is my first kernel modulen");
return 0;
}
static void __exit hello_exit(void)
{
printk(“Bye, unloading the modulen");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_DESCRIPTION(“Sample module"); MODULE_AUTHOR(Vandana Salve");
MODULE_LICENSE("GPL");
Module explanation
•
•

Headers specific to the linux kernel <linux/xxx.h>
• No access to the usual C library
An initialization function
• Called when the module is loaded using insmod/modprobe tool
• Perform all the initialization functionality
• Returns an error code
• 0- success
• negative value on failure, errors defined in header file
• Declared by the module_init() macro
Module explanation
•

A cleanup function
• Called when the module is unloaded using rmmod tool
• Perform all the cleanup functionality
• Declared by the module_exit() macro.

•

Metadata information
– MODULE_DESCRIPTION
• Add description about the kernel module
– MODULE_AUTHOR
• Add the information about the author of the module
– MODULE LICENSE
• Add license for example GPL
Compiling a module
•
•

•

Kernel modules need to be compiled a bit differently from regular user
space apps.
To learn more on how to compile modules which are not part of the
official kernel, see file linux/Documentation/kbuild/modules.txt.

Option1: Inside the kernel tree
– Well integrated into the kernel configuration/compilation process.
– Driver can be build statistically if needed
Contd…
•

Option 2: Out of tree
– When the code is outside of the kernel source tree, in a different
directory.
– Advantage
• Easier to handle than modifications to the kernel itself.
– Disadvantage
• Not integrated to the kernel configuration/compilation process,
needs to be build separately
• driver cannot be built statistically if needed.
Compiling an out-of-tree module
•

When the kernel module code is
outside of the kernel source tree,
i.e. in a different directory.

Module source
/
path/to/module/
source
Hello.c
Hello.ko
Makefile

Kernel sources
/
path/to/kernel
/sources

Drivers
Kernel
Header files
Makefiles
Makefile for basic kernel module
•

KDIR := /path/to/kernel/sources

obj-m := hello.o
all:
make -C $(KDIR) M=$(PWD) modules
clean:
make –C $(KDIR) M=$(PWD) clean

• Refer Documentation/kbuild/modules.txt for details
Overview of make & makefiles
•
•
•
•
•

•

The “make” program automates the building of software based on
specification of dependencies among the files.
“make” determines which pieces of a large program need to be
recompiled and issue commands to recompile them.
To use make, you must write a file called makefile.
A makefile is simple a way of associating short names, called ‘targets’,
with a series of commands to execute when the action is requested.
$make clean
– Target clean, performs actions that clean up after the compilation—
removing object files and resulting executable.
$make [all]
– Target all, performs action that compile the filesv
Kernel log
•

When a new module is loaded, related information is available in the
kernel log.
– The kernel keeps its messages in a circular buffer.
– Kernel log messages are available through the ‘dmesg’ command
– Kernel log messages can be seen in /var/log/messages and/or
/var/log/syslog file
Module dependencies
•
•
•
•

•

Some kernel module can depend on other modules, which need to be
loaded first.
Dependencies are described in
/lib/modules/<kernel-version>/modules.dep
This file is generated when you run make modules_install
sudo modprobe <module_name>
– Loads all the modules the given module depends on. Modprobe looks
into /lib/modules/<kernel-version> for the object file corresponding
to the given module
Sudo modprobe –r <module_name>
– Remove the module and all dependent modules, which are no longer
needed.
Applications Vs. Kernel modules
Application
• Performs single task from
beginning to end
• Application can call functions,
which it doesn’t define. The
linking stage resolves the external
references loading the
appropriate libraries. E.g libc for
‘printf’ function.

Kernel module
• Module registers itself to serve
the future request and its ‘main’
function terminates on loading.
• The module is linked only to the
kernel and it can only the
functions that are exported by
the kernel.
• No C library is linked with the
kernel.
Functions available to modules
•
•
•
•

In the hello world example, you might have noticed that we used a
function, printk() but didn't include a standard I/O library.
That's because modules are object files whose symbols get resolved upon
insmod'ing.
The definition for the symbols comes from the kernel itself; the only
external functions you can use are the ones provided by the kernel.
If you're curious about what symbols have been exported by your kernel,
take a look at /proc/kallsyms.
Passing command line arguments
•
•

•

Modules can take command line arguments, but not with the argc/argv
you might be used to.
To allow arguments to be passed to your module, declare the variables
that will take the values of the command line arguments as global and
then use the module_param() macro, to set the mechanism up.
At runtime, insmod will fill the variables with any command line
arguments that are given
Contd…
•
•
•

•

$insmod hello_2.ko int_param=50
The variable declarations and macros should be placed at the beginning of
the module for clarity.
The module_param() macro takes 3 arguments:
– the name of the variable,
– its type and permissions for the corresponding file in sysfs.
– Integer types can be signed as usual or unsigned.
If you'd like to use arrays of integers or strings see
– module_param_array() and
– module_param_string().
Advantages of modules
•

Modules make it easy to develop drivers without rebooting: load, test,
unload, rebuild & again load and so on.

•

Useful to keep the kernel size to the minimum (essential in embedded
systems). Without modules , would need to build monolithic kernel and
add new functionality directly into the kernel image.

•

Also useful to reduce boot time, you don’t need to spend time initializing
device that may not be needed at boot time.

•

Once loaded, modules have full control and privileges in the system.
That’s why only the root user can load and unload the modules.
Usage of modules
•
•
•
•
•
•

Character device drivers
Block device drivers
Network device drivers
File systems
Any type of device drivers handling the different types of devices such as
USB, I2C etc. etc.
Kernel modules can be used to implement any functionality needed
runtime on demand

More Related Content

What's hot

Linux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBLinux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKB
shimosawa
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
Satpal Parmar
 
Embedded_Linux_Booting
Embedded_Linux_BootingEmbedded_Linux_Booting
Embedded_Linux_BootingRashila Rr
 
Introduction Linux Device Drivers
Introduction Linux Device DriversIntroduction Linux Device Drivers
Introduction Linux Device Drivers
NEEVEE Technologies
 
Uboot startup sequence
Uboot startup sequenceUboot startup sequence
Uboot startup sequenceHoucheng Lin
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
Emertxe Information Technologies Pvt Ltd
 
linux device driver
linux device driverlinux device driver
linux device driver
Rahul Batra
 
Arm device tree and linux device drivers
Arm device tree and linux device driversArm device tree and linux device drivers
Arm device tree and linux device drivers
Houcheng Lin
 
Kernel module in linux os.
Kernel module in linux os.Kernel module in linux os.
Kernel module in linux os.
MUKESH BADIGINENI
 
Introduction To Linux Kernel Modules
Introduction To Linux Kernel ModulesIntroduction To Linux Kernel Modules
Introduction To Linux Kernel Modules
dibyajyotig
 
LCU13: An Introduction to ARM Trusted Firmware
LCU13: An Introduction to ARM Trusted FirmwareLCU13: An Introduction to ARM Trusted Firmware
LCU13: An Introduction to ARM Trusted Firmware
Linaro
 
Bootloaders (U-Boot)
Bootloaders (U-Boot) Bootloaders (U-Boot)
Bootloaders (U-Boot)
Omkar Rane
 
Monitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstatsMonitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstats
Ben Mildren
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
Emertxe Information Technologies Pvt Ltd
 
LFCollab14: Xen vs Xen Automotive
LFCollab14: Xen vs Xen AutomotiveLFCollab14: Xen vs Xen Automotive
LFCollab14: Xen vs Xen Automotive
The Linux Foundation
 
Linux device drivers
Linux device driversLinux device drivers
Linux device drivers
Abhishek Sagar
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
RuggedBoardGroup
 
Linux Kernel Programming
Linux Kernel ProgrammingLinux Kernel Programming
Linux Kernel ProgrammingNalin Sharma
 
Basics of boot-loader
Basics of boot-loaderBasics of boot-loader
Basics of boot-loader
iamumr
 
Linux programming - Getting self started
Linux programming - Getting self started Linux programming - Getting self started
Linux programming - Getting self started
Emertxe Information Technologies Pvt Ltd
 

What's hot (20)

Linux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBLinux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKB
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 
Embedded_Linux_Booting
Embedded_Linux_BootingEmbedded_Linux_Booting
Embedded_Linux_Booting
 
Introduction Linux Device Drivers
Introduction Linux Device DriversIntroduction Linux Device Drivers
Introduction Linux Device Drivers
 
Uboot startup sequence
Uboot startup sequenceUboot startup sequence
Uboot startup sequence
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
 
linux device driver
linux device driverlinux device driver
linux device driver
 
Arm device tree and linux device drivers
Arm device tree and linux device driversArm device tree and linux device drivers
Arm device tree and linux device drivers
 
Kernel module in linux os.
Kernel module in linux os.Kernel module in linux os.
Kernel module in linux os.
 
Introduction To Linux Kernel Modules
Introduction To Linux Kernel ModulesIntroduction To Linux Kernel Modules
Introduction To Linux Kernel Modules
 
LCU13: An Introduction to ARM Trusted Firmware
LCU13: An Introduction to ARM Trusted FirmwareLCU13: An Introduction to ARM Trusted Firmware
LCU13: An Introduction to ARM Trusted Firmware
 
Bootloaders (U-Boot)
Bootloaders (U-Boot) Bootloaders (U-Boot)
Bootloaders (U-Boot)
 
Monitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstatsMonitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstats
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 
LFCollab14: Xen vs Xen Automotive
LFCollab14: Xen vs Xen AutomotiveLFCollab14: Xen vs Xen Automotive
LFCollab14: Xen vs Xen Automotive
 
Linux device drivers
Linux device driversLinux device drivers
Linux device drivers
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
 
Linux Kernel Programming
Linux Kernel ProgrammingLinux Kernel Programming
Linux Kernel Programming
 
Basics of boot-loader
Basics of boot-loaderBasics of boot-loader
Basics of boot-loader
 
Linux programming - Getting self started
Linux programming - Getting self started Linux programming - Getting self started
Linux programming - Getting self started
 

Viewers also liked

Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
Tushar B Kute
 
Module Programming with Project Jigsaw
Module Programming with Project JigsawModule Programming with Project Jigsaw
Module Programming with Project Jigsaw
Yuichi Sakuraba
 
Generative grammar power point presentation,, ulfa
Generative grammar power point presentation,, ulfaGenerative grammar power point presentation,, ulfa
Generative grammar power point presentation,, ulfamahbubiyahulfah
 
Remote procedure call on client server computing
Remote procedure call on client server computingRemote procedure call on client server computing
Remote procedure call on client server computing
Satya P. Joshi
 
Vfs
VfsVfs
FRT Vol. 5 クラウド時代の企業アプリケーションとマーケティング
FRT Vol. 5 クラウド時代の企業アプリケーションとマーケティングFRT Vol. 5 クラウド時代の企業アプリケーションとマーケティング
FRT Vol. 5 クラウド時代の企業アプリケーションとマーケティング
Yasunari Goto (iChain. Inc.)
 
Global Knowledge Training Courses & Promotion 2015-Sep
Global Knowledge Training Courses & Promotion 2015-SepGlobal Knowledge Training Courses & Promotion 2015-Sep
Global Knowledge Training Courses & Promotion 2015-Sep
Aruj Thirawat
 
Trabalhando com o Moodle e a Comunidade
Trabalhando com o Moodle e a ComunidadeTrabalhando com o Moodle e a Comunidade
Trabalhando com o Moodle e a Comunidade
Daniel Neis
 
STelligence Savvius Thai Datasheet
STelligence Savvius Thai DatasheetSTelligence Savvius Thai Datasheet
STelligence Savvius Thai Datasheet
Aruj Thirawat
 
Caching Data For Performance
Caching Data For PerformanceCaching Data For Performance
Caching Data For Performance
Dave Ross
 
MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)
MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)
MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)Daniel Neis
 
ThaiCert Phishing and Malicious Code Infographic 2015
ThaiCert Phishing and Malicious Code Infographic 2015ThaiCert Phishing and Malicious Code Infographic 2015
ThaiCert Phishing and Malicious Code Infographic 2015
Aruj Thirawat
 
OSSV [Open System SnapVault]
OSSV [Open System SnapVault]OSSV [Open System SnapVault]
OSSV [Open System SnapVault]
Ashwin Pawar
 
SQL Server 簡易診断サービス ご紹介資料
SQL Server 簡易診断サービス ご紹介資料SQL Server 簡易診断サービス ご紹介資料
SQL Server 簡易診断サービス ご紹介資料Masayuki Ozawa
 
SQL Server 現状診断サービス ご紹介資料
SQL Server 現状診断サービス ご紹介資料SQL Server 現状診断サービス ご紹介資料
SQL Server 現状診断サービス ご紹介資料Masayuki Ozawa
 
[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)
[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)
[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)Insight Technology, Inc.
 
Driver development – memory management
Driver development – memory managementDriver development – memory management
Driver development – memory management
Vandana Salve
 
Linux Kernel Development
Linux Kernel DevelopmentLinux Kernel Development
Linux Kernel Development
Priyank Kapadia
 
Sql server 構築 運用 tips
Sql server 構築 運用 tipsSql server 構築 運用 tips
Sql server 構築 運用 tipsMasayuki Ozawa
 
Board support package_on_linux
Board support package_on_linuxBoard support package_on_linux
Board support package_on_linux
Vandana Salve
 

Viewers also liked (20)

Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
 
Module Programming with Project Jigsaw
Module Programming with Project JigsawModule Programming with Project Jigsaw
Module Programming with Project Jigsaw
 
Generative grammar power point presentation,, ulfa
Generative grammar power point presentation,, ulfaGenerative grammar power point presentation,, ulfa
Generative grammar power point presentation,, ulfa
 
Remote procedure call on client server computing
Remote procedure call on client server computingRemote procedure call on client server computing
Remote procedure call on client server computing
 
Vfs
VfsVfs
Vfs
 
FRT Vol. 5 クラウド時代の企業アプリケーションとマーケティング
FRT Vol. 5 クラウド時代の企業アプリケーションとマーケティングFRT Vol. 5 クラウド時代の企業アプリケーションとマーケティング
FRT Vol. 5 クラウド時代の企業アプリケーションとマーケティング
 
Global Knowledge Training Courses & Promotion 2015-Sep
Global Knowledge Training Courses & Promotion 2015-SepGlobal Knowledge Training Courses & Promotion 2015-Sep
Global Knowledge Training Courses & Promotion 2015-Sep
 
Trabalhando com o Moodle e a Comunidade
Trabalhando com o Moodle e a ComunidadeTrabalhando com o Moodle e a Comunidade
Trabalhando com o Moodle e a Comunidade
 
STelligence Savvius Thai Datasheet
STelligence Savvius Thai DatasheetSTelligence Savvius Thai Datasheet
STelligence Savvius Thai Datasheet
 
Caching Data For Performance
Caching Data For PerformanceCaching Data For Performance
Caching Data For Performance
 
MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)
MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)
MoodleMoot Brasil 2011 - O Moodle na UFSC (Infraestrutura de TI)
 
ThaiCert Phishing and Malicious Code Infographic 2015
ThaiCert Phishing and Malicious Code Infographic 2015ThaiCert Phishing and Malicious Code Infographic 2015
ThaiCert Phishing and Malicious Code Infographic 2015
 
OSSV [Open System SnapVault]
OSSV [Open System SnapVault]OSSV [Open System SnapVault]
OSSV [Open System SnapVault]
 
SQL Server 簡易診断サービス ご紹介資料
SQL Server 簡易診断サービス ご紹介資料SQL Server 簡易診断サービス ご紹介資料
SQL Server 簡易診断サービス ご紹介資料
 
SQL Server 現状診断サービス ご紹介資料
SQL Server 現状診断サービス ご紹介資料SQL Server 現状診断サービス ご紹介資料
SQL Server 現状診断サービス ご紹介資料
 
[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)
[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)
[INSIGHT OUT 2011] C12 50分で理解する SQL Serverでできることできないこと(uchiyama)
 
Driver development – memory management
Driver development – memory managementDriver development – memory management
Driver development – memory management
 
Linux Kernel Development
Linux Kernel DevelopmentLinux Kernel Development
Linux Kernel Development
 
Sql server 構築 運用 tips
Sql server 構築 運用 tipsSql server 構築 運用 tips
Sql server 構築 運用 tips
 
Board support package_on_linux
Board support package_on_linuxBoard support package_on_linux
Board support package_on_linux
 

Similar to Kernel module programming

Device Drivers and Running Modules
Device Drivers and Running ModulesDevice Drivers and Running Modules
Device Drivers and Running Modules
YourHelper1
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Tushar B Kute
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modules
Hao-Ran Liu
 
Linux kernel code
Linux kernel codeLinux kernel code
Linux kernel code
Ganesh Naik
 
Course 102: Lecture 25: Devices and Device Drivers
Course 102: Lecture 25: Devices and Device Drivers Course 102: Lecture 25: Devices and Device Drivers
Course 102: Lecture 25: Devices and Device Drivers
Ahmed El-Arabawy
 
JavaScript Module Loaders
JavaScript Module LoadersJavaScript Module Loaders
JavaScript Module Loaders
zeroproductionincidents
 
Linux kernel driver tutorial vorlesung
Linux kernel driver tutorial vorlesungLinux kernel driver tutorial vorlesung
Linux kernel driver tutorial vorlesungdns -
 
Embedded system - embedded system programming
Embedded system - embedded system programmingEmbedded system - embedded system programming
Embedded system - embedded system programming
Vibrant Technologies & Computers
 
PowerCLI in the Enterprise Breaking the Magicians Code original
PowerCLI in the Enterprise Breaking the Magicians Code   originalPowerCLI in the Enterprise Breaking the Magicians Code   original
PowerCLI in the Enterprise Breaking the Magicians Code originaljonathanmedd
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2
Anil Sagar
 
lesson03.ppt
lesson03.pptlesson03.ppt
lesson03.ppt
IraqReshi
 
Pppt
PpptPppt
Linux Device Driver v3 [Chapter 2]
Linux Device Driver v3 [Chapter 2]Linux Device Driver v3 [Chapter 2]
Linux Device Driver v3 [Chapter 2]
Anupam Datta
 
Intro to Drupal Module Developement
Intro to Drupal Module DevelopementIntro to Drupal Module Developement
Intro to Drupal Module Developement
Matt Mendonca
 
Java modulesystem
Java modulesystemJava modulesystem
Java modulesystem
Marc Kassis
 
Device Drivers
Device DriversDevice Drivers
Device Drivers
Kushal Modi
 
Yocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDK
Yocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDKYocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDK
Yocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDK
Marco Cavallini
 
Drupal module development
Drupal module developmentDrupal module development
Drupal module developmentRachit Gupta
 
As7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yongAs7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yongjbossug
 

Similar to Kernel module programming (20)

Device Drivers and Running Modules
Device Drivers and Running ModulesDevice Drivers and Running Modules
Device Drivers and Running Modules
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modules
 
Linux kernel code
Linux kernel codeLinux kernel code
Linux kernel code
 
Studienarb linux kernel-dev
Studienarb linux kernel-devStudienarb linux kernel-dev
Studienarb linux kernel-dev
 
Course 102: Lecture 25: Devices and Device Drivers
Course 102: Lecture 25: Devices and Device Drivers Course 102: Lecture 25: Devices and Device Drivers
Course 102: Lecture 25: Devices and Device Drivers
 
JavaScript Module Loaders
JavaScript Module LoadersJavaScript Module Loaders
JavaScript Module Loaders
 
Linux kernel driver tutorial vorlesung
Linux kernel driver tutorial vorlesungLinux kernel driver tutorial vorlesung
Linux kernel driver tutorial vorlesung
 
Embedded system - embedded system programming
Embedded system - embedded system programmingEmbedded system - embedded system programming
Embedded system - embedded system programming
 
PowerCLI in the Enterprise Breaking the Magicians Code original
PowerCLI in the Enterprise Breaking the Magicians Code   originalPowerCLI in the Enterprise Breaking the Magicians Code   original
PowerCLI in the Enterprise Breaking the Magicians Code original
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2
 
lesson03.ppt
lesson03.pptlesson03.ppt
lesson03.ppt
 
Pppt
PpptPppt
Pppt
 
Linux Device Driver v3 [Chapter 2]
Linux Device Driver v3 [Chapter 2]Linux Device Driver v3 [Chapter 2]
Linux Device Driver v3 [Chapter 2]
 
Intro to Drupal Module Developement
Intro to Drupal Module DevelopementIntro to Drupal Module Developement
Intro to Drupal Module Developement
 
Java modulesystem
Java modulesystemJava modulesystem
Java modulesystem
 
Device Drivers
Device DriversDevice Drivers
Device Drivers
 
Yocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDK
Yocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDKYocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDK
Yocto Project Dev Day Prague 2017 - Advanced class - Kernel modules with eSDK
 
Drupal module development
Drupal module developmentDrupal module development
Drupal module development
 
As7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yongAs7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yong
 

Recently uploaded

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 

Kernel module programming

  • 1. Introduction to kernel modules • Objectives • Understanding Kernel modules • Writing a simple kernel module • Compiling the kernel module • Loading and unloading of modules • Kernel log • Module dependencies • Modules vs Programs
  • 2. Kernel modules • • • • • • Linux kernel has the ability to extend at runtime the set of features offered by the kernel. This means that you can add functionality to the kernel while the system is up and running. Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. For example, one type of module is the device driver, which allows the kernel to access hardware connected to the system. Without modules, we would have to build monolithic kernels and add new functionality directly into the kernel image. Besides having larger kernels, this has the disadvantage of requiring us to rebuild and reboot the kernel every time we want new functionality.
  • 3. Module utilities • • • • • modinfo <module_name> • Gets information about the module: parameters, license, descriptions and dependencies insmod <module_name>.ko • Load the given module. Full path of module is needed rmmod <module_name> • Unloads the given module lsmod <module_name> • Displays the list of modules loaded. • Check /proc/modules file modprobe • Loads the kernel modules plus any module dependencies
  • 4. Write simple module #include <linux/module.h> #include <linux/kernel.h> static int __init hello_init(void) { printk(“Hello :This is my first kernel modulen"); return 0; } static void __exit hello_exit(void) { printk(“Bye, unloading the modulen"); } module_init(hello_init); module_exit(hello_exit); MODULE_DESCRIPTION(“Sample module"); MODULE_AUTHOR(Vandana Salve"); MODULE_LICENSE("GPL");
  • 5. Module explanation • • Headers specific to the linux kernel <linux/xxx.h> • No access to the usual C library An initialization function • Called when the module is loaded using insmod/modprobe tool • Perform all the initialization functionality • Returns an error code • 0- success • negative value on failure, errors defined in header file • Declared by the module_init() macro
  • 6. Module explanation • A cleanup function • Called when the module is unloaded using rmmod tool • Perform all the cleanup functionality • Declared by the module_exit() macro. • Metadata information – MODULE_DESCRIPTION • Add description about the kernel module – MODULE_AUTHOR • Add the information about the author of the module – MODULE LICENSE • Add license for example GPL
  • 7. Compiling a module • • • Kernel modules need to be compiled a bit differently from regular user space apps. To learn more on how to compile modules which are not part of the official kernel, see file linux/Documentation/kbuild/modules.txt. Option1: Inside the kernel tree – Well integrated into the kernel configuration/compilation process. – Driver can be build statistically if needed
  • 8. Contd… • Option 2: Out of tree – When the code is outside of the kernel source tree, in a different directory. – Advantage • Easier to handle than modifications to the kernel itself. – Disadvantage • Not integrated to the kernel configuration/compilation process, needs to be build separately • driver cannot be built statistically if needed.
  • 9. Compiling an out-of-tree module • When the kernel module code is outside of the kernel source tree, i.e. in a different directory. Module source / path/to/module/ source Hello.c Hello.ko Makefile Kernel sources / path/to/kernel /sources Drivers Kernel Header files Makefiles
  • 10. Makefile for basic kernel module • KDIR := /path/to/kernel/sources obj-m := hello.o all: make -C $(KDIR) M=$(PWD) modules clean: make –C $(KDIR) M=$(PWD) clean • Refer Documentation/kbuild/modules.txt for details
  • 11. Overview of make & makefiles • • • • • • The “make” program automates the building of software based on specification of dependencies among the files. “make” determines which pieces of a large program need to be recompiled and issue commands to recompile them. To use make, you must write a file called makefile. A makefile is simple a way of associating short names, called ‘targets’, with a series of commands to execute when the action is requested. $make clean – Target clean, performs actions that clean up after the compilation— removing object files and resulting executable. $make [all] – Target all, performs action that compile the filesv
  • 12. Kernel log • When a new module is loaded, related information is available in the kernel log. – The kernel keeps its messages in a circular buffer. – Kernel log messages are available through the ‘dmesg’ command – Kernel log messages can be seen in /var/log/messages and/or /var/log/syslog file
  • 13. Module dependencies • • • • • Some kernel module can depend on other modules, which need to be loaded first. Dependencies are described in /lib/modules/<kernel-version>/modules.dep This file is generated when you run make modules_install sudo modprobe <module_name> – Loads all the modules the given module depends on. Modprobe looks into /lib/modules/<kernel-version> for the object file corresponding to the given module Sudo modprobe –r <module_name> – Remove the module and all dependent modules, which are no longer needed.
  • 14. Applications Vs. Kernel modules Application • Performs single task from beginning to end • Application can call functions, which it doesn’t define. The linking stage resolves the external references loading the appropriate libraries. E.g libc for ‘printf’ function. Kernel module • Module registers itself to serve the future request and its ‘main’ function terminates on loading. • The module is linked only to the kernel and it can only the functions that are exported by the kernel. • No C library is linked with the kernel.
  • 15. Functions available to modules • • • • In the hello world example, you might have noticed that we used a function, printk() but didn't include a standard I/O library. That's because modules are object files whose symbols get resolved upon insmod'ing. The definition for the symbols comes from the kernel itself; the only external functions you can use are the ones provided by the kernel. If you're curious about what symbols have been exported by your kernel, take a look at /proc/kallsyms.
  • 16. Passing command line arguments • • • Modules can take command line arguments, but not with the argc/argv you might be used to. To allow arguments to be passed to your module, declare the variables that will take the values of the command line arguments as global and then use the module_param() macro, to set the mechanism up. At runtime, insmod will fill the variables with any command line arguments that are given
  • 17. Contd… • • • • $insmod hello_2.ko int_param=50 The variable declarations and macros should be placed at the beginning of the module for clarity. The module_param() macro takes 3 arguments: – the name of the variable, – its type and permissions for the corresponding file in sysfs. – Integer types can be signed as usual or unsigned. If you'd like to use arrays of integers or strings see – module_param_array() and – module_param_string().
  • 18. Advantages of modules • Modules make it easy to develop drivers without rebooting: load, test, unload, rebuild & again load and so on. • Useful to keep the kernel size to the minimum (essential in embedded systems). Without modules , would need to build monolithic kernel and add new functionality directly into the kernel image. • Also useful to reduce boot time, you don’t need to spend time initializing device that may not be needed at boot time. • Once loaded, modules have full control and privileges in the system. That’s why only the root user can load and unload the modules.
  • 19. Usage of modules • • • • • • Character device drivers Block device drivers Network device drivers File systems Any type of device drivers handling the different types of devices such as USB, I2C etc. etc. Kernel modules can be used to implement any functionality needed runtime on demand