Linux Kernel Programming
Linux Kernel Programming
Linux Kernel Programming
programming
Vandana Salve,
LSI, Pune
Contents
Hardware
Boot Loader
Linux Kernel
Linux kernel modules
Root file systems
User-mode programs
Boot Loader
X86 Example
GRUB – Grand Unified boot loader
Configuration file /boot/grub/grub.conf
Lsmod
Display list of currently loaded modules
/proc/modules
Modinfo
Display module information
/sbin/modinfo
Filename,description,author,license etc
Insmod
Insert a module
Rmmod
Remove a module
Modprobe
Loads modules plus any module dependencies
Uses info provided in
/lib/modules/Version/modules.dep
Updated by depmod command
Writing a simple kernel
module
/* hello-1.c - The simplest kernel module. */
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
int init_module(void)
{
printk(KERN_INFO "Hello world 1.\n");
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Goodbye world 1.\n");
}
MODULE_LICENSE(“GPL”);
MODULE_AUTHOR(DRIVER_AUTHOR);//author
MODULE_DESCRIPTION(“HELLO WORLD Module”);//what this module does
Makefile for a basic kernel
module (2.6kernel)
obj-m += hello-1.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
Option 1
Build device drivers into the kernel
Adv : driver available at boot time
Dis-adv: need to load drivers that are rarely
used,increase kernel size
Option 2
Build device driver as a kernel module
Adv : Load and unloaded as needed/not needed
Dis-adv: potential attempts to load “bad” module into
kernel
….continued
File_operations structure
Every character driver needs to define functions
perform by the device
‘File_operations’ structure holds the address of
the modules functions that perform those
operations
File_operations defined in Linux/fs.h
….continued
Registering a device
Adding a driver to your system means registering
it with the kernel
“Register_chrdev” defined in Linux/fs.h
int register_chrdev(unsigned int major, const char
*name, struct file_operations *fops);
Major – major number
Name – name of device, as it appears in /proc/devices
Fops – file operation table
….continued
Unregistering a device
Whenever the module is unloaded, the major number
should be released
int unregister_chrdev(unsigned int major, const char
*name);
Major – major number
Name – name of device
Usage counter functions, defined in linux/module.h
try_module_get(THIS_MODULE);// Increment the use
count
module_put(THIS_MODULE);// Decrement the use count
Writing a simple character
driver
Examples
Useful References for kernel
programming
http://tldp.org/LDP/lkmpg/2.6/html/index.html
Kernel module programming,
http://lwn.net/Kernel/LDD3/
Device drivers programming