Linux Kernel Driver Module writing overview-ioctl, class_create, device_create

Source: Internet
Author: User

If you have no idea about the kernel driver module, first learn the basic knowledge of the kernel driver module.

If you have already started the kernel driver module, but still feel a bit fuzzy, you cannot understand the structure of a kernel driver module as a whole. Please read this article.

If you have been engaged in kernel module programming for N years and are advanced in the field, please do not hesitate to give us any omissions or errors in this article.

 

In this article, I will implement a simple Linux character device, which aims to outline the outline of the compiling method of the Linux kernel module. This section focuses on the use of IOCTL.

I name this simple Linux character device module hello_mod.

The device type is hello_class.

Device Name: Hello

 

This device is a virtual device. When a module is loaded, a logical device named hello_class is created in/sys/class/, and a hello physical device file is created in/dev. The module name is hello_mod. It can accept the input string data (the length is less than 128). After processing the input string, the module can output the string externally. The IOCTL () function can be used to internally process strings.

For example:

A. Write "Tom" using the write function and set langtype = Chinese using the ioctl function. The data read through the READ function will be "Hello! Tom/N"

B. Write "Tom" using the write function and set langtype = English using the ioctl function. The data read through the READ function will be "Hello! Tom/N"

C. Write "Tom" through the write function and set langtype = pinyin through the ioctl function. The data read through the READ function will be "Ni hao! Tom/N"

 

 

Generally, the kernel module is not responsible for creating device categories and nodes. O or. ko file. Then, after insmod, mknod is required to create the corresponding file. In this simple example, the driver module is responsible for automatically creating the device category and file during loading. This function has two steps,

1) create a device category file class_create ();

2) Create the device file device_create ();

For more information about how to use these two functions, see.

 

Compared with windows programming, writing a Linux device driver is easier to understand. Because you do not need to process IRPs, the association between application-layer functions and kernel functions is easy to understand.

For example, when the application-layer function calls the open () function to my device, the application-layer function will call the custom open () function in my device, how to write this function,

The function name I defined in my device is hello_mod_open. Note that the function name can be defined at will, but the function signature must comply with kernel requirements, for more information about the definition, see <Linux/Fs. h>

 

Static int hello_mod_open (struct inode *, struct file *);

 

In this way, the open function in the kernel is defined, which only needs to be associated with our own modules. This requires a structure.

 

Struct file_operations

 

The members in this structure are pointers corresponding to various functions operated by the device.

These functions are defined as follows in the device. Note that the syntax below is not the standard ansi c syntax, but the GNU extension syntax.

 

Struct file_operations hello_mod_fops =
{
. Owner = this_module,
. Open = hello_mod_open,
. Read = hello_mod_read,
. Write = hello_mod_write,
. IOCTL = hello_mod_ioctl,
. Release = hello_mod_release,
};

 

After this struct variable is defined, we can use register_chrdev () in the module initialization function or fill in the cdev structure to associate all operations to our module function.

 

The data that interacts with devices is called "data", but it can be roughly divided into two types.

"Function data": Enter the data that the device processes and that the device outputs after processing.

"Control Data": commands and parameters used to control device features.

Open, read, write, release and other functions are used for a driver module, which is our use of "device functions. However, a device may have many functions. How can we control the device to allow the device to complete the specified functions?

For example, if we have a translation machine (for example, a machine or a machine), the main function is to input Chinese characters and then output the Translation results corresponding to various languages, the function of this machine is translation. The data we actually use to process is the Chinese input. The "device function" we want to get is the output content after translation, the various languages are the control of our choice. We can set the language in which the device is translated. This requires us to send commands to the device and set the target language. Note that we want to send two "Control Data" commands and parameters.

 

Command: A device may have many behaviors. Our command represents what behavior we want the device to perform. "Reset", "set target language", "Get current target language", etc.

Parameter: for a command, parameters may not be required.

For example:

Parameters are not required for the "reset" command.

To set the target language, you need to input the type of the target language.

To obtain the target language, you must input a parameter that can receive the target language type.

 

I drew a picture of the device "data flow", hoping to deepen my understanding.

 

For our own devices, we need to define their own device commands. If you want to find out the command format, please refer to other information about IOCTL parameters.

I will not introduce this here. I will only introduce the actual functions of IOCTL. Macros are required to define your own Io control commands. Write down my definition instead of introducing macro implementation.

 

