Linux Device driven Ioctl control

Most drivers need to have the ability to read and write devices , Also need to have the ability to control the hardware .

One 、 In user space , Use ioctl The system is called to control the equipment , The prototype is as follows :

 

int ioctl(int fd,unsigned long cmd,...);
/*
fd: File descriptor
cmd: Control command
...: Optional parameters : Insert *argp, The details depend on cmd
*/

 

All the user program does is tell the driver what it wants to do through the command code , as for How to explain these commands and how to implement them , That's what drivers do .

Two 、 drive ioctl Method

 

int (*ioctl) (struct inode *inode,struct file *filp,unsigned int cmd,unsigned long arg);
/*
inode And filp Two pointers correspond to the file descriptor passed by the application fd, It's not just about delivery open The parameters of the method are the same .
cmd  The user space is directly passed to the driver without modification
arg  Optional .
*/

Implemented in the driver ioctl Function body , There's actually one switch {case} structure , every last case Corresponding to a command code , Do something about it . How to implement these operations , It's every programmer's own business , Because devices are specific . The key is how to organize the command code , Because in ioctl Command code is the only way to contact user program command and driver support .

stay Linux The core is to define a Command code Of :
____________________________________

| Device type  | Serial number |   Direction | Data size |

|----------|--------|------|-------- |

| 8 bit |  8 bit   | 2 bit |8~14 bit|

|----------|--------|------|-------- |

thus , A command becomes an integer command code . But the command code is not intuitive , therefore Linux Kernel Some macros are provided in , These macros generate command codes based on easy to understand strings , Or get some strings that users can understand from the command code to indicate the device type corresponding to the command 、 Equipment serial number 、 Data transmission direction and data transmission size .

1、 Define the order :
The kernel provides some macros to help define commands :

//nr Serial number ,datatype Is the data type , Such as int
_IO(type, nr ) // Commands without parameters
_IOR(type, nr, datatype) // Read data from the driver
_IOW(type, nr, datatype) // Write data to drive
_IOWR(type,nr, datatype) // Two way transmission 

Define command examples :

#define MEM_IOC_MAGIC 'm' // Definition type
#define MEM_IOCSET _IOW(MEM_IOC_MAGIC,0,int)
#define MEM_IOCGQSET _IOR(MEM_IOC_MAGIC, 1, int)

 

2、 Implement the command :
The command is defined , The next step is to achieve ioctl Function ,ioctl The realization of the system includes three technical links :
1) Return value ;
ioctl The implementation of the function is a switch sentence , however , When a command cannot match a command supported by any device , Usually back to -EINVAL( Illegal parameters );
2) Parameters use ;
The user to use int ioctl(int fd,unsinged long cmd,...) when ,... Is the parameter to pass ;
Re pass int (*ioctl)(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) Medium arg Pass on ;
If arg It's a Integers , You can use it directly ;
If it is The pointer , We have to make sure that the user address is valid , therefore , It needs to be checked correctly before use .
There are internal checks , No need to test Of :

copy_from_user
copy_to_user
get_user
put_user

Need to detect Of :

__get_user
__put_user

Detection function access_ok():

static inline int access_ok(int type, const void *addr, unsigned long size)
/*
type : yes VERIFY_READ  perhaps VERIFY_WRITE Used to indicate whether to read or write user memory ;
addr: Is the memory address of the user to be operated on ;
size: It's the length of the operation . If ioctl You need to read an integer from user space , that size The parameter is equal to sizeof(int);
Return value :Access_ok Returns a Boolean value :1, To be successful ( No problem with access );0, It's failure ,ioctl return -EFAULT;
*/

 

3) The command operation ;

switch(cmd)
{
     case:
     ... ...
}

 

3、 ... and 、ioctl The example analysis

(1)memdev.h:

 

 

#ifndef _MEMDEV_H_
#define _MEMDEV_H_
#include <linux/ioctl.h>
#ifndef MEMDEV_MAJOR
#define MEMDEV_MAJOR 0   /* Preset mem The master number of the device */
#endif
#ifndef MEMDEV_NR_DEVS
#define MEMDEV_NR_DEVS 2    /* Number of devices */
#endif
#ifndef MEMDEV_SIZE
#define MEMDEV_SIZE 4096
#endif
/*mem Device description structure */
struct mem_dev                                     
{                                                        
  char *data;                      
  unsigned long size;       
};
/*  Defining magic numbers  */
#define MEMDEV_IOC_MAGIC  'k'
/*  Define the order  */
#define MEMDEV_IOCPRINT   _IO(MEMDEV_IOC_MAGIC, 1)
#define MEMDEV_IOCGETDATA _IOR(MEMDEV_IOC_MAGIC, 2, int)
#define MEMDEV_IOCSETDATA _IOW(MEMDEV_IOC_MAGIC, 3, int)
#define MEMDEV_IOC_MAXNR 3
#endif /* _MEMDEV_H_ */

 

 

(2)memdev.c:( The driver )

 

 

