From aed96129bf18a3c17502b281d124caf61908ed80 Mon Sep 17 00:00:00 2001
From: jserv If you want more information, you can read this web page:
0.16 Crypto
0.16.1 Hash functions
0.16.2 Symmetric key encryption
-
0.17 Standardising the interfaces: The Device Model
+
0.17 Standardizing the interfaces: The Device Model
0.18 Optimizations
0.18.1 Likely and Unlikely conditions
0.19 Common Pitfalls
@@ -2006,144 +2006,119 @@ still use the same way as in the previous example.
1/*
2 * procfs4.c - create a "file" in /proc
3 * This program uses the seq_file library to manage the /proc file.
-4 *
-5 */
-6
-7#include <linux/kernel.h> /* We're doing kernel work */
-8#include <linux/module.h> /* Specifically, a module */
-9#include <linux/proc_fs.h> /* Necessary because we use proc fs */
-10#include <linux/seq_file.h> /* for seq_file */
-11#include <linux/version.h>
-12
-13#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)
-14#define HAVE_PROC_OPS
-15#endif
-16
-17#define PROC_NAME "iter"
-18
-19MODULE_LICENSE("GPL");
-20
-21/**
-22 * This function is called at the beginning of a sequence.
-23 * ie, when:
-24 * - the /proc file is read (first time)
-25 * - after the function stop (end of sequence)
-26 *
-27 */
-28static void *my_seq_start(struct seq_file *s, loff_t *pos)
-29{
-30 static unsigned long counter = 0;
-31
-32 /* beginning a new sequence ? */
-33 if (*pos == 0) {
-34 /* yes => return a non null value to begin the sequence */
-35 return &counter;
-36 } else {
-37 /* no => it's the end of the sequence, return end to stop reading */
-38 *pos = 0;
-39 return NULL;
-40 }
-41}
-42
-43/**
-44 * This function is called after the beginning of a sequence.
-45 * It's called untill the return is NULL (this ends the sequence).
-46 *
-47 */
-48static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos)
-49{
-50 unsigned long *tmp_v = (unsigned long *) v;
-51 (*tmp_v)++;
-52 (*pos)++;
-53 return NULL;
+4 */
+5
+6#include <linux/kernel.h> /* We are doing kernel work */
+7#include <linux/module.h> /* Specifically, a module */
+8#include <linux/proc_fs.h> /* Necessary because we use proc fs */
+9#include <linux/seq_file.h> /* for seq_file */
+10#include <linux/version.h>
+11
+12#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)
+13#define HAVE_PROC_OPS
+14#endif
+15
+16#define PROC_NAME "iter"
+17
+18MODULE_LICENSE("GPL");
+19
+20/* This function is called at the beginning of a sequence.
+21 * ie, when:
+22 * - the /proc file is read (first time)
+23 * - after the function stop (end of sequence)
+24 */
+25static void *my_seq_start(struct seq_file *s, loff_t *pos)
+26{
+27 static unsigned long counter = 0;
+28
+29 /* beginning a new sequence? */
+30 if (*pos == 0) {
+31 /* yes => return a non null value to begin the sequence */
+32 return &counter;
+33 }
+34 /* no => it is the end of the sequence, return end to stop reading */
+35 *pos = 0;
+36 return NULL;
+37}
+38
+39/* This function is called after the beginning of a sequence.
+40 * It is called untill the return is NULL (this ends the sequence).
+41 */
+42static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos)
+43{
+44 unsigned long *tmp_v = (unsigned long *) v;
+45 (*tmp_v)++;
+46 (*pos)++;
+47 return NULL;
+48}
+49
+50/* This function is called at the end of a sequence. */
+51static void my_seq_stop(struct seq_file *s, void *v)
+52{
+53 /* nothing to do, we use a static value in start() */
54}
55
-56/**
-57 * This function is called at the end of a sequence
-58 *
-59 */
-60static void my_seq_stop(struct seq_file *s, void *v)
-61{
-62 /* nothing to do, we use a static value in start() */
+56/* This function is called for each "step" of a sequence. */
+57static int my_seq_show(struct seq_file *s, void *v)
+58{
+59 loff_t *spos = (loff_t *) v;
+60
+61 seq_printf(s, "%Ld\n", *spos);
+62 return 0;
63}
64
-65/**
-66 * This function is called for each "step" of a sequence
-67 *
-68 */
-69static int my_seq_show(struct seq_file *s, void *v)
-70{
-71 loff_t *spos = (loff_t *) v;
+65/* This structure gather "function" to manage the sequence */
+66static struct seq_operations my_seq_ops = {
+67 .start = my_seq_start,
+68 .next = my_seq_next,
+69 .stop = my_seq_stop,
+70 .show = my_seq_show,
+71};
72
-73 seq_printf(s, "%Ld\n", *spos);
-74 return 0;
-75}
-76
-77/**
-78 * This structure gather "function" to manage the sequence
-79 *
-80 */
-81static struct seq_operations my_seq_ops = {.start = my_seq_start,
-82 .next = my_seq_next,
-83 .stop = my_seq_stop,
-84 .show = my_seq_show};
-85
-86/**
-87 * This function is called when the /proc file is open.
-88 *
-89 */
-90static int my_open(struct inode *inode, struct file *file)
-91{
-92 return seq_open(file, &my_seq_ops);
+73/* This function is called when the /proc file is open. */
+74static int my_open(struct inode *inode, struct file *file)
+75{
+76 return seq_open(file, &my_seq_ops);
+77};
+78
+79/* This structure gather "function" that manage the /proc file */
+80#ifdef HAVE_PROC_OPS
+81static const struct proc_ops my_file_ops = {
+82 .proc_open = my_open,
+83 .proc_read = seq_read,
+84 .proc_lseek = seq_lseek,
+85 .proc_release = seq_release,
+86};
+87#else
+88static const struct file_operations my_file_ops = {
+89 .open = my_open,
+90 .read = seq_read,
+91 .llseek = seq_lseek,
+92 .release = seq_release,
93};
-94
-95/**
-96 * This structure gather "function" that manage the /proc file
-97 *
-98 */
-99#ifdef HAVE_PROC_OPS
-100static const struct proc_ops my_file_ops = {
-101 .proc_open = my_open,
-102 .proc_read = seq_read,
-103 .proc_lseek = seq_lseek,
-104 .proc_release = seq_release,
-105};
-106#else
-107static const struct file_operations my_file_ops = {
-108 .open = my_open,
-109 .read = seq_read,
-110 .llseek = seq_lseek,
-111 .release = seq_release,
-112};
-113#endif
-114
-115/**
-116 * This function is called when the module is loaded
-117 *
-118 */
-119int init_module(void)
-120{
-121 struct proc_dir_entry *entry;
-122
-123 entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops);
-124 if (entry == NULL) {
-125 remove_proc_entry(PROC_NAME, NULL);
-126 pr_debug("Error: Could not initialize /proc/%s\n", PROC_NAME);
-127 return -ENOMEM;
-128 }
-129
-130 return 0;
-131}
-132
-133/**
-134 * This function is called when the module is unloaded.
-135 *
-136 */
-137void cleanup_module(void)
-138{
-139 remove_proc_entry(PROC_NAME, NULL);
-140 pr_debug("/proc/%s removed\n", PROC_NAME);
-141}
+94#endif
+95
+96/* This function is called when the module is loaded. */
+97int init_module(void)
+98{
+99 struct proc_dir_entry *entry;
+100
+101 entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops);
+102 if (entry == NULL) {
+103 remove_proc_entry(PROC_NAME, NULL);
+104 pr_debug("Error: Could not initialize /proc/%s\n", PROC_NAME);
+105 return -ENOMEM;
+106 }
+107
+108 return 0;
+109}
+110
+111/* This function is called when the module is unloaded. */
+112void cleanup_module(void)
+113{
+114 remove_proc_entry(PROC_NAME, NULL);
+115 pr_debug("/proc/%s removed\n", PROC_NAME);
+116}
@@ -2164,66 +2139,66 @@ under the sys directory on your system.
accessible via sysfs is given below.
-
1/* -2 * hello-sysfs.c sysfs example -3 */ -4#include <linux/fs.h> -5#include <linux/init.h> -6#include <linux/kobject.h> -7#include <linux/module.h> -8#include <linux/string.h> -9#include <linux/sysfs.h> +1/* +2 * hello-sysfs.c sysfs example +3 */ +4#include <linux/fs.h> +5#include <linux/init.h> +6#include <linux/kobject.h> +7#include <linux/module.h> +8#include <linux/string.h> +9#include <linux/sysfs.h> 10 -11MODULE_LICENSE("GPL"); +11MODULE_LICENSE("GPL"); 12 -13static struct kobject *mymodule; +13static struct kobject *mymodule; 14 -15/* the variable you want to be able to change */ -16static int myvariable = 0; +15/* the variable you want to be able to change */ +16static int myvariable = 0; 17 -18static ssize_t myvariable_show(struct kobject *kobj, -19 struct kobj_attribute *attr, -20 char *buf) +18static ssize_t myvariable_show(struct kobject *kobj, +19 struct kobj_attribute *attr, +20 char *buf) 21{ -22 return sprintf(buf, "%d\n", myvariable); +22 return sprintf(buf, "%d\n", myvariable); 23} 24 -25static ssize_t myvariable_store(struct kobject *kobj, -26 struct kobj_attribute *attr, -27 char *buf, -28 size_t count) +25static ssize_t myvariable_store(struct kobject *kobj, +26 struct kobj_attribute *attr, +27 char *buf, +28 size_t count) 29{ -30 sscanf(buf, "%du", &myvariable); -31 return count; +30 sscanf(buf, "%du", &myvariable); +31 return count; 32} 33 34 -35static struct kobj_attribute myvariable_attribute = -36 __ATTR(myvariable, 0660, myvariable_show, (void *) myvariable_store); +35static struct kobj_attribute myvariable_attribute = +36 __ATTR(myvariable, 0660, myvariable_show, (void *) myvariable_store); 37 -38static int __init mymodule_init(void) +38static int __init mymodule_init(void) 39{ -40 int error = 0; +40 int error = 0; 41 -42 pr_info("mymodule: initialised\n"); +42 pr_info("mymodule: initialised\n"); 43 -44 mymodule = kobject_create_and_add("mymodule", kernel_kobj); -45 if (!mymodule) -46 return -ENOMEM; +44 mymodule = kobject_create_and_add("mymodule", kernel_kobj); +45 if (!mymodule) +46 return -ENOMEM; 47 48 error = sysfs_create_file(mymodule, &myvariable_attribute.attr); -49 if (error) { +49 if (error) { 50 pr_info( -51 "failed to create the myvariable file " -52 "in /sys/kernel/mymodule\n"); +51 "failed to create the myvariable file " +52 "in /sys/kernel/mymodule\n"); 53 } 54 -55 return error; +55 return error; 56} 57 -58static void __exit mymodule_exit(void) +58static void __exit mymodule_exit(void) 59{ -60 pr_info("mymodule: Exit success\n"); +60 pr_info("mymodule: Exit success\n"); 61 kobject_put(mymodule); 62} 63 @@ -2248,7 +2223,7 @@ accessible via sysfs is given below.Set the value of myvariable and check that it changed.
-
1echo "32" > /sys/kernel/mymodule/myvariable +1echo "32" > /sys/kernel/mymodule/myvariable 2cat /sys/kernel/mymodule/myvariableFinally, remove the test module:
@@ -2301,255 +2276,255 @@ get yours, you’ll know something is wrong. For more information, consult the k source tree at Documentation/ioctl-number.txt.
-
1/* -2 * chardev2.c - Create an input/output character device -3 */ +1/* +2 * chardev2.c - Create an input/output character device +3 */ 4 -5#include <linux/cdev.h> -6#include <linux/delay.h> -7#include <linux/device.h> -8#include <linux/fs.h> -9#include <linux/init.h> -10#include <linux/irq.h> -11#include <linux/kernel.h> /* We're doing kernel work */ -12#include <linux/module.h> /* Specifically, a module */ -13#include <linux/poll.h> +5#include <linux/cdev.h> +6#include <linux/delay.h> +7#include <linux/device.h> +8#include <linux/fs.h> +9#include <linux/init.h> +10#include <linux/irq.h> +11#include <linux/kernel.h> /* We're doing kernel work */ +12#include <linux/module.h> /* Specifically, a module */ +13#include <linux/poll.h> 14 -15#include "chardev.h" -16#define SUCCESS 0 -17#define DEVICE_NAME "char_dev" -18#define BUF_LEN 80 +15#include "chardev.h" +16#define SUCCESS 0 +17#define DEVICE_NAME "char_dev" +18#define BUF_LEN 80 19 -20/* -21 * Is the device open right now? Used to prevent -22 * concurent access into the same device -23 */ -24static int Device_Open = 0; +20/* +21 * Is the device open right now? Used to prevent +22 * concurent access into the same device +23 */ +24static int Device_Open = 0; 25 -26/* -27 * The message the device will give when asked -28 */ -29static char Message[BUF_LEN]; +26/* +27 * The message the device will give when asked +28 */ +29static char Message[BUF_LEN]; 30 -31/* -32 * How far did the process reading the message get? -33 * Useful if the message is larger than the size of the -34 * buffer we get to fill in device_read. -35 */ -36static char *Message_Ptr; +31/* +32 * How far did the process reading the message get? +33 * Useful if the message is larger than the size of the +34 * buffer we get to fill in device_read. +35 */ +36static char *Message_Ptr; 37 -38static int Major; /* Major number assigned to our device driver */ -39static struct class *cls; +38static int Major; /* Major number assigned to our device driver */ +39static struct class *cls; 40 -41/* -42 * This is called whenever a process attempts to open the device file -43 */ -44static int device_open(struct inode *inode, struct file *file) +41/* +42 * This is called whenever a process attempts to open the device file +43 */ +44static int device_open(struct inode *inode, struct file *file) 45{ -46 pr_info("device_open(%p)\n", file); +46 pr_info("device_open(%p)\n", file); 47 -48 /* -49 * We don't want to talk to two processes at the same time -50 */ -51 if (Device_Open) -52 return -EBUSY; +48 /* +49 * We don't want to talk to two processes at the same time +50 */ +51 if (Device_Open) +52 return -EBUSY; 53 54 Device_Open++; -55 /* -56 * Initialize the message -57 */ +55 /* +56 * Initialize the message +57 */ 58 Message_Ptr = Message; 59 try_module_get(THIS_MODULE); -60 return SUCCESS; +60 return SUCCESS; 61} 62 -63static int device_release(struct inode *inode, struct file *file) +63static int device_release(struct inode *inode, struct file *file) 64{ -65 pr_info("device_release(%p,%p)\n", inode, file); +65 pr_info("device_release(%p,%p)\n", inode, file); 66 -67 /* -68 * We're now ready for our next caller -69 */ +67 /* +68 * We're now ready for our next caller +69 */ 70 Device_Open--; 71 72 module_put(THIS_MODULE); -73 return SUCCESS; +73 return SUCCESS; 74} 75 -76/* -77 * This function is called whenever a process which has already opened the -78 * device file attempts to read from it. -79 */ -80static ssize_t device_read(struct file *file, /* see include/linux/fs.h */ -81 char __user *buffer, /* buffer to be -82 * filled with data */ -83 size_t length, /* length of the buffer */ +76/* +77 * This function is called whenever a process which has already opened the +78 * device file attempts to read from it. +79 */ +80static ssize_t device_read(struct file *file, /* see include/linux/fs.h */ +81 char __user *buffer, /* buffer to be +82 * filled with data */ +83 size_t length, /* length of the buffer */ 84 loff_t *offset) 85{ -86 /* -87 * Number of bytes actually written to the buffer -88 */ -89 int bytes_read = 0; +86 /* +87 * Number of bytes actually written to the buffer +88 */ +89 int bytes_read = 0; 90 -91 pr_info("device_read(%p,%p,%ld)\n", file, buffer, length); +91 pr_info("device_read(%p,%p,%ld)\n", file, buffer, length); 92 -93 /* -94 * If we're at the end of the message, return 0 -95 * (which signifies end of file) -96 */ -97 if (*Message_Ptr == 0) -98 return 0; +93 /* +94 * If we're at the end of the message, return 0 +95 * (which signifies end of file) +96 */ +97 if (*Message_Ptr == 0) +98 return 0; 99 -100 /* -101 * Actually put the data into the buffer -102 */ -103 while (length && *Message_Ptr) { -104 /* -105 * Because the buffer is in the user data segment, -106 * not the kernel data segment, assignment wouldn't -107 * work. Instead, we have to use put_user which -108 * copies data from the kernel data segment to the -109 * user data segment. -110 */ +100 /* +101 * Actually put the data into the buffer +102 */ +103 while (length && *Message_Ptr) { +104 /* +105 * Because the buffer is in the user data segment, +106 * not the kernel data segment, assignment wouldn't +107 * work. Instead, we have to use put_user which +108 * copies data from the kernel data segment to the +109 * user data segment. +110 */ 111 put_user(*(Message_Ptr++), buffer++); 112 length--; 113 bytes_read++; 114 } 115 -116 pr_info("Read %d bytes, %ld left\n", bytes_read, length); +116 pr_info("Read %d bytes, %ld left\n", bytes_read, length); 117 -118 /* -119 * Read functions are supposed to return the number -120 * of bytes actually inserted into the buffer -121 */ -122 return bytes_read; +118 /* +119 * Read functions are supposed to return the number +120 * of bytes actually inserted into the buffer +121 */ +122 return bytes_read; 123} 124 -125/* -126 * This function is called when somebody tries to -127 * write into our device file. -128 */ -129static ssize_t device_write(struct file *file, -130 const char __user *buffer, -131 size_t length, +125/* +126 * This function is called when somebody tries to +127 * write into our device file. +128 */ +129static ssize_t device_write(struct file *file, +130 const char __user *buffer, +131 size_t length, 132 loff_t *offset) 133{ -134 int i; +134 int i; 135 -136 pr_info("device_write(%p,%s,%ld)", file, buffer, length); +136 pr_info("device_write(%p,%s,%ld)", file, buffer, length); 137 -138 for (i = 0; i < length && i < BUF_LEN; i++) +138 for (i = 0; i < length && i < BUF_LEN; i++) 139 get_user(Message[i], buffer + i); 140 141 Message_Ptr = Message; 142 -143 /* -144 * Again, return the number of input characters used -145 */ -146 return i; +143 /* +144 * Again, return the number of input characters used +145 */ +146 return i; 147} 148 -149/* -150 * This function is called whenever a process tries to do an ioctl on our -151 * device file. We get two extra parameters (additional to the inode and file -152 * structures, which all device functions get): the number of the ioctl called -153 * and the parameter given to the ioctl function. -154 * -155 * If the ioctl is write or read/write (meaning output is returned to the -156 * calling process), the ioctl call returns the output of this function. -157 * -158 */ -159long device_ioctl(struct file *file, /* ditto */ -160 unsigned int ioctl_num, /* number and param for ioctl */ -161 unsigned long ioctl_param) +149/* +150 * This function is called whenever a process tries to do an ioctl on our +151 * device file. We get two extra parameters (additional to the inode and file +152 * structures, which all device functions get): the number of the ioctl called +153 * and the parameter given to the ioctl function. +154 * +155 * If the ioctl is write or read/write (meaning output is returned to the +156 * calling process), the ioctl call returns the output of this function. +157 * +158 */ +159long device_ioctl(struct file *file, /* ditto */ +160 unsigned int ioctl_num, /* number and param for ioctl */ +161 unsigned long ioctl_param) 162{ -163 int i; -164 char *temp; -165 char ch; +163 int i; +164 char *temp; +165 char ch; 166 -167 /* -168 * Switch according to the ioctl called -169 */ -170 switch (ioctl_num) { -171 case IOCTL_SET_MSG: -172 /* -173 * Receive a pointer to a message (in user space) and set that -174 * to be the device's message. Get the parameter given to -175 * ioctl by the process. -176 */ -177 temp = (char *) ioctl_param; +167 /* +168 * Switch according to the ioctl called +169 */ +170 switch (ioctl_num) { +171 case IOCTL_SET_MSG: +172 /* +173 * Receive a pointer to a message (in user space) and set that +174 * to be the device's message. Get the parameter given to +175 * ioctl by the process. +176 */ +177 temp = (char *) ioctl_param; 178 -179 /* -180 * Find the length of the message -181 */ +179 /* +180 * Find the length of the message +181 */ 182 get_user(ch, temp); -183 for (i = 0; ch && i < BUF_LEN; i++, temp++) +183 for (i = 0; ch && i < BUF_LEN; i++, temp++) 184 get_user(ch, temp); 185 -186 device_write(file, (char *) ioctl_param, i, 0); -187 break; +186 device_write(file, (char *) ioctl_param, i, 0); +187 break; 188 -189 case IOCTL_GET_MSG: -190 /* -191 * Give the current message to the calling process - -192 * the parameter we got is a pointer, fill it. -193 */ -194 i = device_read(file, (char *) ioctl_param, 99, 0); +189 case IOCTL_GET_MSG: +190 /* +191 * Give the current message to the calling process - +192 * the parameter we got is a pointer, fill it. +193 */ +194 i = device_read(file, (char *) ioctl_param, 99, 0); 195 -196 /* -197 * Put a zero at the end of the buffer, so it will be -198 * properly terminated -199 */ -200 put_user('\0', (char *) ioctl_param + i); -201 break; +196 /* +197 * Put a zero at the end of the buffer, so it will be +198 * properly terminated +199 */ +200 put_user('\0', (char *) ioctl_param + i); +201 break; 202 -203 case IOCTL_GET_NTH_BYTE: -204 /* -205 * This ioctl is both input (ioctl_param) and -206 * output (the return value of this function) -207 */ -208 return Message[ioctl_param]; -209 break; +203 case IOCTL_GET_NTH_BYTE: +204 /* +205 * This ioctl is both input (ioctl_param) and +206 * output (the return value of this function) +207 */ +208 return Message[ioctl_param]; +209 break; 210 } 211 -212 return SUCCESS; +212 return SUCCESS; 213} 214 -215/* Module Declarations */ +215/* Module Declarations */ 216 -217/* -218 * This structure will hold the functions to be called -219 * when a process does something to the device we -220 * created. Since a pointer to this structure is kept in -221 * the devices table, it can't be local to -222 * init_module. NULL is for unimplemented functions. -223 */ -224struct file_operations Fops = { +217/* +218 * This structure will hold the functions to be called +219 * when a process does something to the device we +220 * created. Since a pointer to this structure is kept in +221 * the devices table, it can't be local to +222 * init_module. NULL is for unimplemented functions. +223 */ +224struct file_operations Fops = { 225 .read = device_read, 226 .write = device_write, 227 .unlocked_ioctl = device_ioctl, 228 .open = device_open, -229 .release = device_release, /* a.k.a. close */ +229 .release = device_release, /* a.k.a. close */ 230}; 231 -232/* -233 * Initialize the module - Register the character device -234 */ -235int init_module() +232/* +233 * Initialize the module - Register the character device +234 */ +235int init_module() 236{ -237 int ret_val; -238 /* -239 * Register the character device (atleast try) -240 */ +237 int ret_val; +238 /* +239 * Register the character device (atleast try) +240 */ 241 ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &Fops); 242 -243 /* -244 * Negative values signify an error -245 */ -246 if (ret_val < 0) { -247 pr_alert("%s failed with %d\n", -248 "Sorry, registering the character device ", ret_val); -249 return ret_val; +243 /* +244 * Negative values signify an error +245 */ +246 if (ret_val < 0) { +247 pr_alert("%s failed with %d\n", +248 "Sorry, registering the character device ", ret_val); +249 return ret_val; 250 } 251 252 Major = ret_val; @@ -2557,262 +2532,262 @@ source tree at Documentation/ioctl-number.txt. 254 cls = class_create(THIS_MODULE, DEVICE_FILE_NAME); 255 device_create(cls, NULL, MKDEV(Major, MAJOR_NUM), NULL, DEVICE_FILE_NAME); 256 -257 pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME); +257 pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME); 258 -259 return 0; +259 return 0; 260} 261 -262/* -263 * Cleanup - unregister the appropriate file from /proc -264 */ -265void cleanup_module() +262/* +263 * Cleanup - unregister the appropriate file from /proc +264 */ +265void cleanup_module() 266{ 267 device_destroy(cls, MKDEV(Major, 0)); 268 class_destroy(cls); 269 -270 /* -271 * Unregister the device -272 */ +270 /* +271 * Unregister the device +272 */ 273 unregister_chrdev(Major, DEVICE_NAME); 274} 275 -276MODULE_LICENSE("GPL");+276MODULE_LICENSE("GPL");-
1/* -2 * chardev.h - the header file with the ioctl definitions. -3 * -4 * The declarations here have to be in a header file, because -5 * they need to be known both to the kernel module -6 * (in chardev.c) and the process calling ioctl (ioctl.c) -7 */ +1/* +2 * chardev.h - the header file with the ioctl definitions. +3 * +4 * The declarations here have to be in a header file, because +5 * they need to be known both to the kernel module +6 * (in chardev.c) and the process calling ioctl (ioctl.c) +7 */ 8 -9#ifndef CHARDEV_H -10#define CHARDEV_H +9#ifndef CHARDEV_H +10#define CHARDEV_H 11 -12#include <linux/ioctl.h> +12#include <linux/ioctl.h> 13 -14/* -15 * The major device number. We can't rely on dynamic -16 * registration any more, because ioctls need to know -17 * it. -18 */ -19#define MAJOR_NUM 100 +14/* +15 * The major device number. We can't rely on dynamic +16 * registration any more, because ioctls need to know +17 * it. +18 */ +19#define MAJOR_NUM 100 20 -21/* -22 * Set the message of the device driver -23 */ -24#define IOCTL_SET_MSG _IOW(MAJOR_NUM, 0, char *) -25/* -26 * _IOW means that we're creating an ioctl command -27 * number for passing information from a user process -28 * to the kernel module. -29 * -30 * The first arguments, MAJOR_NUM, is the major device -31 * number we're using. -32 * -33 * The second argument is the number of the command -34 * (there could be several with different meanings). -35 * -36 * The third argument is the type we want to get from -37 * the process to the kernel. -38 */ +21/* +22 * Set the message of the device driver +23 */ +24#define IOCTL_SET_MSG _IOW(MAJOR_NUM, 0, char *) +25/* +26 * _IOW means that we're creating an ioctl command +27 * number for passing information from a user process +28 * to the kernel module. +29 * +30 * The first arguments, MAJOR_NUM, is the major device +31 * number we're using. +32 * +33 * The second argument is the number of the command +34 * (there could be several with different meanings). +35 * +36 * The third argument is the type we want to get from +37 * the process to the kernel. +38 */ 39 -40/* -41 * Get the message of the device driver -42 */ -43#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *) -44/* -45 * This IOCTL is used for output, to get the message -46 * of the device driver. However, we still need the -47 * buffer to place the message in to be input, -48 * as it is allocated by the process. -49 */ +40/* +41 * Get the message of the device driver +42 */ +43#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *) +44/* +45 * This IOCTL is used for output, to get the message +46 * of the device driver. However, we still need the +47 * buffer to place the message in to be input, +48 * as it is allocated by the process. +49 */ 50 -51/* -52 * Get the n'th byte of the message -53 */ -54#define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int) -55/* -56 * The IOCTL is used for both input and output. It -57 * receives from the user a number, n, and returns -58 * Message[n]. -59 */ +51/* +52 * Get the n'th byte of the message +53 */ +54#define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int) +55/* +56 * The IOCTL is used for both input and output. It +57 * receives from the user a number, n, and returns +58 * Message[n]. +59 */ 60 -61/* -62 * The name of the device file -63 */ -64#define DEVICE_FILE_NAME "char_dev" +61/* +62 * The name of the device file +63 */ +64#define DEVICE_FILE_NAME "char_dev" 65 -66#endif+66#endif-
1/* -2 * ioctl.c -3 */ -4#include <linux/cdev.h> -5#include <linux/fs.h> -6#include <linux/init.h> -7#include <linux/ioctl.h> -8#include <linux/module.h> -9#include <linux/slab.h> -10#include <linux/uaccess.h> +1/* +2 * ioctl.c +3 */ +4#include <linux/cdev.h> +5#include <linux/fs.h> +6#include <linux/init.h> +7#include <linux/ioctl.h> +8#include <linux/module.h> +9#include <linux/slab.h> +10#include <linux/uaccess.h> 11 -12struct ioctl_arg { -13 unsigned int reg; -14 unsigned int val; +12struct ioctl_arg { +13 unsigned int reg; +14 unsigned int val; 15}; 16 -17/* Documentation/ioctl/ioctl-number.txt */ -18#define IOC_MAGIC '\x66' +17/* Documentation/ioctl/ioctl-number.txt */ +18#define IOC_MAGIC '\x66' 19 -20#define IOCTL_VALSET _IOW(IOC_MAGIC, 0, struct ioctl_arg) -21#define IOCTL_VALGET _IOR(IOC_MAGIC, 1, struct ioctl_arg) -22#define IOCTL_VALGET_NUM _IOR(IOC_MAGIC, 2, int) -23#define IOCTL_VALSET_NUM _IOW(IOC_MAGIC, 3, int) +20#define IOCTL_VALSET _IOW(IOC_MAGIC, 0, struct ioctl_arg) +21#define IOCTL_VALGET _IOR(IOC_MAGIC, 1, struct ioctl_arg) +22#define IOCTL_VALGET_NUM _IOR(IOC_MAGIC, 2, int) +23#define IOCTL_VALSET_NUM _IOW(IOC_MAGIC, 3, int) 24 -25#define IOCTL_VAL_MAXNR 3 -26#define DRIVER_NAME "ioctltest" +25#define IOCTL_VAL_MAXNR 3 +26#define DRIVER_NAME "ioctltest" 27 -28static unsigned int test_ioctl_major = 0; -29static unsigned int num_of_dev = 1; -30static struct cdev test_ioctl_cdev; -31static int ioctl_num = 0; +28static unsigned int test_ioctl_major = 0; +29static unsigned int num_of_dev = 1; +30static struct cdev test_ioctl_cdev; +31static int ioctl_num = 0; 32 -33struct test_ioctl_data { -34 unsigned char val; +33struct test_ioctl_data { +34 unsigned char val; 35 rwlock_t lock; 36}; 37 -38static long test_ioctl_ioctl(struct file *filp, -39 unsigned int cmd, -40 unsigned long arg) +38static long test_ioctl_ioctl(struct file *filp, +39 unsigned int cmd, +40 unsigned long arg) 41{ -42 struct test_ioctl_data *ioctl_data = filp->private_data; -43 int retval = 0; -44 unsigned char val; -45 struct ioctl_arg data; -46 memset(&data, 0, sizeof(data)); +42 struct test_ioctl_data *ioctl_data = filp->private_data; +43 int retval = 0; +44 unsigned char val; +45 struct ioctl_arg data; +46 memset(&data, 0, sizeof(data)); 47 -48 switch (cmd) { -49 case IOCTL_VALSET: +48 switch (cmd) { +49 case IOCTL_VALSET: 50 -51 /* -52 if (!capable(CAP_SYS_ADMIN)) { -53 retval = -EPERM; -54 goto done; -55 } -56 if (!access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd))) { -57 retval = -EFAULT; -58 goto done; -59 } -60 */ -61 if (copy_from_user(&data, (int __user *) arg, sizeof(data))) { +51 /* +52 if (!capable(CAP_SYS_ADMIN)) { +53 retval = -EPERM; +54 goto done; +55 } +56 if (!access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd))) { +57 retval = -EFAULT; +58 goto done; +59 } +60 */ +61 if (copy_from_user(&data, (int __user *) arg, sizeof(data))) { 62 retval = -EFAULT; -63 goto done; +63 goto done; 64 } 65 -66 pr_alert("IOCTL set val:%x .\n", data.val); +66 pr_alert("IOCTL set val:%x .\n", data.val); 67 write_lock(&ioctl_data->lock); 68 ioctl_data->val = data.val; 69 write_unlock(&ioctl_data->lock); -70 break; +70 break; 71 -72 case IOCTL_VALGET: -73 /* -74 if (!access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd))) { -75 retval = -EFAULT; -76 goto done; -77 } -78 */ +72 case IOCTL_VALGET: +73 /* +74 if (!access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd))) { +75 retval = -EFAULT; +76 goto done; +77 } +78 */ 79 read_lock(&ioctl_data->lock); 80 val = ioctl_data->val; 81 read_unlock(&ioctl_data->lock); 82 data.val = val; 83 -84 if (copy_to_user((int __user *) arg, &data, sizeof(data))) { +84 if (copy_to_user((int __user *) arg, &data, sizeof(data))) { 85 retval = -EFAULT; -86 goto done; +86 goto done; 87 } 88 -89 break; +89 break; 90 -91 case IOCTL_VALGET_NUM: -92 retval = __put_user(ioctl_num, (int __user *) arg); -93 break; +91 case IOCTL_VALGET_NUM: +92 retval = __put_user(ioctl_num, (int __user *) arg); +93 break; 94 -95 case IOCTL_VALSET_NUM: -96 /* -97 if (!capable(CAP_SYS_ADMIN)) -98 return -EPERM; -99 */ +95 case IOCTL_VALSET_NUM: +96 /* +97 if (!capable(CAP_SYS_ADMIN)) +98 return -EPERM; +99 */ 100 ioctl_num = arg; -101 break; +101 break; 102 -103 default: +103 default: 104 retval = -ENOTTY; 105 } 106 107done: -108 return retval; +108 return retval; 109} 110 -111ssize_t test_ioctl_read(struct file *filp, -112 char __user *buf, -113 size_t count, +111ssize_t test_ioctl_read(struct file *filp, +112 char __user *buf, +113 size_t count, 114 loff_t *f_pos) 115{ -116 struct test_ioctl_data *ioctl_data = filp->private_data; -117 unsigned char val; -118 int retval; -119 int i = 0; +116 struct test_ioctl_data *ioctl_data = filp->private_data; +117 unsigned char val; +118 int retval; +119 int i = 0; 120 read_lock(&ioctl_data->lock); 121 val = ioctl_data->val; 122 read_unlock(&ioctl_data->lock); 123 -124 for (; i < count; i++) { -125 if (copy_to_user(&buf[i], &val, 1)) { +124 for (; i < count; i++) { +125 if (copy_to_user(&buf[i], &val, 1)) { 126 retval = -EFAULT; -127 goto out; +127 goto out; 128 } 129 } 130 131 retval = count; 132out: -133 return retval; +133 return retval; 134} 135 -136static int test_ioctl_close(struct inode *inode, struct file *filp) +136static int test_ioctl_close(struct inode *inode, struct file *filp) 137{ -138 pr_alert("%s call.\n", __func__); +138 pr_alert("%s call.\n", __func__); 139 -140 if (filp->private_data) { +140 if (filp->private_data) { 141 kfree(filp->private_data); 142 filp->private_data = NULL; 143 } 144 -145 return 0; +145 return 0; 146} 147 -148static int test_ioctl_open(struct inode *inode, struct file *filp) +148static int test_ioctl_open(struct inode *inode, struct file *filp) 149{ -150 struct test_ioctl_data *ioctl_data; -151 pr_alert("%s call.\n", __func__); -152 ioctl_data = kmalloc(sizeof(struct test_ioctl_data), GFP_KERNEL); +150 struct test_ioctl_data *ioctl_data; +151 pr_alert("%s call.\n", __func__); +152 ioctl_data = kmalloc(sizeof(struct test_ioctl_data), GFP_KERNEL); 153 -154 if (ioctl_data == NULL) { -155 return -ENOMEM; +154 if (ioctl_data == NULL) { +155 return -ENOMEM; 156 } 157 158 rwlock_init(&ioctl_data->lock); 159 ioctl_data->val = 0xFF; 160 filp->private_data = ioctl_data; -161 return 0; +161 return 0; 162} 163 -164struct file_operations fops = { +164struct file_operations fops = { 165 .owner = THIS_MODULE, 166 .open = test_ioctl_open, 167 .release = test_ioctl_close, @@ -2820,54 +2795,54 @@ source tree at Documentation/ioctl-number.txt. 169 .unlocked_ioctl = test_ioctl_ioctl, 170}; 171 -172static int ioctl_init(void) +172static int ioctl_init(void) 173{ -174 dev_t dev = MKDEV(test_ioctl_major, 0); -175 int alloc_ret = 0; -176 int cdev_ret = 0; +174 dev_t dev = MKDEV(test_ioctl_major, 0); +175 int alloc_ret = 0; +176 int cdev_ret = 0; 177 alloc_ret = alloc_chrdev_region(&dev, 0, num_of_dev, DRIVER_NAME); 178 -179 if (alloc_ret) { -180 goto error; +179 if (alloc_ret) { +180 goto error; 181 } 182 183 test_ioctl_major = MAJOR(dev); 184 cdev_init(&test_ioctl_cdev, &fops); 185 cdev_ret = cdev_add(&test_ioctl_cdev, dev, num_of_dev); 186 -187 if (cdev_ret) { -188 goto error; +187 if (cdev_ret) { +188 goto error; 189 } 190 -191 pr_alert("%s driver(major: %d) installed.\n", DRIVER_NAME, +191 pr_alert("%s driver(major: %d) installed.\n", DRIVER_NAME, 192 test_ioctl_major); -193 return 0; +193 return 0; 194error: 195 -196 if (cdev_ret == 0) { +196 if (cdev_ret == 0) { 197 cdev_del(&test_ioctl_cdev); 198 } 199 -200 if (alloc_ret == 0) { +200 if (alloc_ret == 0) { 201 unregister_chrdev_region(dev, num_of_dev); 202 } 203 -204 return -1; +204 return -1; 205} 206 -207static void ioctl_exit(void) +207static void ioctl_exit(void) 208{ -209 dev_t dev = MKDEV(test_ioctl_major, 0); +209 dev_t dev = MKDEV(test_ioctl_major, 0); 210 cdev_del(&test_ioctl_cdev); 211 unregister_chrdev_region(dev, num_of_dev); -212 pr_alert("%s driver removed.\n", DRIVER_NAME); +212 pr_alert("%s driver removed.\n", DRIVER_NAME); 213} 214 215module_init(ioctl_init); 216module_exit(ioctl_exit); 217 -218MODULE_LICENSE("GPL"); -219MODULE_DESCRIPTION("This is test_ioctl module");+218MODULE_LICENSE("GPL"); +219MODULE_DESCRIPTION("This is test_ioctl module");
0.10 System Calls
@@ -2970,151 +2945,151 @@ Depending on your kernel version, you might even need to hand apply the patch.-
1/* -2 * syscall.c -3 * -4 * System call "stealing" sample. -5 * -6 * Disables page protection at a processor level by -7 * changing the 16th bit in the cr0 register (could be Intel specific) -8 * -9 * Based on example by Peter Jay Salzman and -10 * https://bbs.archlinux.org/viewtopic.php?id=139406 -11 */ +1/* +2 * syscall.c +3 * +4 * System call "stealing" sample. +5 * +6 * Disables page protection at a processor level by +7 * changing the 16th bit in the cr0 register (could be Intel specific) +8 * +9 * Based on example by Peter Jay Salzman and +10 * https://bbs.archlinux.org/viewtopic.php?id=139406 +11 */ 12 -13#include <linux/delay.h> -14#include <linux/kernel.h> -15#include <linux/module.h> -16#include <linux/moduleparam.h> /* which will have params */ -17#include <linux/syscalls.h> -18#include <linux/unistd.h> /* The list of system calls */ +13#include <linux/delay.h> +14#include <linux/kernel.h> +15#include <linux/module.h> +16#include <linux/moduleparam.h> /* which will have params */ +17#include <linux/syscalls.h> +18#include <linux/unistd.h> /* The list of system calls */ 19 -20/* -21 * For the current (process) structure, we need -22 * this to know who the current user is. -23 */ -24#include <linux/sched.h> -25#include <linux/uaccess.h> +20/* +21 * For the current (process) structure, we need +22 * this to know who the current user is. +23 */ +24#include <linux/sched.h> +25#include <linux/uaccess.h> 26 -27unsigned long **sys_call_table; -28unsigned long original_cr0; +27unsigned long **sys_call_table; +28unsigned long original_cr0; 29 -30/* -31 * UID we want to spy on - will be filled from the -32 * command line -33 */ -34static int uid; -35module_param(uid, int, 0644); +30/* +31 * UID we want to spy on - will be filled from the +32 * command line +33 */ +34static int uid; +35module_param(uid, int, 0644); 36 -37/* -38 * A pointer to the original system call. The reason -39 * we keep this, rather than call the original function -40 * (sys_open), is because somebody else might have -41 * replaced the system call before us. Note that this -42 * is not 100% safe, because if another module -43 * replaced sys_open before us, then when we're inserted -44 * we'll call the function in that module - and it -45 * might be removed before we are. -46 * -47 * Another reason for this is that we can't get sys_open. -48 * It's a static variable, so it is not exported. -49 */ -50asmlinkage int (*original_call)(const char *, int, int); +37/* +38 * A pointer to the original system call. The reason +39 * we keep this, rather than call the original function +40 * (sys_open), is because somebody else might have +41 * replaced the system call before us. Note that this +42 * is not 100% safe, because if another module +43 * replaced sys_open before us, then when we're inserted +44 * we'll call the function in that module - and it +45 * might be removed before we are. +46 * +47 * Another reason for this is that we can't get sys_open. +48 * It's a static variable, so it is not exported. +49 */ +50asmlinkage int (*original_call)(const char *, int, int); 51 -52/* -53 * The function we'll replace sys_open (the function -54 * called when you call the open system call) with. To -55 * find the exact prototype, with the number and type -56 * of arguments, we find the original function first -57 * (it's at fs/open.c). -58 * -59 * In theory, this means that we're tied to the -60 * current version of the kernel. In practice, the -61 * system calls almost never change (it would wreck havoc -62 * and require programs to be recompiled, since the system -63 * calls are the interface between the kernel and the -64 * processes). -65 */ -66asmlinkage int our_sys_open(const char *filename, int flags, int mode) +52/* +53 * The function we'll replace sys_open (the function +54 * called when you call the open system call) with. To +55 * find the exact prototype, with the number and type +56 * of arguments, we find the original function first +57 * (it's at fs/open.c). +58 * +59 * In theory, this means that we're tied to the +60 * current version of the kernel. In practice, the +61 * system calls almost never change (it would wreck havoc +62 * and require programs to be recompiled, since the system +63 * calls are the interface between the kernel and the +64 * processes). +65 */ +66asmlinkage int our_sys_open(const char *filename, int flags, int mode) 67{ -68 int i = 0; -69 char ch; +68 int i = 0; +69 char ch; 70 -71 /* -72 * Report the file, if relevant -73 */ -74 pr_info("Opened file by %d: ", uid); -75 do { +71 /* +72 * Report the file, if relevant +73 */ +74 pr_info("Opened file by %d: ", uid); +75 do { 76 get_user(ch, filename + i); 77 i++; -78 pr_info("%c", ch); -79 } while (ch != 0); -80 pr_info("\n"); +78 pr_info("%c", ch); +79 } while (ch != 0); +80 pr_info("\n"); 81 -82 /* -83 * Call the original sys_open - otherwise, we lose -84 * the ability to open files -85 */ -86 return original_call(filename, flags, mode); +82 /* +83 * Call the original sys_open - otherwise, we lose +84 * the ability to open files +85 */ +86 return original_call(filename, flags, mode); 87} 88 -89static unsigned long **aquire_sys_call_table(void) +89static unsigned long **aquire_sys_call_table(void) 90{ -91 unsigned long int offset = PAGE_OFFSET; -92 unsigned long **sct; +91 unsigned long int offset = PAGE_OFFSET; +92 unsigned long **sct; 93 -94 while (offset < ULLONG_MAX) { -95 sct = (unsigned long **) offset; +94 while (offset < ULLONG_MAX) { +95 sct = (unsigned long **) offset; 96 -97 if (sct[__NR_close] == (unsigned long *) ksys_close) -98 return sct; +97 if (sct[__NR_close] == (unsigned long *) ksys_close) +98 return sct; 99 -100 offset += sizeof(void *); +100 offset += sizeof(void *); 101 } 102 -103 return NULL; +103 return NULL; 104} 105 -106static int __init syscall_start(void) +106static int __init syscall_start(void) 107{ -108 if (!(sys_call_table = aquire_sys_call_table())) -109 return -1; +108 if (!(sys_call_table = aquire_sys_call_table())) +109 return -1; 110 111 original_cr0 = read_cr0(); 112 113 write_cr0(original_cr0 & ~0x00010000); 114 -115 /* keep track of the original open function */ -116 original_call = (void *) sys_call_table[__NR_open]; +115 /* keep track of the original open function */ +116 original_call = (void *) sys_call_table[__NR_open]; 117 -118 /* use our open function instead */ -119 sys_call_table[__NR_open] = (unsigned long *) our_sys_open; +118 /* use our open function instead */ +119 sys_call_table[__NR_open] = (unsigned long *) our_sys_open; 120 121 write_cr0(original_cr0); 122 -123 pr_info("Spying on UID:%d\n", uid); +123 pr_info("Spying on UID:%d\n", uid); 124 -125 return 0; +125 return 0; 126} 127 -128static void __exit syscall_end(void) +128static void __exit syscall_end(void) 129{ -130 if (!sys_call_table) { -131 return; +130 if (!sys_call_table) { +131 return; 132 } 133 -134 /* -135 * Return the system call back to normal -136 */ -137 if (sys_call_table[__NR_open] != (unsigned long *) our_sys_open) { -138 pr_alert("Somebody else also played with the "); -139 pr_alert("open system call\n"); -140 pr_alert("The system may be left in "); -141 pr_alert("an unstable state.\n"); +134 /* +135 * Return the system call back to normal +136 */ +137 if (sys_call_table[__NR_open] != (unsigned long *) our_sys_open) { +138 pr_alert("Somebody else also played with the "); +139 pr_alert("open system call\n"); +140 pr_alert("The system may be left in "); +141 pr_alert("an unstable state.\n"); 142 } 143 144 write_cr0(original_cr0 & ~0x00010000); -145 sys_call_table[__NR_open] = (unsigned long *) original_call; +145 sys_call_table[__NR_open] = (unsigned long *) original_call; 146 write_cr0(original_cr0); 147 148 msleep(2000); @@ -3123,7 +3098,7 @@ patch. 151module_init(syscall_start); 152module_exit(syscall_end); 153 -154MODULE_LICENSE("GPL");+154MODULE_LICENSE("GPL");
0.11 Blocking Processes and threads
@@ -3223,347 +3198,347 @@ $
-
1/* -2 * sleep.c - create a /proc file, and if several processes try to open it at -3 * the same time, put all but one to sleep -4 */ +1/* +2 * sleep.c - create a /proc file, and if several processes try to open it at +3 * the same time, put all but one to sleep +4 */ 5 -6#include <linux/kernel.h> /* We're doing kernel work */ -7#include <linux/module.h> /* Specifically, a module */ -8#include <linux/proc_fs.h> /* Necessary because we use proc fs */ -9#include <linux/sched.h> /* For putting processes to sleep and -10 waking them up */ -11#include <linux/uaccess.h> /* for get_user and put_user */ -12#include <linux/version.h> +6#include <linux/kernel.h> /* We're doing kernel work */ +7#include <linux/module.h> /* Specifically, a module */ +8#include <linux/proc_fs.h> /* Necessary because we use proc fs */ +9#include <linux/sched.h> /* For putting processes to sleep and +10 waking them up */ +11#include <linux/uaccess.h> /* for get_user and put_user */ +12#include <linux/version.h> 13 -14#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) -15#define HAVE_PROC_OPS -16#endif +14#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) +15#define HAVE_PROC_OPS +16#endif 17 -18/* -19 * The module's file functions -20 */ +18/* +19 * The module's file functions +20 */ 21 -22/* -23 * Here we keep the last message received, to prove that we can process our -24 * input -25 */ -26#define MESSAGE_LENGTH 80 -27static char Message[MESSAGE_LENGTH]; +22/* +23 * Here we keep the last message received, to prove that we can process our +24 * input +25 */ +26#define MESSAGE_LENGTH 80 +27static char Message[MESSAGE_LENGTH]; 28 -29static struct proc_dir_entry *Our_Proc_File; -30#define PROC_ENTRY_FILENAME "sleep" +29static struct proc_dir_entry *Our_Proc_File; +30#define PROC_ENTRY_FILENAME "sleep" 31 -32/* -33 * Since we use the file operations struct, we can't use the special proc -34 * output provisions - we have to use a standard read function, which is this -35 * function -36 */ -37static ssize_t module_output(struct file *file, /* see include/linux/fs.h */ -38 char *buf, /* The buffer to put data to -39 (in the user segment) */ -40 size_t len, /* The length of the buffer */ +32/* +33 * Since we use the file operations struct, we can't use the special proc +34 * output provisions - we have to use a standard read function, which is this +35 * function +36 */ +37static ssize_t module_output(struct file *file, /* see include/linux/fs.h */ +38 char *buf, /* The buffer to put data to +39 (in the user segment) */ +40 size_t len, /* The length of the buffer */ 41 loff_t *offset) 42{ -43 static int finished = 0; -44 int i; -45 char message[MESSAGE_LENGTH + 30]; +43 static int finished = 0; +44 int i; +45 char message[MESSAGE_LENGTH + 30]; 46 -47 /* -48 * Return 0 to signify end of file - that we have nothing -49 * more to say at this point. -50 */ -51 if (finished) { +47 /* +48 * Return 0 to signify end of file - that we have nothing +49 * more to say at this point. +50 */ +51 if (finished) { 52 finished = 0; -53 return 0; +53 return 0; 54 } 55 -56 /* -57 * If you don't understand this by now, you're hopeless as a kernel -58 * programmer. -59 */ -60 sprintf(message, "Last input:%s\n", Message); -61 for (i = 0; i < len && message[i]; i++) +56 /* +57 * If you don't understand this by now, you're hopeless as a kernel +58 * programmer. +59 */ +60 sprintf(message, "Last input:%s\n", Message); +61 for (i = 0; i < len && message[i]; i++) 62 put_user(message[i], buf + i); 63 64 finished = 1; -65 return i; /* Return the number of bytes "read" */ +65 return i; /* Return the number of bytes "read" */ 66} 67 -68/* -69 * This function receives input from the user when the user writes to the /proc -70 * file. -71 */ -72static ssize_t module_input(struct file *file, /* The file itself */ -73 const char *buf, /* The buffer with input */ -74 size_t length, /* The buffer's length */ -75 loff_t *offset) /* offset to file - ignore */ +68/* +69 * This function receives input from the user when the user writes to the /proc +70 * file. +71 */ +72static ssize_t module_input(struct file *file, /* The file itself */ +73 const char *buf, /* The buffer with input */ +74 size_t length, /* The buffer's length */ +75 loff_t *offset) /* offset to file - ignore */ 76{ -77 int i; +77 int i; 78 -79 /* -80 * Put the input into Message, where module_output will later be -81 * able to use it -82 */ -83 for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++) +79 /* +80 * Put the input into Message, where module_output will later be +81 * able to use it +82 */ +83 for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++) 84 get_user(Message[i], buf + i); -85 /* -86 * we want a standard, zero terminated string -87 */ -88 Message[i] = '\0'; +85 /* +86 * we want a standard, zero terminated string +87 */ +88 Message[i] = '\0'; 89 -90 /* -91 * We need to return the number of input characters used -92 */ -93 return i; +90 /* +91 * We need to return the number of input characters used +92 */ +93 return i; 94} 95 -96/* -97 * 1 if the file is currently open by somebody -98 */ -99int Already_Open = 0; +96/* +97 * 1 if the file is currently open by somebody +98 */ +99int Already_Open = 0; 100 -101/* -102 * Queue of processes who want our file -103 */ +101/* +102 * Queue of processes who want our file +103 */ 104DECLARE_WAIT_QUEUE_HEAD(WaitQ); -105/* -106 * Called when the /proc file is opened -107 */ -108static int module_open(struct inode *inode, struct file *file) +105/* +106 * Called when the /proc file is opened +107 */ +108static int module_open(struct inode *inode, struct file *file) 109{ -110 /* -111 * If the file's flags include O_NONBLOCK, it means the process doesn't -112 * want to wait for the file. In this case, if the file is already -113 * open, we should fail with -EAGAIN, meaning "you'll have to try -114 * again", instead of blocking a process which would rather stay awake. -115 */ -116 if ((file->f_flags & O_NONBLOCK) && Already_Open) -117 return -EAGAIN; +110 /* +111 * If the file's flags include O_NONBLOCK, it means the process doesn't +112 * want to wait for the file. In this case, if the file is already +113 * open, we should fail with -EAGAIN, meaning "you'll have to try +114 * again", instead of blocking a process which would rather stay awake. +115 */ +116 if ((file->f_flags & O_NONBLOCK) && Already_Open) +117 return -EAGAIN; 118 -119 /* -120 * This is the correct place for try_module_get(THIS_MODULE) because -121 * if a process is in the loop, which is within the kernel module, -122 * the kernel module must not be removed. -123 */ +119 /* +120 * This is the correct place for try_module_get(THIS_MODULE) because +121 * if a process is in the loop, which is within the kernel module, +122 * the kernel module must not be removed. +123 */ 124 try_module_get(THIS_MODULE); 125 -126 /* -127 * If the file is already open, wait until it isn't -128 */ +126 /* +127 * If the file is already open, wait until it isn't +128 */ 129 -130 while (Already_Open) { -131 int i, is_sig = 0; +130 while (Already_Open) { +131 int i, is_sig = 0; 132 -133 /* -134 * This function puts the current process, including any system -135 * calls, such as us, to sleep. Execution will be resumed right -136 * after the function call, either because somebody called -137 * wake_up(&WaitQ) (only module_close does that, when the file -138 * is closed) or when a signal, such as Ctrl-C, is sent -139 * to the process -140 */ +133 /* +134 * This function puts the current process, including any system +135 * calls, such as us, to sleep. Execution will be resumed right +136 * after the function call, either because somebody called +137 * wake_up(&WaitQ) (only module_close does that, when the file +138 * is closed) or when a signal, such as Ctrl-C, is sent +139 * to the process +140 */ 141 wait_event_interruptible(WaitQ, !Already_Open); 142 -143 /* -144 * If we woke up because we got a signal we're not blocking, -145 * return -EINTR (fail the system call). This allows processes -146 * to be killed or stopped. -147 */ +143 /* +144 * If we woke up because we got a signal we're not blocking, +145 * return -EINTR (fail the system call). This allows processes +146 * to be killed or stopped. +147 */ 148 -149 /* -150 * Emmanuel Papirakis: -151 * -152 * This is a little update to work with 2.2.*. Signals now are -153 * contained in two words (64 bits) and are stored in a structure that -154 * contains an array of two unsigned longs. We now have to make 2 -155 * checks in our if. -156 * -157 * Ori Pomerantz: -158 * -159 * Nobody promised me they'll never use more than 64 bits, or that this -160 * book won't be used for a version of Linux with a word size of 16 -161 * bits. This code would work in any case. -162 */ -163 for (i = 0; i < _NSIG_WORDS && !is_sig; i++) +149 /* +150 * Emmanuel Papirakis: +151 * +152 * This is a little update to work with 2.2.*. Signals now are +153 * contained in two words (64 bits) and are stored in a structure that +154 * contains an array of two unsigned longs. We now have to make 2 +155 * checks in our if. +156 * +157 * Ori Pomerantz: +158 * +159 * Nobody promised me they'll never use more than 64 bits, or that this +160 * book won't be used for a version of Linux with a word size of 16 +161 * bits. This code would work in any case. +162 */ +163 for (i = 0; i < _NSIG_WORDS && !is_sig; i++) 164 is_sig = current->pending.signal.sig[i] & ~current->blocked.sig[i]; 165 -166 if (is_sig) { -167 /* -168 * It's important to put module_put(THIS_MODULE) here, -169 * because for processes where the open is interrupted -170 * there will never be a corresponding close. If we -171 * don't decrement the usage count here, we will be -172 * left with a positive usage count which we'll have no -173 * way to bring down to zero, giving us an immortal -174 * module, which can only be killed by rebooting -175 * the machine. -176 */ +166 if (is_sig) { +167 /* +168 * It's important to put module_put(THIS_MODULE) here, +169 * because for processes where the open is interrupted +170 * there will never be a corresponding close. If we +171 * don't decrement the usage count here, we will be +172 * left with a positive usage count which we'll have no +173 * way to bring down to zero, giving us an immortal +174 * module, which can only be killed by rebooting +175 * the machine. +176 */ 177 module_put(THIS_MODULE); -178 return -EINTR; +178 return -EINTR; 179 } 180 } 181 -182 /* -183 * If we got here, Already_Open must be zero -184 */ +182 /* +183 * If we got here, Already_Open must be zero +184 */ 185 -186 /* -187 * Open the file -188 */ +186 /* +187 * Open the file +188 */ 189 Already_Open = 1; -190 return 0; /* Allow the access */ +190 return 0; /* Allow the access */ 191} 192 -193/* -194 * Called when the /proc file is closed -195 */ -196int module_close(struct inode *inode, struct file *file) +193/* +194 * Called when the /proc file is closed +195 */ +196int module_close(struct inode *inode, struct file *file) 197{ -198 /* -199 * Set Already_Open to zero, so one of the processes in the WaitQ will -200 * be able to set Already_Open back to one and to open the file. All -201 * the other processes will be called when Already_Open is back to one, -202 * so they'll go back to sleep. -203 */ +198 /* +199 * Set Already_Open to zero, so one of the processes in the WaitQ will +200 * be able to set Already_Open back to one and to open the file. All +201 * the other processes will be called when Already_Open is back to one, +202 * so they'll go back to sleep. +203 */ 204 Already_Open = 0; 205 -206 /* -207 * Wake up all the processes in WaitQ, so if anybody is waiting for the -208 * file, they can have it. -209 */ +206 /* +207 * Wake up all the processes in WaitQ, so if anybody is waiting for the +208 * file, they can have it. +209 */ 210 wake_up(&WaitQ); 211 212 module_put(THIS_MODULE); 213 -214 return 0; /* success */ +214 return 0; /* success */ 215} 216 -217/* -218 * Structures to register as the /proc file, with pointers to all the relevant -219 * functions. -220 */ +217/* +218 * Structures to register as the /proc file, with pointers to all the relevant +219 * functions. +220 */ 221 -222/* -223 * File operations for our proc file. This is where we place pointers to all -224 * the functions called when somebody tries to do something to our file. NULL -225 * means we don't want to deal with something. -226 */ -227#ifdef HAVE_PROC_OPS -228static const struct proc_ops File_Ops_4_Our_Proc_File = { -229 .proc_read = module_output, /* "read" from the file */ -230 .proc_write = module_input, /* "write" to the file */ -231 .proc_open = module_open, /* called when the /proc file is opened */ -232 .proc_release = module_close, /* called when it's closed */ +222/* +223 * File operations for our proc file. This is where we place pointers to all +224 * the functions called when somebody tries to do something to our file. NULL +225 * means we don't want to deal with something. +226 */ +227#ifdef HAVE_PROC_OPS +228static const struct proc_ops File_Ops_4_Our_Proc_File = { +229 .proc_read = module_output, /* "read" from the file */ +230 .proc_write = module_input, /* "write" to the file */ +231 .proc_open = module_open, /* called when the /proc file is opened */ +232 .proc_release = module_close, /* called when it's closed */ 233}; -234#else -235static const struct file_operations File_Ops_4_Our_Proc_File = { +234#else +235static const struct file_operations File_Ops_4_Our_Proc_File = { 236 .read = module_output, 237 .write = module_input, 238 .open = module_open, 239 .release = module_close, 240}; -241#endif +241#endif 242 -243/* -244 * Module initialization and cleanup -245 */ +243/* +244 * Module initialization and cleanup +245 */ 246 -247/* -248 * Initialize the module - register the proc file -249 */ +247/* +248 * Initialize the module - register the proc file +249 */ 250 -251int init_module() +251int init_module() 252{ 253 Our_Proc_File = 254 proc_create(PROC_ENTRY_FILENAME, 0644, NULL, &File_Ops_4_Our_Proc_File); -255 if (Our_Proc_File == NULL) { +255 if (Our_Proc_File == NULL) { 256 remove_proc_entry(PROC_ENTRY_FILENAME, NULL); -257 pr_debug("Error: Could not initialize /proc/%s\n", PROC_ENTRY_FILENAME); -258 return -ENOMEM; +257 pr_debug("Error: Could not initialize /proc/%s\n", PROC_ENTRY_FILENAME); +258 return -ENOMEM; 259 } 260 proc_set_size(Our_Proc_File, 80); 261 proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID); 262 -263 pr_info("/proc/test created\n"); +263 pr_info("/proc/test created\n"); 264 -265 return 0; +265 return 0; 266} 267 -268/* -269 * Cleanup - unregister our file from /proc. This could get dangerous if -270 * there are still processes waiting in WaitQ, because they are inside our -271 * open function, which will get unloaded. I'll explain how to avoid removal -272 * of a kernel module in such a case in chapter 10. -273 */ -274void cleanup_module() +268/* +269 * Cleanup - unregister our file from /proc. This could get dangerous if +270 * there are still processes waiting in WaitQ, because they are inside our +271 * open function, which will get unloaded. I'll explain how to avoid removal +272 * of a kernel module in such a case in chapter 10. +273 */ +274void cleanup_module() 275{ 276 remove_proc_entry(PROC_ENTRY_FILENAME, NULL); -277 pr_debug("/proc/%s removed\n", PROC_ENTRY_FILENAME); +277 pr_debug("/proc/%s removed\n", PROC_ENTRY_FILENAME); 278} 279 -280MODULE_LICENSE("GPL");+280MODULE_LICENSE("GPL");-
1/* -2 * cat_nonblock.c - open a file and display its contents, but exit rather than -3 * wait for input. -4 */ -5#include <errno.h> /* for errno */ -6#include <fcntl.h> /* for open */ -7#include <stdio.h> /* standard I/O */ -8#include <stdlib.h> /* for exit */ -9#include <unistd.h> /* for read */ +1/* +2 * cat_nonblock.c - open a file and display its contents, but exit rather than +3 * wait for input. +4 */ +5#include <errno.h> /* for errno */ +6#include <fcntl.h> /* for open */ +7#include <stdio.h> /* standard I/O */ +8#include <stdlib.h> /* for exit */ +9#include <unistd.h> /* for read */ 10 -11#define MAX_BYTES 1024 * 4 +11#define MAX_BYTES 1024 * 4 12 -13int main(int argc, char *argv[]) +13int main(int argc, char *argv[]) 14{ -15 int fd; /* The file descriptor for the file to read */ -16 size_t bytes; /* The number of bytes read */ -17 char buffer[MAX_BYTES]; /* The buffer for the bytes */ +15 int fd; /* The file descriptor for the file to read */ +16 size_t bytes; /* The number of bytes read */ +17 char buffer[MAX_BYTES]; /* The buffer for the bytes */ 18 -19 /* Usage */ -20 if (argc != 2) { -21 printf("Usage: %s <filename>\n", argv[0]); -22 puts("Reads the content of a file, but doesn't wait for input"); +19 /* Usage */ +20 if (argc != 2) { +21 printf("Usage: %s <filename>\n", argv[0]); +22 puts("Reads the content of a file, but doesn't wait for input"); 23 exit(-1); 24 } 25 -26 /* Open the file for reading in non blocking mode */ +26 /* Open the file for reading in non blocking mode */ 27 fd = open(argv[1], O_RDONLY | O_NONBLOCK); 28 -29 /* If open failed */ -30 if (fd == -1) { -31 puts(errno == EAGAIN ? "Open would block" : "Open failed"); +29 /* If open failed */ +30 if (fd == -1) { +31 puts(errno == EAGAIN ? "Open would block" : "Open failed"); 32 exit(-1); 33 } 34 -35 /* Read the file and output its contents */ -36 do { -37 /* Read characters from the file */ +35 /* Read the file and output its contents */ +36 do { +37 /* Read characters from the file */ 38 bytes = read(fd, buffer, MAX_BYTES); 39 -40 /* If there's an error, report it and die */ -41 if (bytes == -1) { -42 if (errno = EAGAIN) -43 puts("Normally I'd block, but you told me not to"); -44 else -45 puts("Another read error"); +40 /* If there's an error, report it and die */ +41 if (bytes == -1) { +42 if (errno = EAGAIN) +43 puts("Normally I'd block, but you told me not to"); +44 else +45 puts("Another read error"); 46 exit(-1); 47 } 48 -49 /* Print the characters */ -50 if (bytes > 0) { -51 for (int i = 0; i < bytes; i++) +49 /* Print the characters */ +50 if (bytes > 0) { +51 for (int i = 0; i < bytes; i++) 52 putchar(buffer[i]); 53 } 54 -55 /* While there are no errors and the file isn't over */ -56 } while (bytes > 0); +55 /* While there are no errors and the file isn't over */ +56 } while (bytes > 0); 57 -58 return 0; +58 return 0; 59}@@ -3578,82 +3553,82 @@ another. -
1/* -2 * completions.c -3 */ -4#include <linux/completion.h> -5#include <linux/init.h> -6#include <linux/kernel.h> -7#include <linux/kthread.h> -8#include <linux/module.h> +1/* +2 * completions.c +3 */ +4#include <linux/completion.h> +5#include <linux/init.h> +6#include <linux/kernel.h> +7#include <linux/kthread.h> +8#include <linux/module.h> 9 -10static struct { -11 struct completion crank_comp; -12 struct completion flywheel_comp; +10static struct { +11 struct completion crank_comp; +12 struct completion flywheel_comp; 13} machine; 14 -15static int machine_crank_thread(void *arg) +15static int machine_crank_thread(void *arg) 16{ -17 pr_info("Turn the crank\n"); +17 pr_info("Turn the crank\n"); 18 19 complete_all(&machine.crank_comp); 20 complete_and_exit(&machine.crank_comp, 0); 21} 22 -23static int machine_flywheel_spinup_thread(void *arg) +23static int machine_flywheel_spinup_thread(void *arg) 24{ 25 wait_for_completion(&machine.crank_comp); 26 -27 pr_info("Flywheel spins up\n"); +27 pr_info("Flywheel spins up\n"); 28 29 complete_all(&machine.flywheel_comp); 30 complete_and_exit(&machine.flywheel_comp, 0); 31} 32 -33static int completions_init(void) +33static int completions_init(void) 34{ -35 struct task_struct *crank_thread; -36 struct task_struct *flywheel_thread; +35 struct task_struct *crank_thread; +36 struct task_struct *flywheel_thread; 37 -38 pr_info("completions example\n"); +38 pr_info("completions example\n"); 39 40 init_completion(&machine.crank_comp); 41 init_completion(&machine.flywheel_comp); 42 -43 crank_thread = kthread_create(machine_crank_thread, NULL, "KThread Crank"); -44 if (IS_ERR(crank_thread)) -45 goto ERROR_THREAD_1; +43 crank_thread = kthread_create(machine_crank_thread, NULL, "KThread Crank"); +44 if (IS_ERR(crank_thread)) +45 goto ERROR_THREAD_1; 46 47 flywheel_thread = kthread_create(machine_flywheel_spinup_thread, NULL, -48 "KThread Flywheel"); -49 if (IS_ERR(flywheel_thread)) -50 goto ERROR_THREAD_2; +48 "KThread Flywheel"); +49 if (IS_ERR(flywheel_thread)) +50 goto ERROR_THREAD_2; 51 52 wake_up_process(flywheel_thread); 53 wake_up_process(crank_thread); 54 -55 return 0; +55 return 0; 56 57ERROR_THREAD_2: 58 kthread_stop(crank_thread); 59ERROR_THREAD_1: 60 -61 return -1; +61 return -1; 62} 63 -64void completions_exit(void) +64void completions_exit(void) 65{ 66 wait_for_completion(&machine.crank_comp); 67 wait_for_completion(&machine.flywheel_comp); 68 -69 pr_info("completions exit\n"); +69 pr_info("completions exit\n"); 70} 71 72module_init(completions_init); 73module_exit(completions_exit); 74 -75MODULE_DESCRIPTION("Completions example"); -76MODULE_LICENSE("GPL");+75MODULE_DESCRIPTION("Completions example"); +76MODULE_LICENSE("GPL");The machine structure stores the completion states for the two threads. At the exit point of each thread the respective completion state is updated, and {wait_for_completion is used by the flywheel thread to ensure that it does not @@ -3679,47 +3654,47 @@ might deploy them in userland. This may be all that is needed to avoid collision most cases.
-
1/* -2 * example_mutex.c -3 */ -4#include <linux/init.h> -5#include <linux/kernel.h> -6#include <linux/module.h> -7#include <linux/mutex.h> +1/* +2 * example_mutex.c +3 */ +4#include <linux/init.h> +5#include <linux/kernel.h> +6#include <linux/module.h> +7#include <linux/mutex.h> 8 9DEFINE_MUTEX(mymutex); 10 -11static int example_mutex_init(void) +11static int example_mutex_init(void) 12{ -13 int ret; +13 int ret; 14 -15 pr_info("example_mutex init\n"); +15 pr_info("example_mutex init\n"); 16 17 ret = mutex_trylock(&mymutex); -18 if (ret != 0) { -19 pr_info("mutex is locked\n"); +18 if (ret != 0) { +19 pr_info("mutex is locked\n"); 20 -21 if (mutex_is_locked(&mymutex) == 0) -22 pr_info("The mutex failed to lock!\n"); +21 if (mutex_is_locked(&mymutex) == 0) +22 pr_info("The mutex failed to lock!\n"); 23 24 mutex_unlock(&mymutex); -25 pr_info("mutex is unlocked\n"); -26 } else -27 pr_info("Failed to lock\n"); +25 pr_info("mutex is unlocked\n"); +26 } else +27 pr_info("Failed to lock\n"); 28 -29 return 0; +29 return 0; 30} 31 -32static void example_mutex_exit(void) +32static void example_mutex_exit(void) 33{ -34 pr_info("example_mutex exit\n"); +34 pr_info("example_mutex exit\n"); 35} 36 37module_init(example_mutex_init); 38module_exit(example_mutex_exit); 39 -40MODULE_DESCRIPTION("Mutex example"); -41MODULE_LICENSE("GPL");+40MODULE_DESCRIPTION("Mutex example"); +41MODULE_LICENSE("GPL");
0.12.2 Spinlocks
@@ -3736,71 +3711,71 @@ they will not be forgotten and will activate when the unlock happens, using the variable to retain their state.-
1/* -2 * example_spinlock.c -3 */ -4#include <linux/init.h> -5#include <linux/interrupt.h> -6#include <linux/kernel.h> -7#include <linux/module.h> -8#include <linux/spinlock.h> +1/* +2 * example_spinlock.c +3 */ +4#include <linux/init.h> +5#include <linux/interrupt.h> +6#include <linux/kernel.h> +7#include <linux/module.h> +8#include <linux/spinlock.h> 9 10DEFINE_SPINLOCK(sl_static); 11spinlock_t sl_dynamic; 12 -13static void example_spinlock_static(void) +13static void example_spinlock_static(void) 14{ -15 unsigned long flags; +15 unsigned long flags; 16 17 spin_lock_irqsave(&sl_static, flags); -18 pr_info("Locked static spinlock\n"); +18 pr_info("Locked static spinlock\n"); 19 -20 /* Do something or other safely. -21 Because this uses 100% CPU time this -22 code should take no more than a few -23 milliseconds to run */ +20 /* Do something or other safely. +21 Because this uses 100% CPU time this +22 code should take no more than a few +23 milliseconds to run */ 24 25 spin_unlock_irqrestore(&sl_static, flags); -26 pr_info("Unlocked static spinlock\n"); +26 pr_info("Unlocked static spinlock\n"); 27} 28 -29static void example_spinlock_dynamic(void) +29static void example_spinlock_dynamic(void) 30{ -31 unsigned long flags; +31 unsigned long flags; 32 33 spin_lock_init(&sl_dynamic); 34 spin_lock_irqsave(&sl_dynamic, flags); -35 pr_info("Locked dynamic spinlock\n"); +35 pr_info("Locked dynamic spinlock\n"); 36 -37 /* Do something or other safely. -38 Because this uses 100% CPU time this -39 code should take no more than a few -40 milliseconds to run */ +37 /* Do something or other safely. +38 Because this uses 100% CPU time this +39 code should take no more than a few +40 milliseconds to run */ 41 42 spin_unlock_irqrestore(&sl_dynamic, flags); -43 pr_info("Unlocked dynamic spinlock\n"); +43 pr_info("Unlocked dynamic spinlock\n"); 44} 45 -46static int example_spinlock_init(void) +46static int example_spinlock_init(void) 47{ -48 pr_info("example spinlock started\n"); +48 pr_info("example spinlock started\n"); 49 50 example_spinlock_static(); 51 example_spinlock_dynamic(); 52 -53 return 0; +53 return 0; 54} 55 -56static void example_spinlock_exit(void) +56static void example_spinlock_exit(void) 57{ -58 pr_info("example spinlock exit\n"); +58 pr_info("example spinlock exit\n"); 59} 60 61module_init(example_spinlock_init); 62module_exit(example_spinlock_exit); 63 -64MODULE_DESCRIPTION("Spinlock example"); -65MODULE_LICENSE("GPL");+64MODULE_DESCRIPTION("Spinlock example"); +65MODULE_LICENSE("GPL");
0.12.3 Read and write locks
@@ -3814,61 +3789,61 @@ the system and cause users to start revolting against the tyranny of your module.-
1/* -2 * example_rwlock.c -3 */ -4#include <linux/interrupt.h> -5#include <linux/kernel.h> -6#include <linux/module.h> +1/* +2 * example_rwlock.c +3 */ +4#include <linux/interrupt.h> +5#include <linux/kernel.h> +6#include <linux/module.h> 7 8DEFINE_RWLOCK(myrwlock); 9 -10static void example_read_lock(void) +10static void example_read_lock(void) 11{ -12 unsigned long flags; +12 unsigned long flags; 13 14 read_lock_irqsave(&myrwlock, flags); -15 pr_info("Read Locked\n"); +15 pr_info("Read Locked\n"); 16 -17 /* Read from something */ +17 /* Read from something */ 18 19 read_unlock_irqrestore(&myrwlock, flags); -20 pr_info("Read Unlocked\n"); +20 pr_info("Read Unlocked\n"); 21} 22 -23static void example_write_lock(void) +23static void example_write_lock(void) 24{ -25 unsigned long flags; +25 unsigned long flags; 26 27 write_lock_irqsave(&myrwlock, flags); -28 pr_info("Write Locked\n"); +28 pr_info("Write Locked\n"); 29 -30 /* Write to something */ +30 /* Write to something */ 31 32 write_unlock_irqrestore(&myrwlock, flags); -33 pr_info("Write Unlocked\n"); +33 pr_info("Write Unlocked\n"); 34} 35 -36static int example_rwlock_init(void) +36static int example_rwlock_init(void) 37{ -38 pr_info("example_rwlock started\n"); +38 pr_info("example_rwlock started\n"); 39 40 example_read_lock(); 41 example_write_lock(); 42 -43 return 0; +43 return 0; 44} 45 -46static void example_rwlock_exit(void) +46static void example_rwlock_exit(void) 47{ -48 pr_info("example_rwlock exit\n"); +48 pr_info("example_rwlock exit\n"); 49} 50 51module_init(example_rwlock_init); 52module_exit(example_rwlock_exit); 53 -54MODULE_DESCRIPTION("Read/Write locks example"); -55MODULE_LICENSE("GPL");+54MODULE_DESCRIPTION("Read/Write locks example"); +55MODULE_LICENSE("GPL");Of course, if you know for sure that there are no functions triggered by irqs which could possibly interfere with your logic then you can use the simpler read_lock(&myrwlock) and read_unlock(&myrwlock) or the corresponding write @@ -3883,246 +3858,246 @@ and was not overwritten by some other shenanigans. An example is shown below.
-
1/* -2 * example_atomic.c -3 */ -4#include <linux/interrupt.h> -5#include <linux/kernel.h> -6#include <linux/module.h> +-1/* +2 * example_atomic.c +3 */ +4#include <linux/interrupt.h> +5#include <linux/kernel.h> +6#include <linux/module.h> 7 -8#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" -9#define BYTE_TO_BINARY(byte) \ -10 (byte & 0x80 ? '1' : '0'), (byte & 0x40 ? '1' : '0'), \ -11 (byte & 0x20 ? '1' : '0'), (byte & 0x10 ? '1' : '0'), \ -12 (byte & 0x08 ? '1' : '0'), (byte & 0x04 ? '1' : '0'), \ -13 (byte & 0x02 ? '1' : '0'), (byte & 0x01 ? '1' : '0') +8#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" +9#define BYTE_TO_BINARY(byte) \ +10 (byte & 0x80 ? '1' : '0'), (byte & 0x40 ? '1' : '0'), \ +11 (byte & 0x20 ? '1' : '0'), (byte & 0x10 ? '1' : '0'), \ +12 (byte & 0x08 ? '1' : '0'), (byte & 0x04 ? '1' : '0'), \ +13 (byte & 0x02 ? '1' : '0'), (byte & 0x01 ? '1' : '0') 14 -15static void atomic_add_subtract(void) +15static void atomic_add_subtract(void) 16{ 17 atomic_t debbie; 18 atomic_t chris = ATOMIC_INIT(50); 19 20 atomic_set(&debbie, 45); 21 -22 /* subtract one */ +22 /* subtract one */ 23 atomic_dec(&debbie); 24 25 atomic_add(7, &debbie); 26 -27 /* add one */ +27 /* add one */ 28 atomic_inc(&debbie); 29 -30 pr_info("chris: %d, debbie: %d\n", atomic_read(&chris), +30 pr_info("chris: %d, debbie: %d\n", atomic_read(&chris), 31 atomic_read(&debbie)); 32} 33 -34static void atomic_bitwise(void) +34static void atomic_bitwise(void) 35{ -36 unsigned long word = 0; +36 unsigned long word = 0; 37 -38 pr_info("Bits 0: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); +38 pr_info("Bits 0: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 39 set_bit(3, &word); 40 set_bit(5, &word); -41 pr_info("Bits 1: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); +41 pr_info("Bits 1: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 42 clear_bit(5, &word); -43 pr_info("Bits 2: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); +43 pr_info("Bits 2: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 44 change_bit(3, &word); 45 -46 pr_info("Bits 3: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); -47 if (test_and_set_bit(3, &word)) -48 pr_info("wrong\n"); -49 pr_info("Bits 4: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); +46 pr_info("Bits 3: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); +47 if (test_and_set_bit(3, &word)) +48 pr_info("wrong\n"); +49 pr_info("Bits 4: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 50 51 word = 255; -52 pr_info("Bits 5: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); +52 pr_info("Bits 5: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 53} 54 -55static int example_atomic_init(void) +55static int example_atomic_init(void) 56{ -57 pr_info("example_atomic started\n"); +57 pr_info("example_atomic started\n"); 58 59 atomic_add_subtract(); 60 atomic_bitwise(); 61 -62 return 0; +62 return 0; 63} 64 -65static void example_atomic_exit(void) +65static void example_atomic_exit(void) 66{ -67 pr_info("example_atomic exit\n"); +67 pr_info("example_atomic exit\n"); 68} 69 70module_init(example_atomic_init); 71module_exit(example_atomic_exit); 72 -73MODULE_DESCRIPTION("Atomic operations example"); -74MODULE_LICENSE("GPL");+73MODULE_DESCRIPTION("Atomic operations example"); +74MODULE_LICENSE("GPL");+
0.13 Replacing Print Macros
-+
0.13.1 Replacement
-In Section 1.2.1.2, I said that X and kernel module programming don’t mix. That’s +
In Section 1.2.1.2, I said that X and kernel module programming do not mix. That is true for developing kernel modules, but in actual use, you want to be able to send messages to whichever tty the command to load the module came from. -
"tty" is an abbreviation of teletype: originally a combination keyboard-printer +
"tty" is an abbreviation of teletype: originally a combination keyboard-printer used to communicate with a Unix system, and today an abstraction for the text -stream used for a Unix program, whether it’s a physical terminal, an xterm on an X +stream used for a Unix program, whether it is a physical terminal, an xterm on an X display, a network connection used with ssh, etc. -
The way this is done is by using current, a pointer to the currently running task, +
The way this is done is by using current, a pointer to the currently running task, to get the current task’s tty structure. Then, we look inside that tty structure to find a pointer to a string write function, which we use to write a string to the tty.
-
1/* -2 * print_string.c - Send output to the tty we're running on, regardless if it's -3 * through X11, telnet, etc. We do this by printing the string to the tty -4 * associated with the current task. -5 */ -6#include <linux/init.h> -7#include <linux/kernel.h> -8#include <linux/module.h> -9#include <linux/sched.h> /* For current */ -10#include <linux/tty.h> /* For the tty declarations */ +1/* +2 * print_string.c - Send output to the tty we're running on, regardless if it's +3 * through X11, telnet, etc. We do this by printing the string to the tty +4 * associated with the current task. +5 */ +6#include <linux/init.h> +7#include <linux/kernel.h> +8#include <linux/module.h> +9#include <linux/sched.h> /* For current */ +10#include <linux/tty.h> /* For the tty declarations */ 11 -12MODULE_LICENSE("GPL"); +12MODULE_LICENSE("GPL"); 13 -14static void print_string(char *str) +14static void print_string(char *str) 15{ -16 struct tty_struct *my_tty; -17 const struct tty_operations *ttyops; +16 struct tty_struct *my_tty; +17 const struct tty_operations *ttyops; 18 -19 /* -20 * The tty for the current task, for 2.6.6+ kernels -21 */ +19 /* +20 * The tty for the current task, for 2.6.6+ kernels +21 */ 22 my_tty = get_current_tty(); 23 ttyops = my_tty->driver->ops; 24 -25 /* -26 * If my_tty is NULL, the current task has no tty you can print to -27 * (ie, if it's a daemon). If so, there's nothing we can do. -28 */ -29 if (my_tty != NULL) { -30 /* -31 * my_tty->driver is a struct which holds the tty's functions, -32 * one of which (write) is used to write strings to the tty. -33 * It can be used to take a string either from the user's or -34 * kernel's memory segment. -35 * -36 * The function's 1st parameter is the tty to write to, -37 * because the same function would normally be used for all -38 * tty's of a certain type. -39 * The 2nd parameter is a pointer to a string. -40 * The 3rd parameter is the length of the string. -41 * -42 * As you will see below, sometimes it's necessary to use -43 * preprocessor stuff to create code that works for different -44 * kernel versions. The (naive) approach we've taken here -45 * does not scale well. The right way to deal with this -46 * is described in section 2 of -47 * linux/Documentation/SubmittingPatches -48 */ -49 (ttyops->write)(my_tty, /* The tty itself */ -50 str, /* String */ -51 strlen(str)); /* Length */ +25 /* +26 * If my_tty is NULL, the current task has no tty you can print to +27 * (ie, if it's a daemon). If so, there's nothing we can do. +28 */ +29 if (my_tty != NULL) { +30 /* +31 * my_tty->driver is a struct which holds the tty's functions, +32 * one of which (write) is used to write strings to the tty. +33 * It can be used to take a string either from the user's or +34 * kernel's memory segment. +35 * +36 * The function's 1st parameter is the tty to write to, +37 * because the same function would normally be used for all +38 * tty's of a certain type. +39 * The 2nd parameter is a pointer to a string. +40 * The 3rd parameter is the length of the string. +41 * +42 * As you will see below, sometimes it's necessary to use +43 * preprocessor stuff to create code that works for different +44 * kernel versions. The (naive) approach we've taken here +45 * does not scale well. The right way to deal with this +46 * is described in section 2 of +47 * linux/Documentation/SubmittingPatches +48 */ +49 (ttyops->write)(my_tty, /* The tty itself */ +50 str, /* String */ +51 strlen(str)); /* Length */ 52 -53 /* -54 * ttys were originally hardware devices, which (usually) -55 * strictly followed the ASCII standard. In ASCII, to move to -56 * a new line you need two characters, a carriage return and a -57 * line feed. On Unix, the ASCII line feed is used for both -58 * purposes - so we can't just use \n, because it wouldn't have -59 * a carriage return and the next line will start at the -60 * column right after the line feed. -61 * -62 * This is why text files are different between Unix and -63 * MS Windows. In CP/M and derivatives, like MS-DOS and -64 * MS Windows, the ASCII standard was strictly adhered to, -65 * and therefore a newline requirs both a LF and a CR. -66 */ -67 (ttyops->write)(my_tty, "\015\012", 2); +53 /* +54 * ttys were originally hardware devices, which (usually) +55 * strictly followed the ASCII standard. In ASCII, to move to +56 * a new line you need two characters, a carriage return and a +57 * line feed. On Unix, the ASCII line feed is used for both +58 * purposes - so we can't just use \n, because it wouldn't have +59 * a carriage return and the next line will start at the +60 * column right after the line feed. +61 * +62 * This is why text files are different between Unix and +63 * MS Windows. In CP/M and derivatives, like MS-DOS and +64 * MS Windows, the ASCII standard was strictly adhered to, +65 * and therefore a newline requirs both a LF and a CR. +66 */ +67 (ttyops->write)(my_tty, "\015\012", 2); 68 } 69} 70 -71static int __init print_string_init(void) +71static int __init print_string_init(void) 72{ -73 print_string("The module has been inserted. Hello world!"); -74 return 0; +73 print_string("The module has been inserted. Hello world!"); +74 return 0; 75} 76 -77static void __exit print_string_exit(void) +77static void __exit print_string_exit(void) 78{ -79 print_string("The module has been removed. Farewell world!"); +79 print_string("The module has been removed. Farewell world!"); 80} 81 82module_init(print_string_init); 83module_exit(print_string_exit);-+
0.13.2 Flashing keyboard LEDs
-In certain conditions, you may desire a simpler and more direct way to communicate +
In certain conditions, you may desire a simpler and more direct way to communicate to the external world. Flashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition. Keyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file. -
The following source code illustrates a minimal kernel module which, when +
The following source code illustrates a minimal kernel module which, when loaded, starts blinking the keyboard LEDs until it is unloaded.
-
1/* -2 * kbleds.c - Blink keyboard leds until the module is unloaded. -3 */ +-1/* +2 * kbleds.c - Blink keyboard leds until the module is unloaded. +3 */ 4 -5#include <linux/init.h> -6#include <linux/kd.h> /* For KDSETLED */ -7#include <linux/module.h> -8#include <linux/tty.h> /* For fg_console, MAX_NR_CONSOLES */ -9#include <linux/vt.h> -10#include <linux/vt_kern.h> /* for fg_console */ +5#include <linux/init.h> +6#include <linux/kd.h> /* For KDSETLED */ +7#include <linux/module.h> +8#include <linux/tty.h> /* For fg_console, MAX_NR_CONSOLES */ +9#include <linux/vt.h> +10#include <linux/vt_kern.h> /* for fg_console */ 11 -12#include <linux/console_struct.h> /* For vc_cons */ +12#include <linux/console_struct.h> /* For vc_cons */ 13 -14MODULE_DESCRIPTION("Example module illustrating the use of Keyboard LEDs."); -15MODULE_LICENSE("GPL"); +14MODULE_DESCRIPTION("Example module illustrating the use of Keyboard LEDs."); +15MODULE_LICENSE("GPL"); 16 -17struct timer_list my_timer; -18struct tty_driver *my_driver; -19char kbledstatus = 0; +17struct timer_list my_timer; +18struct tty_driver *my_driver; +19char kbledstatus = 0; 20 -21#define BLINK_DELAY HZ / 5 -22#define ALL_LEDS_ON 0x07 -23#define RESTORE_LEDS 0xFF +21#define BLINK_DELAY HZ / 5 +22#define ALL_LEDS_ON 0x07 +23#define RESTORE_LEDS 0xFF 24 -25/* -26 * Function my_timer_func blinks the keyboard LEDs periodically by invoking -27 * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual -28 * terminal ioctl operations, please see file: -29 * /usr/src/linux/drivers/char/vt_ioctl.c, function vt_ioctl(). -30 * -31 * The argument to KDSETLED is alternatively set to 7 (thus causing the led -32 * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF -33 * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus -34 * the LEDs reflect the actual keyboard status). To learn more on this, -35 * please see file: -36 * /usr/src/linux/drivers/char/keyboard.c, function setledstate(). -37 * -38 */ +25/* +26 * Function my_timer_func blinks the keyboard LEDs periodically by invoking +27 * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual +28 * terminal ioctl operations, please see file: +29 * /usr/src/linux/drivers/char/vt_ioctl.c, function vt_ioctl(). +30 * +31 * The argument to KDSETLED is alternatively set to 7 (thus causing the led +32 * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF +33 * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus +34 * the LEDs reflect the actual keyboard status). To learn more on this, +35 * please see file: +36 * /usr/src/linux/drivers/char/keyboard.c, function setledstate(). +37 * +38 */ 39 -40static void my_timer_func(unsigned long ptr) +40static void my_timer_func(unsigned long ptr) 41{ -42 unsigned long *pstatus = (unsigned long *) ptr; -43 struct tty_struct *t = vc_cons[fg_console].d->port.tty; +42 unsigned long *pstatus = (unsigned long *) ptr; +43 struct tty_struct *t = vc_cons[fg_console].d->port.tty; 44 -45 if (*pstatus == ALL_LEDS_ON) +45 if (*pstatus == ALL_LEDS_ON) 46 *pstatus = RESTORE_LEDS; -47 else +47 else 48 *pstatus = ALL_LEDS_ON; 49 50 (my_driver->ops->ioctl)(t, KDSETLED, *pstatus); @@ -4131,37 +4106,37 @@ loaded, starts blinking the keyboard LEDs until it is unloaded. 53 add_timer(&my_timer); 54} 55 -56static int __init kbleds_init(void) +56static int __init kbleds_init(void) 57{ -58 int i; +58 int i; 59 -60 pr_info("kbleds: loading\n"); -61 pr_info("kbleds: fgconsole is %x\n", fg_console); -62 for (i = 0; i < MAX_NR_CONSOLES; i++) { -63 if (!vc_cons[i].d) -64 break; -65 pr_info("poet_atkm: console[%i/%i] #%i, tty %lx\n", i, MAX_NR_CONSOLES, -66 vc_cons[i].d->vc_num, (unsigned long) vc_cons[i].d->port.tty); +60 pr_info("kbleds: loading\n"); +61 pr_info("kbleds: fgconsole is %x\n", fg_console); +62 for (i = 0; i < MAX_NR_CONSOLES; i++) { +63 if (!vc_cons[i].d) +64 break; +65 pr_info("poet_atkm: console[%i/%i] #%i, tty %lx\n", i, MAX_NR_CONSOLES, +66 vc_cons[i].d->vc_num, (unsigned long) vc_cons[i].d->port.tty); 67 } -68 pr_info("kbleds: finished scanning consoles\n"); +68 pr_info("kbleds: finished scanning consoles\n"); 69 70 my_driver = vc_cons[fg_console].d->port.tty->driver; -71 pr_info("kbleds: tty driver magic %x\n", my_driver->magic); +71 pr_info("kbleds: tty driver magic %x\n", my_driver->magic); 72 -73 /* -74 * Set up the LED blink timer the first time -75 */ -76 timer_setup(&my_timer, (void *) &my_timer_func, -77 (unsigned long) &kbledstatus); +73 /* +74 * Set up the LED blink timer the first time +75 */ +76 timer_setup(&my_timer, (void *) &my_timer_func, +77 (unsigned long) &kbledstatus); 78 my_timer.expires = jiffies + BLINK_DELAY; 79 add_timer(&my_timer); 80 -81 return 0; +81 return 0; 82} 83 -84static void __exit kbleds_cleanup(void) +84static void __exit kbleds_cleanup(void) 85{ -86 pr_info("kbleds: unloading...\n"); +86 pr_info("kbleds: unloading...\n"); 87 del_timer(&my_timer); 88 (my_driver->ops->ioctl)(vc_cons[fg_console].d->port.tty, KDSETLED, 89 RESTORE_LEDS); @@ -4169,77 +4144,77 @@ loaded, starts blinking the keyboard LEDs until it is unloaded. 91 92module_init(kbleds_init); 93module_exit(kbleds_cleanup);-If none of the examples in this chapter fit your debugging needs there might yet -be some other tricks to try. Ever wondered what CONFIG_LL_DEBUG in -make menuconfig is good for? If you activate that you get low level access -to the serial port. While this might not sound very powerful by itself, you +
If none of the examples in this chapter fit your debugging needs there might yet +be some other tricks to try. Ever wondered what CONFIG_LL_DEBUG in make +menuconfig is good for? If you activate that you get low level access to the serial +port. While this might not sound very powerful by itself, you can patch -can patch kernel/printk.c or any other essential syscall to use printascii, +kernel/printk.c or any other essential syscall to print ASCII characters, thus makeing it possible to trace virtually everything what your code does over a serial line. If you find yourself porting the kernel to some new and -former unsupported architecture this is usually amongst the first things that +former unsupported architecture, this is usually amongst the first things that should be implemented. Logging over a netconsole might also be worth a try. -
While you have seen lots of stuff that can be used to aid debugging here, there are +
While you have seen lots of stuff that can be used to aid debugging here, there are some things to be aware of. Debugging is almost always intrusive. Adding debug code can change the situation enough to make the bug seem to dissappear. Thus you should try to keep debug code to a minimum and make sure it does not show up in production code. -
+
0.14 Scheduling Tasks
-There are two main ways of running tasks: tasklets and work queues. Tasklets are a +
There are two main ways of running tasks: tasklets and work queues. Tasklets are a quick and easy way of scheduling a single function to be run, for example when triggered from an interrupt, whereas work queues are more complicated but also better suited to running multiple things in a sequence. -
+
0.14.1 Tasklets
-Here’s an example tasklet module. The tasklet_fn function runs for a few seconds -and in the mean time execution of the example_tasklet_init function continues to +
Here is an example tasklet module. The tasklet_fn function runs for a few seconds +and in the mean time execution of the example_tasklet_init function continues to the exit point.
-
1/* -2 * example_tasklet.c -3 */ -4#include <linux/delay.h> -5#include <linux/interrupt.h> -6#include <linux/kernel.h> -7#include <linux/module.h> ++1/* +2 * example_tasklet.c +3 */ +4#include <linux/delay.h> +5#include <linux/interrupt.h> +6#include <linux/kernel.h> +7#include <linux/module.h> 8 -9static void tasklet_fn(unsigned long data) +9static void tasklet_fn(unsigned long data) 10{ -11 pr_info("Example tasklet starts\n"); +11 pr_info("Example tasklet starts\n"); 12 mdelay(5000); -13 pr_info("Example tasklet ends\n"); +13 pr_info("Example tasklet ends\n"); 14} 15 16DECLARE_TASKLET(mytask, tasklet_fn, 0L); 17 -18static int example_tasklet_init(void) +18static int example_tasklet_init(void) 19{ -20 pr_info("tasklet example init\n"); +20 pr_info("tasklet example init\n"); 21 tasklet_schedule(&mytask); 22 mdelay(200); -23 pr_info("Example tasklet init continues...\n"); -24 return 0; +23 pr_info("Example tasklet init continues...\n"); +24 return 0; 25} 26 -27static void example_tasklet_exit(void) +27static void example_tasklet_exit(void) 28{ -29 pr_info("tasklet example exit\n"); +29 pr_info("tasklet example exit\n"); 30 tasklet_kill(&mytask); 31} 32 33module_init(example_tasklet_init); 34module_exit(example_tasklet_exit); 35 -36MODULE_DESCRIPTION("Tasklet example"); -37MODULE_LICENSE("GPL");-So with this example loaded dmesg should show: +36MODULE_DESCRIPTION("Tasklet example"); +37MODULE_LICENSE("GPL");
So with this example loaded dmesg should show: @@ -4250,74 +4225,74 @@ Example tasklet starts Example tasklet init continues... Example tasklet ends
-
+
+
0.14.2 Work queues
-To add a task to the scheduler we can use a workqueue. The kernel then uses the +
To add a task to the scheduler we can use a workqueue. The kernel then uses the Completely Fair Scheduler (CFS) to execute work within the queue.
-
1/* -2 * sched.c -3 */ -4#include <linux/init.h> -5#include <linux/module.h> -6#include <linux/workqueue.h> ++1/* +2 * sched.c +3 */ +4#include <linux/init.h> +5#include <linux/module.h> +6#include <linux/workqueue.h> 7 -8static struct workqueue_struct *queue = NULL; -9static struct work_struct work; +8static struct workqueue_struct *queue = NULL; +9static struct work_struct work; 10 -11static void work_handler(struct work_struct *data) +11static void work_handler(struct work_struct *data) 12{ -13 pr_info("work handler function.\n"); +13 pr_info("work handler function.\n"); 14} 15 -16int init_module() +16int init_module() 17{ -18 queue = alloc_workqueue("HELLOWORLD", WQ_UNBOUND, 1); +18 queue = alloc_workqueue("HELLOWORLD", WQ_UNBOUND, 1); 19 INIT_WORK(&work, work_handler); 20 schedule_work(&work); 21 -22 return 0; +22 return 0; 23} 24 -25void cleanup_module() +25void cleanup_module() 26{ 27 destroy_workqueue(queue); 28} 29 -30MODULE_LICENSE("GPL"); -31MODULE_DESCRIPTION("Workqueue example");-+30MODULE_LICENSE("GPL"); +31MODULE_DESCRIPTION("Workqueue example");
0.15 Interrupt Handlers
-+
0.15.1 Interrupt Handlers
-Except for the last chapter, everything we did in the kernel so far we’ve done as a +
Except for the last chapter, everything we did in the kernel so far we have done as a response to a process asking for it, either by dealing with a special file, sending an -ioctl(), or issuing a system call. But the job of the kernel isn’t just to respond to +ioctl(), or issuing a system call. But the job of the kernel is not just to respond to process requests. Another job, which is every bit as important, is to speak to the hardware connected to the machine. -
There are two types of interaction between the CPU and the rest of the +
There are two types of interaction between the CPU and the rest of the computer’s hardware. The first type is when the CPU gives orders to the hardware, the other is when the hardware needs to tell the CPU something. The second, called interrupts, is much harder to implement because it has to be dealt with when convenient for the hardware, not the CPU. Hardware devices typically have a very -small amount of RAM, and if you don’t read their information when available, it is +small amount of RAM, and if you do not read their information when available, it is lost. -
Under Linux, hardware interrupts are called IRQ’s (Interrupt ReQuests). There +
Under Linux, hardware interrupts are called IRQ’s (Interrupt ReQuests). There are two types of IRQ’s, short and long. A short IRQ is one which is expected to take a very short period of time, during which the rest of the machine will be blocked and no other interrupts will be handled. A long IRQ is one which can take longer, and during which other interrupts may occur (but not interrupts from the same -device). If at all possible, it’s better to declare an interrupt handler to be +device). If at all possible, it is better to declare an interrupt handler to be long. -
When the CPU receives an interrupt, it stops whatever it’s doing (unless it’s +
When the CPU receives an interrupt, it stops whatever it is doing (unless it is processing a more important interrupt, in which case it will deal with this one only when the more important one is done), saves certain parameters on the stack and calls the interrupt handler. This means that certain things @@ -4329,156 +4304,156 @@ the new information at a later time (this is called the "bottom half") and return. The kernel is then guaranteed to call the bottom half as soon as possible – and when it does, everything allowed in kernel modules will be allowed. -
The way to implement this is to call request_irq() to get your interrupt handler +
The way to implement this is to call request_irq() to get your interrupt handler called when the relevant IRQ is received. -
In practice IRQ handling can be a bit more complex. Hardware is often +
In practice IRQ handling can be a bit more complex. Hardware is often designed in a way that chains two interrupt controllers, so that all the IRQs from interrupt controller B are cascaded to a certain IRQ from interrupt -controller A. Of course that requires that the kernel finds out which IRQ it +controller A. Of course, that requires that the kernel finds out which IRQ it really was afterwards and that adds overhead. Other architectures offer some special, very low overhead, so called "fast IRQ" or FIQs. To take advantage of -them requires handlers to be written in assembler, so they do not really fit -into the kernel. They can be made to work similar to the others, but after -that procedure, they’re no longer any faster than "common" IRQs. SMP -enabled kernels running on systems with more than one processor need to solve -another truckload of problems. It’s not enough to know if a certain IRQs -has happend, it’s also important for what CPU(s) it was for. People still -interested in more details, might want to do a web search for "APIC" now -;) -
This function receives the IRQ number, the name of the function, flags, a name -for /proc/interrupts and a parameter to pass to the interrupt handler. Usually +them requires handlers to be written in assembler, so they do not really +fit into the kernel. They can be made to work similar to the others, but +after that procedure, they are no longer any faster than "common" IRQs. +SMP enabled kernels running on systems with more than one processor +need to solve another truckload of problems. It is not enough to know if +a certain IRQs has happend, it’s also important for what CPU(s) it was +for. People still interested in more details, might want to refer to "APIC" +now. +
This function receives the IRQ number, the name of the function, flags, a name +for /proc/interrupts and a parameter to pass to the interrupt handler. Usually there is a certain number of IRQs available. How many IRQs there are is -hardware-dependent. The flags can include SA_SHIRQ to indicate you’re willing to +hardware-dependent. The flags can include SA_SHIRQ to indicate you are willing to share the IRQ with other interrupt handlers (usually because a number of hardware -devices sit on the same IRQ) and SA_INTERRUPT to indicate this is a fast -interrupt. This function will only succeed if there isn’t already a handler on this IRQ, -or if you’re both willing to share. +devices sit on the same IRQ) and SA_INTERRUPT to indicate this is a fast interrupt. +This function will only succeed if there is not already a handler on this IRQ, or if you +are both willing to share. -
+
0.15.2 Detecting button presses
-Many popular single board computers, such as Raspberry Pis or Beagleboards, have -a bunch of GPIO pins. Attaching buttons to those and then having a button press do -something is a classic case in which you might need to use interrupts so that instead +
Many popular single board computers, such as Raspberry Pi or Beagleboards, have a +bunch of GPIO pins. Attaching buttons to those and then having a button press do +something is a classic case in which you might need to use interrupts, so that instead of having the CPU waste time and battery power polling for a change in input state -it’s better for the input to trigger the CPU to then run a particular handling +it is better for the input to trigger the CPU to then run a particular handling function. -
Here’s an example where buttons are connected to GPIO numbers 17 and 18 and +
Here is an example where buttons are connected to GPIO numbers 17 and 18 and an LED is connected to GPIO 4. You can change those numbers to whatever is appropriate for your board.
-
1/* -2 * intrpt.c - Handling GPIO with interrupts -3 * -4 * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de) -5 * from: -6 * https://github.com/wendlers/rpi-kmod-samples -7 * -8 * Press one button to turn on a LED and another to turn it off -9 */ ++1/* +2 * intrpt.c - Handling GPIO with interrupts +3 * +4 * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de) +5 * from: +6 * https://github.com/wendlers/rpi-kmod-samples +7 * +8 * Press one button to turn on a LED and another to turn it off +9 */ 10 -11#include <linux/gpio.h> -12#include <linux/interrupt.h> -13#include <linux/kernel.h> -14#include <linux/module.h> +11#include <linux/gpio.h> +12#include <linux/interrupt.h> +13#include <linux/kernel.h> +14#include <linux/module.h> 15 -16static int button_irqs[] = {-1, -1}; +16static int button_irqs[] = {-1, -1}; 17 -18/* Define GPIOs for LEDs. -19 Change the numbers for the GPIO on your board. */ -20static struct gpio leds[] = {{4, GPIOF_OUT_INIT_LOW, "LED 1"}}; +18/* Define GPIOs for LEDs. +19 Change the numbers for the GPIO on your board. */ +20static struct gpio leds[] = {{4, GPIOF_OUT_INIT_LOW, "LED 1"}}; 21 -22/* Define GPIOs for BUTTONS -23 Change the numbers for the GPIO on your board. */ -24static struct gpio buttons[] = {{17, GPIOF_IN, "LED 1 ON BUTTON"}, -25 {18, GPIOF_IN, "LED 1 OFF BUTTON"}}; +22/* Define GPIOs for BUTTONS +23 Change the numbers for the GPIO on your board. */ +24static struct gpio buttons[] = {{17, GPIOF_IN, "LED 1 ON BUTTON"}, +25 {18, GPIOF_IN, "LED 1 OFF BUTTON"}}; 26 -27/* -28 * interrupt function triggered when a button is pressed -29 */ -30static irqreturn_t button_isr(int irq, void *data) +27/* +28 * interrupt function triggered when a button is pressed +29 */ +30static irqreturn_t button_isr(int irq, void *data) 31{ -32 /* first button */ -33 if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) +32 /* first button */ +33 if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) 34 gpio_set_value(leds[0].gpio, 1); -35 /* second button */ -36 else if (irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) +35 /* second button */ +36 else if (irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) 37 gpio_set_value(leds[0].gpio, 0); 38 -39 return IRQ_HANDLED; +39 return IRQ_HANDLED; 40} 41 -42int init_module() +42int init_module() 43{ -44 int ret = 0; +44 int ret = 0; 45 -46 pr_info("%s\n", __func__); +46 pr_info("%s\n", __func__); 47 -48 /* register LED gpios */ +48 /* register LED gpios */ 49 ret = gpio_request_array(leds, ARRAY_SIZE(leds)); 50 -51 if (ret) { -52 pr_err("Unable to request GPIOs for LEDs: %d\n", ret); -53 return ret; +51 if (ret) { +52 pr_err("Unable to request GPIOs for LEDs: %d\n", ret); +53 return ret; 54 } 55 -56 /* register BUTTON gpios */ +56 /* register BUTTON gpios */ 57 ret = gpio_request_array(buttons, ARRAY_SIZE(buttons)); 58 -59 if (ret) { -60 pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); -61 goto fail1; +59 if (ret) { +60 pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); +61 goto fail1; 62 } 63 -64 pr_info("Current button1 value: %d\n", gpio_get_value(buttons[0].gpio)); +64 pr_info("Current button1 value: %d\n", gpio_get_value(buttons[0].gpio)); 65 66 ret = gpio_to_irq(buttons[0].gpio); 67 -68 if (ret < 0) { -69 pr_err("Unable to request IRQ: %d\n", ret); -70 goto fail2; +68 if (ret < 0) { +69 pr_err("Unable to request IRQ: %d\n", ret); +70 goto fail2; 71 } 72 73 button_irqs[0] = ret; 74 -75 pr_info("Successfully requested BUTTON1 IRQ # %d\n", button_irqs[0]); +75 pr_info("Successfully requested BUTTON1 IRQ # %d\n", button_irqs[0]); 76 77 ret = request_irq(button_irqs[0], button_isr, 78 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, -79 "gpiomod#button1", NULL); +79 "gpiomod#button1", NULL); 80 -81 if (ret) { -82 pr_err("Unable to request IRQ: %d\n", ret); -83 goto fail2; +81 if (ret) { +82 pr_err("Unable to request IRQ: %d\n", ret); +83 goto fail2; 84 } 85 86 87 ret = gpio_to_irq(buttons[1].gpio); 88 -89 if (ret < 0) { -90 pr_err("Unable to request IRQ: %d\n", ret); -91 goto fail2; +89 if (ret < 0) { +90 pr_err("Unable to request IRQ: %d\n", ret); +91 goto fail2; 92 } 93 94 button_irqs[1] = ret; 95 -96 pr_info("Successfully requested BUTTON2 IRQ # %d\n", button_irqs[1]); +96 pr_info("Successfully requested BUTTON2 IRQ # %d\n", button_irqs[1]); 97 98 ret = request_irq(button_irqs[1], button_isr, 99 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, -100 "gpiomod#button2", NULL); +100 "gpiomod#button2", NULL); 101 -102 if (ret) { -103 pr_err("Unable to request IRQ: %d\n", ret); -104 goto fail3; +102 if (ret) { +103 pr_err("Unable to request IRQ: %d\n", ret); +104 goto fail3; 105 } 106 -107 return 0; +107 return 0; 108 -109/* cleanup what has been setup so far */ +109/* cleanup what has been setup so far */ 110fail3: 111 free_irq(button_irqs[0], NULL); 112 @@ -4488,164 +4463,164 @@ appropriate for your board. 116fail1: 117 gpio_free_array(leds, ARRAY_SIZE(leds)); 118 -119 return ret; +119 return ret; 120} 121 -122void cleanup_module() +122void cleanup_module() 123{ -124 int i; +124 int i; 125 -126 pr_info("%s\n", __func__); +126 pr_info("%s\n", __func__); 127 -128 /* free irqs */ +128 /* free irqs */ 129 free_irq(button_irqs[0], NULL); 130 free_irq(button_irqs[1], NULL); 131 -132 /* turn all LEDs off */ -133 for (i = 0; i < ARRAY_SIZE(leds); i++) +132 /* turn all LEDs off */ +133 for (i = 0; i < ARRAY_SIZE(leds); i++) 134 gpio_set_value(leds[i].gpio, 0); 135 -136 /* unregister */ +136 /* unregister */ 137 gpio_free_array(leds, ARRAY_SIZE(leds)); 138 gpio_free_array(buttons, ARRAY_SIZE(buttons)); 139} 140 -141MODULE_LICENSE("GPL"); -142MODULE_DESCRIPTION("Handle some GPIO interrupts");-+141MODULE_LICENSE("GPL"); +142MODULE_DESCRIPTION("Handle some GPIO interrupts");
0.15.3 Bottom Half
-Suppose you want to do a bunch of stuff inside of an interrupt routine. A common +
Suppose you want to do a bunch of stuff inside of an interrupt routine. A common way to do that without rendering the interrupt unavailable for a significant duration is to combine it with a tasklet. This pushes the bulk of the work off into the scheduler. -
The example below modifies the previous example to also run an additional task +
The example below modifies the previous example to also run an additional task when an interrupt is triggered.
-
1/* -2 * bottomhalf.c - Top and bottom half interrupt handling -3 * -4 * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de) -5 * from: -6 * https://github.com/wendlers/rpi-kmod-samples -7 * -8 * Press one button to turn on a LED and another to turn it off -9 */ ++1/* +2 * bottomhalf.c - Top and bottom half interrupt handling +3 * +4 * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de) +5 * from: +6 * https://github.com/wendlers/rpi-kmod-samples +7 * +8 * Press one button to turn on a LED and another to turn it off +9 */ 10 -11#include <linux/delay.h> -12#include <linux/gpio.h> -13#include <linux/interrupt.h> -14#include <linux/kernel.h> -15#include <linux/module.h> +11#include <linux/delay.h> +12#include <linux/gpio.h> +13#include <linux/interrupt.h> +14#include <linux/kernel.h> +15#include <linux/module.h> 16 -17static int button_irqs[] = {-1, -1}; +17static int button_irqs[] = {-1, -1}; 18 -19/* Define GPIOs for LEDs. -20 Change the numbers for the GPIO on your board. */ -21static struct gpio leds[] = {{4, GPIOF_OUT_INIT_LOW, "LED 1"}}; +19/* Define GPIOs for LEDs. +20 Change the numbers for the GPIO on your board. */ +21static struct gpio leds[] = {{4, GPIOF_OUT_INIT_LOW, "LED 1"}}; 22 -23/* Define GPIOs for BUTTONS -24 Change the numbers for the GPIO on your board. */ -25static struct gpio buttons[] = {{17, GPIOF_IN, "LED 1 ON BUTTON"}, -26 {18, GPIOF_IN, "LED 1 OFF BUTTON"}}; +23/* Define GPIOs for BUTTONS +24 Change the numbers for the GPIO on your board. */ +25static struct gpio buttons[] = {{17, GPIOF_IN, "LED 1 ON BUTTON"}, +26 {18, GPIOF_IN, "LED 1 OFF BUTTON"}}; 27 -28/* Tasklet containing some non-trivial amount of processing */ -29static void bottomhalf_tasklet_fn(unsigned long data) +28/* Tasklet containing some non-trivial amount of processing */ +29static void bottomhalf_tasklet_fn(unsigned long data) 30{ -31 pr_info("Bottom half tasklet starts\n"); -32 /* do something which takes a while */ +31 pr_info("Bottom half tasklet starts\n"); +32 /* do something which takes a while */ 33 mdelay(500); -34 pr_info("Bottom half tasklet ends\n"); +34 pr_info("Bottom half tasklet ends\n"); 35} 36 37DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L); 38 -39/* -40 * interrupt function triggered when a button is pressed -41 */ -42static irqreturn_t button_isr(int irq, void *data) +39/* +40 * interrupt function triggered when a button is pressed +41 */ +42static irqreturn_t button_isr(int irq, void *data) 43{ -44 /* Do something quickly right now */ -45 if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) +44 /* Do something quickly right now */ +45 if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) 46 gpio_set_value(leds[0].gpio, 1); -47 else if (irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) +47 else if (irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) 48 gpio_set_value(leds[0].gpio, 0); 49 -50 /* Do the rest at leisure via the scheduler */ +50 /* Do the rest at leisure via the scheduler */ 51 tasklet_schedule(&buttontask); 52 -53 return IRQ_HANDLED; +53 return IRQ_HANDLED; 54} 55 -56int init_module() +56int init_module() 57{ -58 int ret = 0; +58 int ret = 0; 59 -60 pr_info("%s\n", __func__); +60 pr_info("%s\n", __func__); 61 -62 /* register LED gpios */ +62 /* register LED gpios */ 63 ret = gpio_request_array(leds, ARRAY_SIZE(leds)); 64 -65 if (ret) { -66 pr_err("Unable to request GPIOs for LEDs: %d\n", ret); -67 return ret; +65 if (ret) { +66 pr_err("Unable to request GPIOs for LEDs: %d\n", ret); +67 return ret; 68 } 69 -70 /* register BUTTON gpios */ +70 /* register BUTTON gpios */ 71 ret = gpio_request_array(buttons, ARRAY_SIZE(buttons)); 72 -73 if (ret) { -74 pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); -75 goto fail1; +73 if (ret) { +74 pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); +75 goto fail1; 76 } 77 -78 pr_info("Current button1 value: %d\n", gpio_get_value(buttons[0].gpio)); +78 pr_info("Current button1 value: %d\n", gpio_get_value(buttons[0].gpio)); 79 80 ret = gpio_to_irq(buttons[0].gpio); 81 -82 if (ret < 0) { -83 pr_err("Unable to request IRQ: %d\n", ret); -84 goto fail2; +82 if (ret < 0) { +83 pr_err("Unable to request IRQ: %d\n", ret); +84 goto fail2; 85 } 86 87 button_irqs[0] = ret; 88 -89 pr_info("Successfully requested BUTTON1 IRQ # %d\n", button_irqs[0]); +89 pr_info("Successfully requested BUTTON1 IRQ # %d\n", button_irqs[0]); 90 91 ret = request_irq(button_irqs[0], button_isr, 92 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, -93 "gpiomod#button1", NULL); +93 "gpiomod#button1", NULL); 94 -95 if (ret) { -96 pr_err("Unable to request IRQ: %d\n", ret); -97 goto fail2; +95 if (ret) { +96 pr_err("Unable to request IRQ: %d\n", ret); +97 goto fail2; 98 } 99 100 101 ret = gpio_to_irq(buttons[1].gpio); 102 -103 if (ret < 0) { -104 pr_err("Unable to request IRQ: %d\n", ret); -105 goto fail2; +103 if (ret < 0) { +104 pr_err("Unable to request IRQ: %d\n", ret); +105 goto fail2; 106 } 107 108 button_irqs[1] = ret; 109 -110 pr_info("Successfully requested BUTTON2 IRQ # %d\n", button_irqs[1]); +110 pr_info("Successfully requested BUTTON2 IRQ # %d\n", button_irqs[1]); 111 112 ret = request_irq(button_irqs[1], button_isr, 113 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, -114 "gpiomod#button2", NULL); +114 "gpiomod#button2", NULL); 115 -116 if (ret) { -117 pr_err("Unable to request IRQ: %d\n", ret); -118 goto fail3; +116 if (ret) { +117 pr_err("Unable to request IRQ: %d\n", ret); +118 goto fail3; 119 } 120 -121 return 0; +121 return 0; 122 -123/* cleanup what has been setup so far */ +123/* cleanup what has been setup so far */ 124fail3: 125 free_irq(button_irqs[0], NULL); 126 @@ -4655,306 +4630,306 @@ when an interrupt is triggered. 130fail1: 131 gpio_free_array(leds, ARRAY_SIZE(leds)); 132 -133 return ret; +133 return ret; 134} 135 -136void cleanup_module() +136void cleanup_module() 137{ -138 int i; +138 int i; 139 -140 pr_info("%s\n", __func__); +140 pr_info("%s\n", __func__); 141 -142 /* free irqs */ +142 /* free irqs */ 143 free_irq(button_irqs[0], NULL); 144 free_irq(button_irqs[1], NULL); 145 -146 /* turn all LEDs off */ -147 for (i = 0; i < ARRAY_SIZE(leds); i++) +146 /* turn all LEDs off */ +147 for (i = 0; i < ARRAY_SIZE(leds); i++) 148 gpio_set_value(leds[i].gpio, 0); 149 -150 /* unregister */ +150 /* unregister */ 151 gpio_free_array(leds, ARRAY_SIZE(leds)); 152 gpio_free_array(buttons, ARRAY_SIZE(buttons)); 153} 154 -155MODULE_LICENSE("GPL"); -156MODULE_DESCRIPTION("Interrupt with top and bottom half");-+155MODULE_LICENSE("GPL"); +156MODULE_DESCRIPTION("Interrupt with top and bottom half");
0.16 Crypto
-At the dawn of the internet everybody trusted everybody completely…but that didn’t -work out so well. When this guide was originally written it was a more innocent era -in which almost nobody actually gave a damn about crypto - least of all kernel -developers. That’s certainly no longer the case now. To handle crypto stuff the kernel -has its own API enabling common methods of encryption, decryption and your +
At the dawn of the internet everybody trusted everybody completely…but that did +not work out so well. When this guide was originally written it was a more innocent +era in which almost nobody actually gave a damn about crypto - least of all kernel +developers. That is certainly no longer the case now. To handle crypto stuff the +kernel has its own API enabling common methods of encryption, decryption and your favourite hash functions. -
+
0.16.1 Hash functions
-Calculating and checking the hashes of things is a common operation. Here is a +
Calculating and checking the hashes of things is a common operation. Here is a demonstration of how to calculate a sha256 hash within a kernel module.
-
1/* -2 * cryptosha256.c -3 */ -4#include <crypto/internal/hash.h> -5#include <linux/module.h> ++1/* +2 * cryptosha256.c +3 */ +4#include <crypto/internal/hash.h> +5#include <linux/module.h> 6 -7#define SHA256_LENGTH 32 +7#define SHA256_LENGTH 32 8 -9static void show_hash_result(char *plaintext, char *hash_sha256) +9static void show_hash_result(char *plaintext, char *hash_sha256) 10{ -11 int i; -12 char str[SHA256_LENGTH * 2 + 1]; +11 int i; +12 char str[SHA256_LENGTH * 2 + 1]; 13 -14 pr_info("sha256 test for string: \"%s\"\n", plaintext); -15 for (i = 0; i < SHA256_LENGTH; i++) -16 sprintf(&str[i * 2], "%02x", (unsigned char) hash_sha256[i]); +14 pr_info("sha256 test for string: \"%s\"\n", plaintext); +15 for (i = 0; i < SHA256_LENGTH; i++) +16 sprintf(&str[i * 2], "%02x", (unsigned char) hash_sha256[i]); 17 str[i * 2] = 0; -18 pr_info("%s\n", str); +18 pr_info("%s\n", str); 19} 20 -21int cryptosha256_init(void) +21int cryptosha256_init(void) 22{ -23 char *plaintext = "This is a test"; -24 char hash_sha256[SHA256_LENGTH]; -25 struct crypto_shash *sha256; -26 struct shash_desc *shash; +23 char *plaintext = "This is a test"; +24 char hash_sha256[SHA256_LENGTH]; +25 struct crypto_shash *sha256; +26 struct shash_desc *shash; 27 -28 sha256 = crypto_alloc_shash("sha256", 0, 0); -29 if (IS_ERR(sha256)) -30 return -1; +28 sha256 = crypto_alloc_shash("sha256", 0, 0); +29 if (IS_ERR(sha256)) +30 return -1; 31 -32 shash = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(sha256), +32 shash = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(sha256), 33 GFP_KERNEL); -34 if (!shash) -35 return -ENOMEM; +34 if (!shash) +35 return -ENOMEM; 36 37 shash->tfm = sha256; 38 -39 if (crypto_shash_init(shash)) -40 return -1; +39 if (crypto_shash_init(shash)) +40 return -1; 41 -42 if (crypto_shash_update(shash, plaintext, strlen(plaintext))) -43 return -1; +42 if (crypto_shash_update(shash, plaintext, strlen(plaintext))) +43 return -1; 44 -45 if (crypto_shash_final(shash, hash_sha256)) -46 return -1; +45 if (crypto_shash_final(shash, hash_sha256)) +46 return -1; 47 48 kfree(shash); 49 crypto_free_shash(sha256); 50 51 show_hash_result(plaintext, hash_sha256); 52 -53 return 0; +53 return 0; 54} 55 -56void cryptosha256_exit(void) {} +56void cryptosha256_exit(void) {} 57 58module_init(cryptosha256_init); 59module_exit(cryptosha256_exit); 60 -61MODULE_DESCRIPTION("sha256 hash test"); -62MODULE_LICENSE("GPL");-Make and install the module: +61MODULE_DESCRIPTION("sha256 hash test"); +62MODULE_LICENSE("GPL");
Make and install the module:
1make 2sudo insmod cryptosha256.ko 3dmesg-And you should see that the hash was calculated for the test string. -
Finally, remove the test module: +
And you should see that the hash was calculated for the test string. +
Finally, remove the test module:
1sudo rmmod cryptosha256-+
0.16.2 Symmetric key encryption
-Here is an example of symmetrically encrypting a string using the AES algorithm +
Here is an example of symmetrically encrypting a string using the AES algorithm and a password.
-
1/* -2 * cryptosk.c -3 */ -4#include <crypto/internal/skcipher.h> -5#include <linux/crypto.h> -6#include <linux/module.h> ++1/* +2 * cryptosk.c +3 */ +4#include <crypto/internal/skcipher.h> +5#include <linux/crypto.h> +6#include <linux/module.h> 7 -8#define SYMMETRIC_KEY_LENGTH 32 -9#define CIPHER_BLOCK_SIZE 16 +8#define SYMMETRIC_KEY_LENGTH 32 +9#define CIPHER_BLOCK_SIZE 16 10 -11struct tcrypt_result { -12 struct completion completion; -13 int err; +11struct tcrypt_result { +12 struct completion completion; +13 int err; 14}; 15 -16struct skcipher_def { -17 struct scatterlist sg; -18 struct crypto_skcipher *tfm; -19 struct skcipher_request *req; -20 struct tcrypt_result result; -21 char *scratchpad; -22 char *ciphertext; -23 char *ivdata; +16struct skcipher_def { +17 struct scatterlist sg; +18 struct crypto_skcipher *tfm; +19 struct skcipher_request *req; +20 struct tcrypt_result result; +21 char *scratchpad; +22 char *ciphertext; +23 char *ivdata; 24}; 25 -26static struct skcipher_def sk; +26static struct skcipher_def sk; 27 -28static void test_skcipher_finish(struct skcipher_def *sk) +28static void test_skcipher_finish(struct skcipher_def *sk) 29{ -30 if (sk->tfm) +30 if (sk->tfm) 31 crypto_free_skcipher(sk->tfm); -32 if (sk->req) +32 if (sk->req) 33 skcipher_request_free(sk->req); -34 if (sk->ivdata) +34 if (sk->ivdata) 35 kfree(sk->ivdata); -36 if (sk->scratchpad) +36 if (sk->scratchpad) 37 kfree(sk->scratchpad); -38 if (sk->ciphertext) +38 if (sk->ciphertext) 39 kfree(sk->ciphertext); 40} 41 -42static int test_skcipher_result(struct skcipher_def *sk, int rc) +42static int test_skcipher_result(struct skcipher_def *sk, int rc) 43{ -44 switch (rc) { -45 case 0: -46 break; -47 case -EINPROGRESS || -EBUSY: +44 switch (rc) { +45 case 0: +46 break; +47 case -EINPROGRESS || -EBUSY: 48 rc = wait_for_completion_interruptible(&sk->result.completion); -49 if (!rc && !sk->result.err) { +49 if (!rc && !sk->result.err) { 50 reinit_completion(&sk->result.completion); -51 break; +51 break; 52 } -53 pr_info("skcipher encrypt returned with %d result %d\n", rc, +53 pr_info("skcipher encrypt returned with %d result %d\n", rc, 54 sk->result.err); -55 break; -56 default: -57 pr_info("skcipher encrypt returned with %d result %d\n", rc, +55 break; +56 default: +57 pr_info("skcipher encrypt returned with %d result %d\n", rc, 58 sk->result.err); -59 break; +59 break; 60 } 61 62 init_completion(&sk->result.completion); 63 -64 return rc; +64 return rc; 65} 66 -67static void test_skcipher_callback(struct crypto_async_request *req, int error) +67static void test_skcipher_callback(struct crypto_async_request *req, int error) 68{ -69 struct tcrypt_result *result = req->data; -70 /* int ret; */ +69 struct tcrypt_result *result = req->data; +70 /* int ret; */ 71 -72 if (error == -EINPROGRESS) -73 return; +72 if (error == -EINPROGRESS) +73 return; 74 75 result->err = error; 76 complete(&result->completion); -77 pr_info("Encryption finished successfully\n"); +77 pr_info("Encryption finished successfully\n"); 78 -79 /* decrypt data */ -80 /* -81 memset((void*)sk.scratchpad, '-', CIPHER_BLOCK_SIZE); -82 ret = crypto_skcipher_decrypt(sk.req); -83 ret = test_skcipher_result(&sk, ret); -84 if (ret) -85 return; +79 /* decrypt data */ +80 /* +81 memset((void*)sk.scratchpad, '-', CIPHER_BLOCK_SIZE); +82 ret = crypto_skcipher_decrypt(sk.req); +83 ret = test_skcipher_result(&sk, ret); +84 if (ret) +85 return; 86 -87 sg_copy_from_buffer(&sk.sg, 1, sk.scratchpad, CIPHER_BLOCK_SIZE); -88 sk.scratchpad[CIPHER_BLOCK_SIZE-1] = 0; +87 sg_copy_from_buffer(&sk.sg, 1, sk.scratchpad, CIPHER_BLOCK_SIZE); +88 sk.scratchpad[CIPHER_BLOCK_SIZE-1] = 0; 89 -90 pr_info("Decryption request successful\n"); -91 pr_info("Decrypted: %s\n", sk.scratchpad); -92 */ +90 pr_info("Decryption request successful\n"); +91 pr_info("Decrypted: %s\n", sk.scratchpad); +92 */ 93} 94 -95static int test_skcipher_encrypt(char *plaintext, -96 char *password, -97 struct skcipher_def *sk) +95static int test_skcipher_encrypt(char *plaintext, +96 char *password, +97 struct skcipher_def *sk) 98{ -99 int ret = -EFAULT; -100 unsigned char key[SYMMETRIC_KEY_LENGTH]; +99 int ret = -EFAULT; +100 unsigned char key[SYMMETRIC_KEY_LENGTH]; 101 -102 if (!sk->tfm) { -103 sk->tfm = crypto_alloc_skcipher("cbc-aes-aesni", 0, 0); -104 if (IS_ERR(sk->tfm)) { -105 pr_info("could not allocate skcipher handle\n"); -106 return PTR_ERR(sk->tfm); +102 if (!sk->tfm) { +103 sk->tfm = crypto_alloc_skcipher("cbc-aes-aesni", 0, 0); +104 if (IS_ERR(sk->tfm)) { +105 pr_info("could not allocate skcipher handle\n"); +106 return PTR_ERR(sk->tfm); 107 } 108 } 109 -110 if (!sk->req) { +110 if (!sk->req) { 111 sk->req = skcipher_request_alloc(sk->tfm, GFP_KERNEL); -112 if (!sk->req) { -113 pr_info("could not allocate skcipher request\n"); +112 if (!sk->req) { +113 pr_info("could not allocate skcipher request\n"); 114 ret = -ENOMEM; -115 goto out; +115 goto out; 116 } 117 } 118 119 skcipher_request_set_callback(sk->req, CRYPTO_TFM_REQ_MAY_BACKLOG, 120 test_skcipher_callback, &sk->result); 121 -122 /* clear the key */ -123 memset((void *) key, '\0', SYMMETRIC_KEY_LENGTH); +122 /* clear the key */ +123 memset((void *) key, '\0', SYMMETRIC_KEY_LENGTH); 124 -125 /* Use the world's favourite password */ -126 sprintf((char *) key, "%s", password); +125 /* Use the world's favourite password */ +126 sprintf((char *) key, "%s", password); 127 -128 /* AES 256 with given symmetric key */ -129 if (crypto_skcipher_setkey(sk->tfm, key, SYMMETRIC_KEY_LENGTH)) { -130 pr_info("key could not be set\n"); +128 /* AES 256 with given symmetric key */ +129 if (crypto_skcipher_setkey(sk->tfm, key, SYMMETRIC_KEY_LENGTH)) { +130 pr_info("key could not be set\n"); 131 ret = -EAGAIN; -132 goto out; +132 goto out; 133 } -134 pr_info("Symmetric key: %s\n", key); -135 pr_info("Plaintext: %s\n", plaintext); +134 pr_info("Symmetric key: %s\n", key); +135 pr_info("Plaintext: %s\n", plaintext); 136 -137 if (!sk->ivdata) { -138 /* see https://en.wikipedia.org/wiki/Initialization_vector */ +137 if (!sk->ivdata) { +138 /* see https://en.wikipedia.org/wiki/Initialization_vector */ 139 sk->ivdata = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL); -140 if (!sk->ivdata) { -141 pr_info("could not allocate ivdata\n"); -142 goto out; +140 if (!sk->ivdata) { +141 pr_info("could not allocate ivdata\n"); +142 goto out; 143 } 144 get_random_bytes(sk->ivdata, CIPHER_BLOCK_SIZE); 145 } 146 -147 if (!sk->scratchpad) { -148 /* The text to be encrypted */ +147 if (!sk->scratchpad) { +148 /* The text to be encrypted */ 149 sk->scratchpad = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL); -150 if (!sk->scratchpad) { -151 pr_info("could not allocate scratchpad\n"); -152 goto out; +150 if (!sk->scratchpad) { +151 pr_info("could not allocate scratchpad\n"); +152 goto out; 153 } 154 } -155 sprintf((char *) sk->scratchpad, "%s", plaintext); +155 sprintf((char *) sk->scratchpad, "%s", plaintext); 156 157 sg_init_one(&sk->sg, sk->scratchpad, CIPHER_BLOCK_SIZE); 158 skcipher_request_set_crypt(sk->req, &sk->sg, &sk->sg, CIPHER_BLOCK_SIZE, 159 sk->ivdata); 160 init_completion(&sk->result.completion); 161 -162 /* encrypt data */ +162 /* encrypt data */ 163 ret = crypto_skcipher_encrypt(sk->req); 164 ret = test_skcipher_result(sk, ret); -165 if (ret) -166 goto out; +165 if (ret) +166 goto out; 167 -168 pr_info("Encryption request successful\n"); +168 pr_info("Encryption request successful\n"); 169 170out: -171 return ret; +171 return ret; 172} 173 -174int cryptoapi_init(void) +174int cryptoapi_init(void) 175{ -176 /* The world's favorite password */ -177 char *password = "password123"; +176 /* The world's favorite password */ +177 char *password = "password123"; 178 179 sk.tfm = NULL; 180 sk.req = NULL; @@ -4962,11 +4937,11 @@ and a password. 182 sk.ciphertext = NULL; 183 sk.ivdata = NULL; 184 -185 test_skcipher_encrypt("Testing", password, &sk); -186 return 0; +185 test_skcipher_encrypt("Testing", password, &sk); +186 return 0; 187} 188 -189void cryptoapi_exit(void) +189void cryptoapi_exit(void) 190{ 191 test_skcipher_finish(&sk); 192} @@ -4974,72 +4949,72 @@ and a password. 194module_init(cryptoapi_init); 195module_exit(cryptoapi_exit); 196 -197MODULE_DESCRIPTION("Symmetric key encryption example"); -198MODULE_LICENSE("GPL");-+197MODULE_DESCRIPTION("Symmetric key encryption example"); +198MODULE_LICENSE("GPL");
-
0.17 Standardising the interfaces: The Device Model
-Up to this point we’ve seen all kinds of modules doing all kinds of things, but there +
0.17 Standardizing the interfaces: The Device Model
+Up to this point we have seen all kinds of modules doing all kinds of things, but there was no consistency in their interfaces with the rest of the kernel. To impose some -consistency such that there is at minimum a standardised way to start, suspend and +consistency such that there is at minimum a standardized way to start, suspend and resume a device a device model was added. An example is show below, and you can use this as a template to add your own suspend, resume or other interface functions.
-
1/* -2 * devicemodel.c -3 */ -4#include <linux/kernel.h> -5#include <linux/module.h> -6#include <linux/platform_device.h> +1/* +2 * devicemodel.c +3 */ +4#include <linux/kernel.h> +5#include <linux/module.h> +6#include <linux/platform_device.h> 7 -8struct devicemodel_data { -9 char *greeting; -10 int number; +8struct devicemodel_data { +9 char *greeting; +10 int number; 11}; 12 -13static int devicemodel_probe(struct platform_device *dev) +13static int devicemodel_probe(struct platform_device *dev) 14{ -15 struct devicemodel_data *pd = -16 (struct devicemodel_data *) (dev->dev.platform_data); +15 struct devicemodel_data *pd = +16 (struct devicemodel_data *) (dev->dev.platform_data); 17 -18 pr_info("devicemodel probe\n"); -19 pr_info("devicemodel greeting: %s; %d\n", pd->greeting, pd->number); +18 pr_info("devicemodel probe\n"); +19 pr_info("devicemodel greeting: %s; %d\n", pd->greeting, pd->number); 20 -21 /* Your device initialisation code */ +21 /* Your device initialization code */ 22 -23 return 0; +23 return 0; 24} 25 -26static int devicemodel_remove(struct platform_device *dev) +26static int devicemodel_remove(struct platform_device *dev) 27{ -28 pr_info("devicemodel example removed\n"); +28 pr_info("devicemodel example removed\n"); 29 -30 /* Your device removal code */ +30 /* Your device removal code */ 31 -32 return 0; +32 return 0; 33} 34 -35static int devicemodel_suspend(struct device *dev) +35static int devicemodel_suspend(struct device *dev) 36{ -37 pr_info("devicemodel example suspend\n"); +37 pr_info("devicemodel example suspend\n"); 38 -39 /* Your device suspend code */ +39 /* Your device suspend code */ 40 -41 return 0; +41 return 0; 42} 43 -44static int devicemodel_resume(struct device *dev) +44static int devicemodel_resume(struct device *dev) 45{ -46 pr_info("devicemodel example resume\n"); +46 pr_info("devicemodel example resume\n"); 47 -48 /* Your device resume code */ +48 /* Your device resume code */ 49 -50 return 0; +50 return 0; 51} 52 -53static const struct dev_pm_ops devicemodel_pm_ops = { +53static const struct dev_pm_ops devicemodel_pm_ops = { 54 .suspend = devicemodel_suspend, 55 .resume = devicemodel_resume, 56 .poweroff = devicemodel_suspend, @@ -5048,10 +5023,10 @@ functions. 59 .restore = devicemodel_resume, 60}; 61 -62static struct platform_driver devicemodel_driver = { +62static struct platform_driver devicemodel_driver = { 63 .driver = 64 { -65 .name = "devicemodel_example", +65 .name = "devicemodel_example", 66 .owner = THIS_MODULE, 67 .pm = &devicemodel_pm_ops, 68 }, @@ -5059,116 +5034,116 @@ functions. 70 .remove = devicemodel_remove, 71}; 72 -73static int devicemodel_init(void) +73static int devicemodel_init(void) 74{ -75 int ret; +75 int ret; 76 -77 pr_info("devicemodel init\n"); +77 pr_info("devicemodel init\n"); 78 79 ret = platform_driver_register(&devicemodel_driver); 80 -81 if (ret) { -82 pr_err("Unable to register driver\n"); -83 return ret; +81 if (ret) { +82 pr_err("Unable to register driver\n"); +83 return ret; 84 } 85 -86 return 0; +86 return 0; 87} 88 -89static void devicemodel_exit(void) +89static void devicemodel_exit(void) 90{ -91 pr_info("devicemodel exit\n"); +91 pr_info("devicemodel exit\n"); 92 platform_driver_unregister(&devicemodel_driver); 93} 94 -95MODULE_LICENSE("GPL"); -96MODULE_DESCRIPTION("Linux Device Model example"); +95MODULE_LICENSE("GPL"); +96MODULE_DESCRIPTION("Linux Device Model example"); 97 98module_init(devicemodel_init); 99module_exit(devicemodel_exit);-+
0.18 Optimizations
-+
0.18.1 Likely and Unlikely conditions
-Sometimes you might want your code to run as quickly as possible, especially if +
Sometimes you might want your code to run as quickly as possible, especially if it’s handling an interrupt or doing something which might cause noticible latency. If your code contains boolean conditions and if you know that the conditions are almost always likely to evaluate as either true or false, then you can allow the compiler to optimise for this using the likely and unlikely macros. -
For example, when allocating memory you’re almost always expecting this to +
For example, when allocating memory you’re almost always expecting this to succeed.
1bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx); -2if (unlikely(!bvl)) { +2if (unlikely(!bvl)) { 3 mempool_free(bio, bio_pool); 4 bio = NULL; -5 goto out; +5 goto out; 6}-When the unlikely macro is used the compiler alters its machine instruction +
When the unlikely macro is used the compiler alters its machine instruction output so that it continues along the false branch and only jumps if the condition is true. That avoids flushing the processor pipeline. The opposite happens if you use the likely macro.
0.19 Common Pitfalls
-Before I send you on your way to go out into the world and write kernel modules, +
Before I send you on your way to go out into the world and write kernel modules, there are a few things I need to warn you about. If I fail to warn you and something bad happens, please report the problem to me for a full refund of the amount I was paid for your copy of the book. -
+
0.19.1 Using standard libraries
-You can’t do that. In a kernel module you can only use kernel functions, which are +
You can’t do that. In a kernel module you can only use kernel functions, which are the functions you can see in /proc/kallsyms. -
+
0.19.2 Disabling interrupts
-You might need to do this for a short time and that is OK, but if you don’t +
You might need to do this for a short time and that is OK, but if you don’t enable them afterwards, your system will be stuck and you’ll have to power it off. -
+
0.19.3 Sticking your head inside a large carnivore
-I probably don’t have to warn you about this, but I figured I will anyway, just in +
I probably don’t have to warn you about this, but I figured I will anyway, just in case. -
+
0.20 Where To Go From Here?
-I could easily have squeezed a few more chapters into this book. I could have added a +
I could easily have squeezed a few more chapters into this book. I could have added a chapter about creating new file systems, or about adding new protocol stacks (as if there’s a need for that – you’d have to dig underground to find a protocol stack not supported by Linux). I could have added explanations of the kernel mechanisms we haven’t touched upon, such as bootstrapping or the disk interface. -
However, I chose not to. My purpose in writing this book was to provide initiation +
However, I chose not to. My purpose in writing this book was to provide initiation into the mysteries of kernel module programming and to teach the common techniques for that purpose. For people seriously interested in kernel programming, I recommend kernelnewbies.org and the Documentation subdirectory within the kernel source code which isn’t always easy to understand but can be a starting point for further investigation. Also, as Linus said, the best way to learn the kernel is to read the source code yourself. -
If you’re interested in more examples of short kernel modules then searching on +
If you’re interested in more examples of short kernel modules then searching on sites such as Github and Gitlab is a good way to start, although there is a lot of duplication of older LKMPG examples which may not compile with newer kernel versions. You will also be able to find examples of the use of kernel modules to attack or compromise systems or exfiltrate data and those can be useful for thinking about how to defend systems and learning about existing security mechanisms within the kernel. -
I hope I have helped you in your quest to become a better programmer, or at +
I hope I have helped you in your quest to become a better programmer, or at least to have fun through technology. And, if you do write useful kernel modules, I hope you publish them under the GPL, so I can use them too. -
If you’d like to contribute to this guide or notice anything glaringly wrong, please +
If you’d like to contribute to this guide or notice anything glaringly wrong, please create an issue at https://github.com/sysprog21/lkmpg. -
Happy hacking. +
Happy hacking.