11. Device Drivers

  • A device driver or software driver is a computer program allowing higher- level computer programs to interact with a hardware device.
  • Translator between a hardware device and the applications or operating systems
  • Drivers are hardware-dependent and operating-system-specific.
  • They usually provide the interrupt handling required for any necessary asynchronous time-dependent

11.1. Device Drivers Types

  • Character Device Drivers
  • Operate on characters as basic unit of input and output
  • Accessed in sequential and non-random manner
  • Block Device Driver
  • Serves blocks of data
  • Random access as required by file systems

11.1.1. copy_to_user(), copy_from_user()

  • Macros to copy data from user space and copy data to kernel space.

11.1.2. Character Device driver and ioctls

11.1.2.1. file: chardev.c

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
 *  <PD> Creates a read-only char device that says how many times
 *  you've read from the dev file </PD>
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <asm/uaccess.h>   /* for put_user */

struct param {
   int number;
   char *ptr[];
};
/*  
 *  Prototypes - this would normally go in a .h file
 */
int init_module(void);
void cleanup_module(void);
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t,\
						loff_t *);
static long device_ioctl(struct file *, unsigned int,
         unsigned long);

static long unlocked_device_ioctl(struct file *, unsigned int,
         unsigned long);
#define SUCCESS 0
#define DEVICE_NAME "sav_dev" /* Dev name as it appears in 
                                 /proc/devices*/
#define BUF_LEN 80   /* Max length of the message from the device */

/* 
 * Global variables are declared as static, 
 * so are global within the file. 
 */

static int Major;    /* Major number assigned to our device driver */
static int Device_Open = 0;   /* Is device open?  
             * Used to prevent multiple access to device */
static char msg[BUF_LEN]; /* The msg the device will give when asked*/
static char *msg_Ptr;

static struct file_operations fops = {
   .read = device_read,
   .write = device_write,
   .open = device_open,
   .release = device_release,
   .compat_ioctl = device_ioctl,
   .unlocked_ioctl = unlocked_device_ioctl

};

/*
 * This function is called when the module is loaded
 */
int init_module(void)
{
   Major = register_chrdev(0, DEVICE_NAME, &fops);

   if (Major < 0) {
      printk(KERN_ALERT "Registering char device failed with %d\n",\
             Major);
      return Major;
   }

   printk(KERN_INFO "I got major number %d. To talk to\n", Major);
   printk(KERN_INFO "the driver, create a dev file with\n");
   printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, Major);
   printk(KERN_INFO "Try various minor numbers, Try to cat and \
			echo to the device file\n");
   printk(KERN_INFO "Remove the device file and module when done.\n");

   return SUCCESS;
}

/*
 * This function is called when the module is unloaded
 */
void cleanup_module(void)
{
   /* 
    * Unregister the device 
    */

   printk(KERN_INFO "\n\nUnregistering the device file.\n");
   unregister_chrdev(Major, DEVICE_NAME);
}

/*
 * Methods
 */

/* 
 * Called when a process tries to open the device file, like
 * "cat /dev/mycharfile"
 */
static int device_open(struct inode *inode, struct file *file)
{
   static int counter = 0;

   if (Device_Open)
      return -EBUSY;

   Device_Open++;
   sprintf(msg, "I already told you %d times Hello world!\n", 
                                    counter++);
   msg_Ptr = msg;
   try_module_get(THIS_MODULE);

   return SUCCESS;
}

/* 
 * Called when a process closes the device file.
 */
static int device_release(struct inode *inode, struct file *file)
{
   Device_Open--;    /* We're now ready for our next caller */

   /* 
    * Decrement the usage count, or else once you opened the file, 
    * you'll
    * never get get rid of the module. 
    */
   module_put(THIS_MODULE);

   return 0;
}

/* 
 * Called when a process, which already opened the dev file, attempts 
   to read from it.  */
static ssize_t device_read(struct file *filp, /* see include/linux/fs.h   */
            char *buffer,  /* buffer to fill with data */
            size_t length, /* length of the buffer     */
            loff_t * offset)
{
   /*
    * Number of bytes actually written to the buffer 
    */
   int bytes_read = 0;

   /*
    * If we're at the end of the message, 
    * return 0 signifying end of file 
    */
   if (*msg_Ptr == 0)
      return 0;

   /* 
    * Actually put the data into the buffer 
    */
   while (length && *msg_Ptr) {

      /* 
       * The buffer is in the user data segment, not the kernel 
       * segment so "*" assignment won't work.  We have to use 
       * put_user which copies data from the kernel data segment to
       * the user data segment. 
       */
      put_user(*(msg_Ptr++), buffer++);

      length--;
      bytes_read++;
   }

   /* 
    * Most read functions return the number of bytes put into the buffer
    */
   return bytes_read;
}

