SlideShare a Scribd company logo
1 of 19
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

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 driversHoucheng Lin
 
Introduction to char device driver
Introduction to char device driverIntroduction to char device driver
Introduction to char device driverVandana Salve
 
Linux Internals - Kernel/Core
Linux Internals - Kernel/CoreLinux Internals - Kernel/Core
Linux Internals - Kernel/CoreShay Cohen
 
Root file system for embedded systems
Root file system for embedded systemsRoot file system for embedded systems
Root file system for embedded systemsalok pal
 
Introduction to Linux Kernel by Quontra Solutions
Introduction to Linux Kernel by Quontra SolutionsIntroduction to Linux Kernel by Quontra Solutions
Introduction to Linux Kernel by Quontra SolutionsQUONTRASOLUTIONS
 
Introduction Linux Device Drivers
Introduction Linux Device DriversIntroduction Linux Device Drivers
Introduction Linux Device DriversNEEVEE Technologies
 
linux device driver
linux device driverlinux device driver
linux device driverRahul Batra
 
Browsing Linux Kernel Source
Browsing Linux Kernel SourceBrowsing Linux Kernel Source
Browsing Linux Kernel SourceMotaz Saad
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal BootloaderSatpal Parmar
 
U boot porting guide for SoC
U boot porting guide for SoCU boot porting guide for SoC
U boot porting guide for SoCMacpaul Lin
 

What's hot (20)

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
 
Linux Device Tree
Linux Device TreeLinux Device Tree
Linux Device Tree
 
Introduction to char device driver
Introduction to char device driverIntroduction to char device driver
Introduction to char device driver
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
Linux Internals - Kernel/Core
Linux Internals - Kernel/CoreLinux Internals - Kernel/Core
Linux Internals - Kernel/Core
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 
Linux device drivers
Linux device driversLinux device drivers
Linux device drivers
 
Root file system for embedded systems
Root file system for embedded systemsRoot file system for embedded systems
Root file system for embedded systems
 
Introduction to Linux Kernel by Quontra Solutions
Introduction to Linux Kernel by Quontra SolutionsIntroduction to Linux Kernel by Quontra Solutions
Introduction to Linux Kernel by Quontra Solutions
 
Introduction Linux Device Drivers
Introduction Linux Device DriversIntroduction Linux Device Drivers
Introduction Linux Device Drivers
 
Linux kernel
Linux kernelLinux kernel
Linux kernel
 
Board Bringup
Board BringupBoard Bringup
Board Bringup
 
Linux programming - Getting self started
Linux programming - Getting self started Linux programming - Getting self started
Linux programming - Getting self started
 
Bootloaders
BootloadersBootloaders
Bootloaders
 
linux device driver
linux device driverlinux device driver
linux device driver
 
Browsing Linux Kernel Source
Browsing Linux Kernel SourceBrowsing Linux Kernel Source
Browsing Linux Kernel Source
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 
U boot porting guide for SoC
U boot porting guide for SoCU boot porting guide for SoC
U boot porting guide for SoC
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modules
 

Viewers also liked

Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Tushar B Kute
 
Linux Kernel Programming
Linux Kernel ProgrammingLinux Kernel Programming
Linux Kernel ProgrammingNalin Sharma
 
Linux Kernel Module - For NLKB
Linux Kernel Module - For NLKBLinux Kernel Module - For NLKB
Linux Kernel Module - For NLKBshimosawa
 
Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in LinuxTushar B Kute
 
Module Programming with Project Jigsaw
Module Programming with Project JigsawModule Programming with Project Jigsaw
Module Programming with Project JigsawYuichi 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 computingSatya P. Joshi
 
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-SepAruj 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 ComunidadeDaniel Neis
 
STelligence Savvius Thai Datasheet
STelligence Savvius Thai DatasheetSTelligence Savvius Thai Datasheet
STelligence Savvius Thai DatasheetAruj Thirawat
 
Caching Data For Performance
Caching Data For PerformanceCaching Data For Performance
Caching Data For PerformanceDave 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 2015Aruj 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 managementVandana Salve
 

Viewers also liked (20)

Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)
 
Linux Kernel Programming
Linux Kernel ProgrammingLinux Kernel Programming
Linux Kernel Programming
 
Linux Kernel Module - For NLKB
Linux Kernel Module - For NLKBLinux Kernel Module - For NLKB
Linux Kernel Module - For NLKB
 
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
 

Similar to Kernel module programming

Device Drivers and Running Modules
Device Drivers and Running ModulesDevice Drivers and Running Modules
Device Drivers and Running ModulesYourHelper1
 
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 KuteTushar B Kute
 
Linux Kernel Development
Linux Kernel DevelopmentLinux Kernel Development
Linux Kernel DevelopmentPriyank Kapadia
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modulesHao-Ran Liu
 
Linux kernel code
Linux kernel codeLinux kernel code
Linux kernel codeGanesh 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
 
Linux kernel driver tutorial vorlesung
Linux kernel driver tutorial vorlesungLinux kernel driver tutorial vorlesung
Linux kernel driver tutorial vorlesungdns -
 
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.2Anil Sagar
 
lesson03.ppt
lesson03.pptlesson03.ppt
lesson03.pptIraqReshi
 
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 DevelopementMatt Mendonca
 
Java modulesystem
Java modulesystemJava modulesystem
Java modulesystemMarc Kassis
 
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 eSDKMarco Cavallini
 
Drupal module development
Drupal module developmentDrupal module development
Drupal module developmentRachit Gupta
 

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 Development
Linux Kernel DevelopmentLinux Kernel Development
Linux Kernel Development
 
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
 

Recently uploaded

THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 

Recently uploaded (20)

THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.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