#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include "memdev.h"
static int mem_major = MEMDEV_MAJOR;
module_param(mem_major, int, S_IRUGO);
struct mem_dev *mem_devp; /* Device structure pointer */
struct cdev cdev; 
/* File open function */
int mem_open(struct inode *inode, struct file *filp)
{
    struct mem_dev *dev;
    
    /* Get the secondary device number */
    int num = MINOR(inode->i_rdev);
    if (num >= MEMDEV_NR_DEVS) 
            return -ENODEV;
    dev = &mem_devp[num];
    
    /* Assign device description structure pointer to file private data pointer */
    filp->private_data = dev;
    
    return 0; 
}
/* File release function */
int mem_release(struct inode *inode, struct file *filp)
{
  return 0;
}
/*IO operation */
int memdev_ioctl(struct inode *inode, struct file *filp,
                 unsigned int cmd, unsigned long arg)
{
    int err = 0;
    int ret = 0;
    int ioarg = 0;
    
    /*  Check the validity of the command  */
    if (_IOC_TYPE(cmd) != MEMDEV_IOC_MAGIC) 
        return -EINVAL;
    if (_IOC_NR(cmd) > MEMDEV_IOC_MAXNR) 
        return -EINVAL;
    /*  Depending on the command type , Check whether the parameter space is accessible  */
    if (_IOC_DIR(cmd) & _IOC_READ)
        err = !access_ok(VERIFY_WRITE, (void *)arg, _IOC_SIZE(cmd));
    else if (_IOC_DIR(cmd) & _IOC_WRITE)
        err = !access_ok(VERIFY_READ, (void *)arg, _IOC_SIZE(cmd));
    if (err) 
        return -EFAULT;
    /*  According to the command , Perform the corresponding operation  */
    switch(cmd) {
      /*  Print current device information  */
      case MEMDEV_IOCPRINT:
          printk("<--- CMD MEMDEV_IOCPRINT Done--->\n\n");
        break;
      
      /*  To obtain parameters  */
      case MEMDEV_IOCGETDATA: 
        ioarg = 1101;
        ret = __put_user(ioarg, (int *)arg);
        break;
      
      /*  Set parameters  */
      case MEMDEV_IOCSETDATA: 
        ret = __get_user(ioarg, (int *)arg);
        printk("<--- In Kernel MEMDEV_IOCSETDATA ioarg = %d --->\n\n",ioarg);
        break;
      default:  
        return -EINVAL;
    }
    return ret;
}
/* File operation structure */
static const struct file_operations mem_fops =
{
  .owner = THIS_MODULE,
  .open = mem_open,
  .release = mem_release,
  .ioctl = memdev_ioctl,
};
/* Device driver module loading function */
static int memdev_init(void)
{
  int result;
  int i;
  dev_t devno = MKDEV(mem_major, 0);
  /*  Static application equipment number */
  if (mem_major)
    result = register_chrdev_region(devno, 2, "memdev");
  else  /*  Dynamically assign device numbers  */
  {
    result = alloc_chrdev_region(&devno, 0, 2, "memdev");
    mem_major = MAJOR(devno);
  }  
  
  if (result < 0)
    return result;
  /* initialization cdev structure */
  cdev_init(&cdev, &mem_fops);
  cdev.owner = THIS_MODULE;
  cdev.ops = &mem_fops;
  
  /*  Register character device  */
  cdev_add(&cdev, MKDEV(mem_major, 0), MEMDEV_NR_DEVS);
   
  /*  Allocate memory for the device description structure */
  mem_devp = kmalloc(MEMDEV_NR_DEVS * sizeof(struct mem_dev), GFP_KERNEL);
  if (!mem_devp)    /* Application failed */
  {
    result =  - ENOMEM;
    goto fail_malloc;
  }
  memset(mem_devp, 0, sizeof(struct mem_dev));
  
  /* Allocate memory for devices */
  for (i=0; i < MEMDEV_NR_DEVS; i++) 
  {
        mem_devp[i].size = MEMDEV_SIZE;
        mem_devp[i].data = kmalloc(MEMDEV_SIZE, GFP_KERNEL);
        memset(mem_devp[i].data, 0, MEMDEV_SIZE);
  }
    
  return 0;
  fail_malloc: 
  unregister_chrdev_region(devno, 1);
  
  return result;
}
/* Module unload function */
static void memdev_exit(void)
{
  cdev_del(&cdev);   /* Log off the device */
  kfree(mem_devp);     /* Free device structure memory */
  unregister_chrdev_region(MKDEV(mem_major, 0), 2); /* Release the device number */
}
MODULE_AUTHOR("David Xie");
MODULE_LICENSE("GPL");
module_init(memdev_init);
module_exit(memdev_exit);

 

(3)app-ioctl.c( Applications )

#include <stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include "memdev.h"  /*  Contains command definitions  */
int main()
{
    int fd = 0;
    int cmd;
    int arg = 0;
    char Buf[4096];
    
    
    /* Open device file */
    fd = open("/dev/memdev0",O_RDWR);
    if (fd < 0)
    {
        printf("Open Dev Mem0 Error!\n");
        return -1;
    }
    
    /*  Call the command MEMDEV_IOCPRINT */
    printf("<--- Call MEMDEV_IOCPRINT --->\n");
    cmd = MEMDEV_IOCPRINT;
    if (ioctl(fd, cmd, &arg) < 0)
        {
            printf("Call cmd MEMDEV_IOCPRINT fail\n");
            return -1;
    }
    
    
    /*  Call the command MEMDEV_IOCSETDATA */
    printf("<--- Call MEMDEV_IOCSETDATA --->\n");
    cmd = MEMDEV_IOCSETDATA;
    arg = 2007;
    if (ioctl(fd, cmd, &arg) < 0)
        {
            printf("Call cmd MEMDEV_IOCSETDATA fail\n");
            return -1;
    }
    
    /*  Call the command MEMDEV_IOCGETDATA */
    printf("<--- Call MEMDEV_IOCGETDATA --->\n");
    cmd = MEMDEV_IOCGETDATA;
    if (ioctl(fd, cmd, &arg) < 0)
        {
            printf("Call cmd MEMDEV_IOCGETDATA fail\n");
            return -1;
    }
    printf("<--- In User Space MEMDEV_IOCGETDATA Get Data is %d --->\n\n",arg);    
    
    close(fd);
    return 0;    
}