Most of this session will focus on Kernel Module Programming. We will briefly talk about the interaction of different layers of operating system from userspace to kernel space. Starting from simple Hello World kernel modules, we will learn the development of more sophisticated modules related to device drivers and interrupt handlers. We will also briefly touch upon the shell scripts and how they can be used to extract system level information. Since, this will be a hands on session, attendees are expected to try the examples on their machines. Basic understanding of operating systems and C programming is expected for the tutorial.
1. Linux Kernel Modules
Let’s solve the puzzle
Dheryta Jaisinghani
Workshop on Computer Systems, Ashoka University
Dec 9, 2018
(Note: Most of the codes in the slides are from references in the end)
3. Basic Operating System Structure
Hardware
Kernel
User Services
User Applications
& Processes
System Call
Interface
● What is an operating system?
○ An operating system is system software
that manages computer hardware and
software resources and provides
common services for computer
programs. [Wikipedia]
● What is Kernel?
○ Core of the operating system
○ Loads at startup and takes care of
everything else -
resources/memory/scheduling and many
more
○ Types: Monolithic, Microkernel, Modular,
Nano, Exo 3
4. What is a Kernel Module?
● Piece of code - Runtime Load/Unload
● Examples - Device Drivers - printer
driver, WLAN driver, vbox driver and
many more
● Actual kernel image is small - Modules
make it big
○ Monolithic kernels would have
been huge
User-level
Programs
System Call Interface
Kernel Services
Device Modules and Drivers
Physical Devices
User space
Kernel space
4
5. Module vs Program
● Program
○ main() - sequentially executes instructions and terminates
● Kernel Modules
○ init_module() or module_init() - Entry function
■ Initial setup to tell kernel about this module
■ Kernel executes it when needed
○ cleanup_module() or module_exit - Exit function
■ Unregister the module
5
9. Prepare the system
● Update the system
○ sudo apt-get update
● Search appropriate headers
○ apt-cache search linux-headers-$(uname -r)
● Download and install correct Linux headers
○ sudo apt-get install linux-headers-$(uname -r)
● Check if installed correctly
○ cd /usr/src/linux-headers-$(uname -r)
○ ls - should show the header files
● Follow steps under Prepare the System for Building LKMs, presented here
(http://derekmolloy.ie/writing-a-linux-kernel-module-part-1-introduction/)
9
10. Hello World Kernel Module
#include <linux/module.h>
#include <linux/kernel.h>
DRIVER_AUTHOR "Dheryta Jaisinghani"
DRIVER_DESC "A Hello World kernel module."
MODULE_LICENSE("GPL");
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
int init_module(void)
{
printk(KERN_INFO "Hello Worldn");
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Goodbye Worldn");
}
10
Header files to make it a kernel module
and log levels
Module Information
Load the module
0 - Success, Else - Failure
Unload the module
12. printk
● Log at kernel
● 8 priority levels (See: include/linux/kern_levels.h)
○ KERN_EMERG 0 system is unusable
○ KERN_ALERT 1 action must be taken immediately
○ KERN_CRIT 2 critical conditions
○ KERN_ERR 3 error conditions
○ KERN_WARNING 4 warning conditions
○ KERN_NOTICE 5 normal but significant condition
○ KERN_INFO 6 informational
○ KERN_DEBUG 7 debug-level messages
12
13. Module Makefile
obj−m += hello.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
13
Multiple modules can be built with single makefile. Refer to
Section 2.2 in The Linux Kernel Module Programming Guide
17. Not Using Default init and cleanup
#include <linux/module.h>
#include <linux/kernel.h>
DRIVER_AUTHOR "Dheryta Jaisinghani"
DRIVER_DESC "A Hello World kernel module."
MODULE_LICENSE("GPL");
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
static int __init myInit(void)
{
printk(KERN_INFO "Hello Worldn");
/*
* A non 0 return means init_module failed; module can't be loaded.
*/
return 0;
}
static void __exit myExit(void)
{
printk(KERN_INFO "Goodbye Worldn");
}
module_init(myInit);
module_exit(myExit);
17
● __init and __exit are Macros
● Kernel can free memory
when initialization or module
unloading is done
24. Device Drivers vs Device Files
● Everything is a file or a directory
● Every device is represented by a file in /dev/
● Device Driver: Kernel Module that controls a device
● Device File:
○ Interface for the Device Driver to read from or
write to a physical device
○ Also known as Device Nodes
○ Created with mknod system call [ex. mknod
<c/b> <major> <minor>]
Device File
(/dev/xxx)
Device Driver
Physical Device
User space
Kernel space
24
26. Types of Device Files
● Character Files
○ Stream of data one character at a time
○ No restriction on number of bytes
● Block Files
○ Random access to block of data
○ Can buffer and schedule the requests
$ ls -a /dev/
$crw-rw---- 1 root dialout 4, 64 Nov 30 09:51 ttyS0
$brw-rw---- 1 root dialout 4, 64 Nov 30 09:52 sdd
26
27. Major and Minor Device Number
root@iiitd-HP-Compaq-8200-Elite-MT-PC:/home/iiitd# ls -l /dev/sda*
brw-rw---- 1 root disk 8, 0 Dec 3 11:48 /dev/sda
brw-rw---- 1 root disk 8, 1 Dec 3 11:48 /dev/sda1
brw-rw---- 1 root disk 8, 2 Dec 3 11:48 /dev/sda2
brw-rw---- 1 root disk 8, 3 Dec 3 11:48 /dev/sda3
● Major Number
○ The driver for the hardware
○ Unique for each driver
● Minor Number
○ The number of unique hardware a driver manages
27
31. Getting Runtime Information of System
● proc file system
○ Reports runtime information about various resources
○ Memory usage/hardware/modules loaded and many more
● Try
○ ls /proc/ (Numbered directories correspond to processes!)
○ cat /proc/devices
○ cat /proc/modules
○ cat /proc/cpuinfo
○ cat /proc/meminfo
● More Details: http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html
31
35. Interacting with External Devices
● printk does not always help
● Device specific commands should be known
● Interfacing with Keyboard
○ Periodic Lighting Keyboard - Example 10.2 from Ref[1]
○ Dancing Lights Keyboard - Modify Example 10.2 (see help on next slide)
35
37. Interrupt Handlers
37
Processor Hardware
Instructions
How? → Interrupts
Received an interrupt
Pause current work.
Save the state (How?)
Address the interrupt
with Interrupt Handler
Resume the work
request_irq() → Create entry in /proc/interrupts
request_irq() → Create entry in /proc/interrupts
39. Raise and Capture Interrupt on a
Character Device
● chardev.c
● Raise the interrupt whenever file is read [asm instruction]
● Capture the interrupt
● Tell user that the interrupt is captured
39
41. Interacting with Physical Devices
Kernel Modules
41
/proc/ file system
/dev/ file system
Device read/write
IOCTLs
System Calls
Interrupt Handlers
Use Existing or Write Your Own Custom Calls
43. What and Why of Shell Scripts
● Shell is an interface to allow the use of operating system services
● All commands are executed in a shell through a terminal
● Bash shell is the most common shell
● Shell scripts allow to
○ Automate the execution of repetitive shell commands
○ Routine procedures such as backups
○ System monitoring
43
44. Shell Script Structure
● Every shell script starts with a shell name like → # !/bin/bash
● As per convention, a shell script file extension is .sh
● A shell script should be made executable with chmod command
● A shell script can have constructs such as for, while, if-elseif-else, switch
● A shell script can read/write from files
● A shell script can call another program may it be a python or C or any other
● In summary - shell scripts are very powerful
44
46. Control CD Drive
#!/bin/bash
while :
do
eject
eject -t
done
Ref:https://www.quora.com/What-is-the-most-interesting-shell-script-you-have-ever-written
46
47. GRE Prep
1. sudo apt-get install cowsay
2. Prepare a dictionary
a. Apple == red fruit
b. LadyFinger == green vegetable
c. Clock == A device to show time
d. English == It is a language
3. In .bashrc → shuf -n 1 MyDictionary.txt | cowsay
Ref:https://www.quora.com/What-is-the-most-interesting-shell-script-you-have-ever-
written 47
48. System Health
● Use standard commands to summarize all vitals
48
Ref: https://www.tecmint.com/linux-server-health-monitoring-script/
49. Conclusion
● Kernel Modules: An introduction
● Hello world modules: Creating, Compiling, Inserting, Initialization and Passing
variables
● Proc, Device file system
● Device drivers, files
● Interaction with devices
● Interrupt handling
● Shell Scripts
49
50. Linux WiFi Subsytem
● Tutorial: Opening Nuts and Bolts of Linux WiFi Subsytem
● Slides:
https://www.slideshare.net/DherytaJaisinghani/tutorial-wifi-driver-code-opening
-nuts-and-bolts-of-linux-wifi-subsystem
● Video: https://www.youtube.com/watch?v=pa1oEyc7Dm0
50