# Define hello_magic 12
# Define hello_ioctl_resetlang _ IO (hello_magic, 0) // set the reset command without Parameters
# Define hello_ioctl_getlang _ ior (hello_magic, 1, INT) // obtain the language type parameter of the current device. The parameter is of the int type.
# Define hello_ioctl_setlang _ Iow (hello_magic, 2, INT) // set the language type of the device. The parameter is of the int type.

 

If you don't want to talk about it much, the complete code will be pasted below, and the lazy will not write comments .. Sorry.

Hello_mod.c

/* <Br/> * = ========================================================== =============< br/> * <br/> * filename: hello. c <br/> * Description: hello_mod <br/> * version: 1.0 <br/> * created: 01/28/2011 05:07:55 <br/> * revision: None <br/> * Compiler: GCC <br/> * Author: tishion (shion ), tishion@163.com <br/> * company: lim <br/> * ==================== ========================================================== ==================================< Br/> */</P> <p> # include <Linux/ module. h> <br/> # include <Linux/init. h> <br/> # include <Linux/kernel. h> <br/> # include <Linux/Fs. h> <br/> # include <Linux/uaccess. h> <br/> # include <Linux/semaphore. h> <br/> # include <Linux/cdev. h> <br/> # include <Linux/device. h> <br/> # include <Linux/IOCTL. h> <br/> # include <Linux/slab. h> <br/> # include <Linux/err No. h> <br/> # include <Linux/string. h> <br/> # include "hello_mod_ioctl.h" </P> <p> # define major_num 250 <br/> # define minor_num 0 <br/> # define in_buf_len 256 <br /># define out_buf_len 512 </P> <p> module_author ("tishion "); <br/> module_description ("hello_mod driver by tishion"); </P> <p> static struct class * hello_class; <br/> static struct cdev hello_cdev; <br/> static dev_t devnum = 0; <br/> static char * modna Me = "hello_mod"; <br/> static char * devicename = "hello"; <br/> static char * classname = "hello_class "; </P> <p> static int open_count = 0; <br/> static struct semaphore SEM; <br/> static spinlock_t spin = spin_lock_unlocked; <br/> static char * inbuffer = NULL; <br/> static char * outbuffer = NULL; <br/> static lang_t langtype; </P> <p> static int hello_mod_open (struct inode *, struct file *); <br/> static Int hello_mod_release (struct inode *, struct file *); <br/> static ssize_t hello_mod_read (struct file *, char *, size_t, loff_t *); <br/> static ssize_t hello_mod_write (struct file *, const char *, size_t, loff_t *); <br/> static int hello_mod_ioctl (struct inode *, struct file *, unsigned int, unsigned long); </P> <p> struct file_operations hello_mod_fops = <br/>{< br/>. owner = this_module, <br/>. open = Hello_mod_open, <br/>. read = hello_mod_read, <br/>. write = hello_mod_write, <br/>. IOCTL = hello_mod_ioctl, <br/>. release = hello_mod_release, <br/>}; </P> <p> static int hello_mod_open (struct inode * inode, struct file * pfile) <br/> {<br/> printk ("+ hello_mod_open ()! /N "); <br/> spin_lock (& spin); <br/> If (open_count) <br/>{< br/> spin_unlock (& spin ); <br/> return-ebusy; <br/>}< br/> open_count ++; <br/> spin_unlock (& spin ); <br/> printk ("-hello_mod_open ()! /N "); <br/> return 0; <br/>}< br/> static int hello_mod_release (struct inode * inode, struct file * pfile) <br/> {<br/> printk ("+ hello_mod_release ()! /N "); <br/> open_count --; <br/> printk ("-hello_mod_release ()! /N "); <br/> return 0; <br/>}< br/> static ssize_t hello_mod_read (struct file * pfile, char * user_buf, size_t Len, loff_t * off) <br/> {<br/> printk ("+ hello_mod_read ()! /N "); </P> <p> If (down_interruptible (& SEM) <br/>{< br/> return-erestartsys; <br/>}< br/> memset (outbuffer, 0, out_buf_len); <br/> printk ("+ switch ()/n "); <br/> switch (langtype) <br/> {<br/> case English: <br/> printk ("> In case: English/N "); <br/> sprintf (outbuffer, "Hello! % S. ", inbuffer); <br/> break; <br/> case Chinese: <br/> printk ("> In case: Chinese/N "); <br/> sprintf (outbuffer, "Hello! % S. ", inbuffer); <br/> break; <br/> case pinyin: <br/> printk ("> In case: pinyin/N "); <br/> sprintf (outbuffer, "Ni hao! % S. ", inbuffer); <br/> break; <br/> default: <br/> printk ("> In case: default/N "); <br/> break; <br/>}< br/> printk ("-switch ()/n"); <br/> If (copy_to_user (user_buf, outbuffer, Len )) <br/>{< br/> up (& SEM); <br/> return-efault; <br/>}< br/> up (& SEM ); <br/> printk ("-hello_mod_read ()! /N "); <br/> return 0; <br/>}< br/> static ssize_t hello_mod_write (struct file * pfile, const char * user_buf, size_t Len, loff_t * off) <br/> {<br/> printk ("+ hello_mod_write ()! /N "); <br/> If (down_interruptible (& SEM) <br/>{< br/> return-erestartsys; <br/>}< br/> If (LEN> in_buf_len) <br/>{< br/> printk ("out of input buffer/N "); <br/> return-erestartsys; <br/>}< br/> If (copy_from_user (inbuffer, user_buf, Len )) <br/>{< br/> up (& SEM); <br/> return-efault; <br/>}< br/> up (& SEM ); <br/> printk ("-hello_mod_write ()! /N "); <br/> return 0; <br/>}< br/> static int hello_mod_ioctl (struct inode * inode, struct file * pfile, unsigned int cmd, unsigned long Arg) <br/>{< br/> int err = 0; <br/> printk ("+ hello_mod_ioctl ()! /N "); <br/> printk (" + switch ()/n "); <br/> switch (CMD) <br/>{< br/> case hello_ioctl_resetlang: <br/> printk ("> In case: hello_ioctl_resetlang/N"); <br/> langtype = English; <br/> break; <br/> case hello_ioctl_getlang: <br/> printk ("> In case: hello_ioctl_getlang/N "); <br/> err = copy_to_user (int *) Arg, & langtype, sizeof (INT); <br/> break; <br/> case hello_ioctl_setlang: <br/> printk ("> In case: hello_ioctl_setla Ng/N "); <br/> err = copy_from_user (& langtype, (int *) Arg, sizeof (INT); <br/> break; <br/> default: <br/> printk ("> In case: default/N"); <br/> err = enotsupp; <br/> break; <br/>}< br/> printk ("-switch ()/n"); <br/> printk ("-hello_mod_ioctl ()! /N "); <br/> return err; <br/>}< br/> static int _ init hello_mod_init (void) <br/>{< br/> int result; <br/> printk ("+ hello_mod_init ()! /N "); <br/> devnum = mkdev (major_num, minor_num); <br/> result = register_chrdev_region (devnum, 1, modname ); </P> <p> If (result <0) <br/> {<br/> printk ("hello_mod: Can't Get Major number! /N "); <br/> return result; <br/>}</P> <p> cdev_init (& hello_cdev, & hello_mod_fops ); <br/> hello_cdev.owner = this_module; <br/> hello_cdev.ops = & hello_mod_fops; <br/> result = cdev_add (& hello_cdev, devnum, 1 ); <br/> If (result) <br/> printk ("failed at cdev_add ()"); <br/> hello_class = class_create (this_module, classname ); <br/> If (is_err (hello_class) <br/> {<br/> printk ("failed at class_create (). please exec [Mknod] Before operate the device/N "); <br/>}< br/> else <br/>{< br/> device_create (hello_class, null, devnum, null, devicename); <br/>}</P> <p> open_count = 0; <br/> langtype = English; <br/> inbuffer = (char *) kmalloc (in_buf_len, gfp_kernel); <br/> outbuffer = (char *) kmalloc (out_buf_len, gfp_kernel); <br/> init_mutex (& SEM ); <br/> printk ("-hello_mod_init ()! /N "); <br/> return 0; <br/>}</P> <p> static void _ exit hello_mod_exit (void) <br/> {<br/> printk ("+ hello_mod_exit! /N "); <br/> kfree (inbuffer); <br/> kfree (outbuffer); <br/> cdev_del (& hello_cdev ); <br/> device_destroy (hello_class, devnum); <br/> class_destroy (hello_class); <br/> unregister_chrdev_region (devnum, 1 ); <br/> printk ("-hello_mod_exit! /N "); <br/> return; <br/>}</P> <p> module_init (hello_mod_init); <br/> module_exit (hello_mod_exit ); <br/> module_license ("GPL"); <br/>

 