/*  
 * Called when a process writes to dev file: echo "hi" > /dev/hello 
 */
static ssize_t
device_write(struct file *filp, const char *buff, size_t len, loff_t * off)
{
   printk(KERN_ALERT "Sorry, this operation isn't supported.\n");
   return -EINVAL;
}

static long device_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
	printk(KERN_INFO "In unlocked ioctl\n");
        return 0;
}

static long unlocked_device_ioctl( struct file *file, unsigned int cmd, unsigned long arg)
{
   int numbers, i;
   printk(KERN_INFO "Command Passed is %d", cmd);

   switch (cmd) {
   case 1:
      printk(KERN_INFO "I AM IN COMMAND NUMBER 1");
      numbers = ((struct param *)arg)->number;
      printk(KERN_INFO "Number Passed %d", ((struct param *)arg)->number);
      for (i = 0; i < numbers; i++) {
         printk(KERN_INFO "ARG 1 %s", ((struct param *)arg)->ptr[i]);
      }
      printk(KERN_INFO "I will try to print the values passed to me");
      return 0;
   case 2:
      printk(KERN_INFO "I AM IN COMMAND NUMBER 1");
      printk(KERN_INFO " HEY ITS DONE");
      return 0;

   default:
      printk(KERN_INFO "Unsupported command. Command is %d", cmd);
      return -1;
   }
   return 0;
}

11.1.2.2. file: Makefile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Makefile to compile chardev.c
# Also this Makefile is used to learn writing Makefiles

CC = gcc

# We have two types of kernel code.
# 1. Which are staticly compiled in the kernel.
# 	For this type we use the string "obj-y". Note the "y" used here.
# 2. Which gets compiled as a module.
# 	For this type we use the string "obj-m". Note the "m" used here.
# So we basically use variables here to specify the value "y" or "m".
# I am using variacle CONFIG_CHARDEV to specify it.
# 
CONFIG_CHARDEV = m
MODULE_NAME = chardev
obj-m += chardev.o
#obj-m += chardev.o
#obj-$(CONFIG_CHARDEV) += chardev.o

# obj-m += chardev.o


all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
	ctags -R

clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
	rm -rf tags

11.1.2.3. file: ioctl.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>

#define DEV_NAME_LENGTH 20

struct param {
    int number;
    char **ptr;
};

int main(int argc, char *argv[])
{
    int i;
    char dev_name[DEV_NAME_LENGTH];
    struct param ioctl_params;
    int fd, retval;
    printf("\n\nNumber of arguements passed %d", argc);

    for (i = 0; i < argc; i++) {
        printf("\nARG %d is %s", i, argv[i]);
    }

    if (argc < 4) {
        printf("\n\n Number of arguements is very less");
        printf("\n\n argc 1 should be device name");
        printf("\n\n argc 2 should be the ioctl number");
        printf("\n\n argc 3 onwards should be all the arguements");
        goto exit;
    } else {
        printf("\n\n Number of arguements is fine .... proceeding");
    }
    /* argc 1 should be device name */
    /* argc 2 should be the ioctl number */
    /* argc 3 onwards should be all the arguements */
    /* Asumming that the parameters are correct */
    ioctl_params.number = argc - 3;
    ioctl_params.ptr = argv[3];

    printf("\nXXXX ARG %d is %s", i, ioctl_params.ptr);
    /* Substract from a single digit number to get the correct digit */
    int ioctl_number = argv[2][0] - 48;

    printf("\n\nioctl number is %d", ioctl_number);

    strcpy(dev_name, argv[1]);
    fd = open(dev_name, O_RDWR);

    /* complain if the open failed */
    if (fd == -1) {
        printf("Error in opening the device %s", dev_name);
        return 1;
    } else {
        printf("\n\nOpened the device file .... proceeding");
    }

    /* Call the ioctl */
    printf("\n\nCalling the ioctl, lets see what happens");
    retval = ioctl(fd, ioctl_number, &ioctl_params);
    if (retval == -1) {
        perror("ioctl : ");
        printf("\n\nIOCTL Failed boss");
    } else {
        printf("\n\nWorks fine");
    }

 exit:
    return 0;
}

11.1.2.4. Steps:

  • insmod chardev.ko
  • cat /proc/devices | grep sav_dev - to get the major number of the device, for example 250.
  • mknod  /dev/mydev c 250 0
  • ls -l /dev/mydev