Hello_mod_iotcl.h

/* <Br/> * = ========================================================== =============< br/> * <br/> * filename: hello_mod_ioctl.h <br/> * Description: Define the CMD supported by hello_mod <br/> * version: 1.0 <br/> * created: 06/19/2011 10:24:20 <br/> * revision: None <br/> * Compiler: GCC <br/> * Author: tishion (shion ), tishion@163.com <br/> * company: lim <br/> * ========================== ========================================================== ======================< br/> */</P> <p> # ifndef _ hello_mod_ioctl_h__< br/> # define _ hello_mod_ioctl_h __</P> <p> # define hello_magic12 <br/> # define hello_ioctl_resetlang_io (hello_magic, 0) // set langtype = English <br/> # define hello_ioctl_getlang_ior (hello_magic, 1, INT) // get langtype <br/> # define hello_ioctl_setlang_iow (hello_magic, 2, INT) // set langtype </P> <p> typedef Enum _ lang_t <br/> {<br/> English, Chinese, Pinyin <br/>} lang_t; </P> <p> # endif <br/>

 

Makefile

#*************************************** * ****** <Br/> # makefile Linux 2.6 module <br/> # This makefile is written for Ubuntu 10.10 <br/> # It may not perfomance without erros on the <br/> # other version or distributions. <br/> #*********************************** * ********** <br/> #: tishion <br/> # mail: tishion@163.com <br/> #**************************** * ***************** <br/> obj-M + = hello_mod.o <br/> current_path: = $ (shell PWD) <br/> linux_kernel :=$ (shell uname-R) <br/> linux_kernel_path: =/usr/src/Linux-headers-$ (linux_kernel) <br/> All: <br/> make-C $ (linux_kernel_path) M = $ (current_path) Modules <br/> clean: <br/> make-C $ (linux_kernel_path) M = $ (current_path) Clean <br/> install: <br/> insmod hello_mod.ko <br/> unistall: <br/> rmmod hello_mod <br/>

 

Attaches a user-layer test file. After compilation, the file must be executed as the root user.

/* <Br/> * = ========================================================== =============< br/> * <br/> * filename: hell_mod_test.c <br/> * Description: hell_mod test app <br/> * version: 1.0 <br/> * created: 06/20/2011 01:44:11 am <br/> * revision: None <br/> * Compiler: GCC <br/> * Author: tishion (shion ), tishion@163.com <br/> * company: Lim <br/> * = ========================================================== =======================================================< Br /> */</P> <p> # include <stdio. h> <br/> # include <sys/types. h> <br/> # include <sys/STAT. h> <br/> # include <fcntl. h> <br/> # include <unistd. h> <br/> # include <Linux/IOCTL. h> <br/> # include <string. h> <br/> # include <errno. h> <br/> # include ".. /hello_mod_ioctl.h "</P> <p> int main () <br/> {<br/> char outbuf [512]; <br/> char * myname = "Tishion"; <br/> lang_t langtype = English; <br/> int FD = open ("/dev/Hello", o_rdwr, s_irusr | s_iwusr ); <br/> If (FD! =-1) <br/>{< br/> write (FD, myname, strlen (myname) + 1); <br/> langtype = Chinese; <br/> IOCTL (FD, hello_ioctl_setlang, & langtype); <br/> Read (FD, outbuf, 512); <br/> printf ("langtype = Chinese: % s/n ", outbuf); <br/> memset (outbuf, 0,512); <br/> langtype = pinyin; <br/> IOCTL (FD, hello_ioctl_setlang, & langtype); <br/> Read (FD, outbuf, 512); <br/> printf ("langtype = pinyin: % s/n", outbuf ); <br/> memset (outbuf, 0,512); <br/> IOCTL (FD, hello_ioctl_resetlang, & langtype); <br/> Read (FD, outbuf, 512 ); <br/> printf ("langtype = English: % s/n", outbuf ); <br/>}< br/> else <br/> {<br/> perror ("failed at open ():"); <br/>}< br/> return 0; <br/>}</P> <p>

 

Compiling and running process diagram

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.