Linux character device driver development (3) - device control character

1 Device Control Theory

1.1 Control Theory - Role

  • Most drivers need to provide in addition to the ability to read and write device, also need to have the ability to control devices. For example: change the baud rate.

Device Control 1.2 - Application Function

  • In user space using ioctl system call to the control apparatus, the following prototype:
int ioctl(int fd,unsigned long cmd,...)
//fd: 要控制的设备文件描述符
//cmd: 发送给设备的控制命令
//…: 第3个参数是可选的参数,存在与否是依赖于控制命令(第 2 个参数 )。比如命令是设置波特率,第三个参数就应该是波特率的数字了;但如果命令是重启,则不需要第三个参数。

Device Control 1.3 - driver function

  • When an application using the ioctl system call, in response to the driver by the following function:
  • Prior to the 2.6.36 kernel: Long (* ioctl) (the Node struct inode *, struct File * filp, cmd unsigned int, unsigned Long Arg)
  • After the 2.6.36 kernel: Long (* unlocked_ioctl) (struct File * filp, cmd unsigned int, unsigned Long Arg)
    • Parameters cmd: command transmitting down by applying the ioctl function
  • Therefore, the design-driven development, required according to the following method, first determine the application uses a system call such as read, write, open, these system calls which function should be used in the kernel, for example sys_read, sys_write, then Thinking how to implement device corresponding to the method. (System calls ---> kernel function ---> Device method)

2 Device control is realized

2.1 Control implementation - defined command

  • Command from its very nature is an integer, but in order to make this integer with better readability, we usually put this integer is divided into several sections: type (8) , serial number , parameter transfer direction , parameter length .
    • Type (Type / magic number): indicates that this is the command which device belongs to.
    • Number () number , the same device used to distinguish different commands
    • The Direction : the direction of transmission parameters, the values may be _IOC_NONE (no data transmission), _IOC_READ , _IOC_WRITE (write parameter to the device)
    • Size : length parameter

2.2 the control device - to define the command

  • Linux system provides the following macro to help define the command:
    • _IO (of the type, nr) : command with no arguments
    • _IOR (type, NR, datatype) : read command parameter from the device, datatype parameters representative of the type
    • _IOW (of the type, nr, DataType) : command parameters are written to the device
  • such as:
  • MEM_MAGIC #define 'm'    // defined magic number, instead of using an 8-bit character values
  • MEM_SET _IOW #define (MEM_MAGIC, 0, int)     // define a data write command to the apparatus

Device Control 2.2 - Implementation-

  • achieve unlocked_ioctl function is usually a switch statement is executed according to the command. However, when the command number does not match any of the commands supported by the device of a return - EINVAL .
    • Programming model:
    • Switch cmd
    • Case command A:
    • // perform an operation corresponding to A
    • Case command B:
    • // perform an operation corresponding to B
    • Default:
    • // return -EINVAL

3 Hands

  • Achieve device control character

mem_ctl.h

#define MEM_MAGIC 'm'                     // 设备幻数

#define MEM_RESTART _IO(MEM_MAGIC, 0)         // 重启命令

#define MEM_SET _IOW(MEM_MAGIC, 1, int)   // 向设备写入参数的命令

mem_ctl.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include "memdev.h"

int main()
{
    int fd;
    
    fd = open("/dev/memdev0", O_RDWR);  // 打开设备文件
    
    ioctl(fd, MEM_SET, 115200);
    
    ioctl(fd, MEM_RESTART);
    
    return 0;	
}

memdev.c

#include <linux/module.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
#include "memdev.h"

int dev1_registers[5];
int dev2_registers[5];

struct cdev cdev; 
dev_t devno;

/*文件打开函数*/
int mem_open(struct inode *inode, struct file *filp)
{
	/*获取次设备号*/
	int num = MINOR(inode->i_rdev);
    
	if (num==0)
		filp->private_data = dev1_registers;
	else if(num == 1)
		filp->private_data = dev2_registers;
	else
		return -ENODEV;  //无效的次设备号
    
	return 0; 
}

/*文件释放函数*/
int mem_release(struct inode *inode, struct file *filp)
{
	return 0;
}

/*读函数*/
static ssize_t mem_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
	unsigned long p =  *ppos;
	unsigned int count = size;
	int ret = 0;
	int *register_addr = filp->private_data; /*获取设备的寄存器基地址*/

	/*判断读位置是否有效*/
	if (p >= 5*sizeof(int))
		return 0;
	if (count > 5*sizeof(int) - p)
		count = 5*sizeof(int) - p;

	/*读数据到用户空间*/
	if (copy_to_user(buf, register_addr+p, count))
	{
		ret = -EFAULT;
	}
	else
	{
		*ppos += count;
		ret = count;
	}

	return ret;
}

/*写函数*/
static ssize_t mem_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
{
	unsigned long p =  *ppos;
	unsigned int count = size;
	int ret = 0;
	int *register_addr = filp->private_data; /*获取设备的寄存器地址*/
  
	/*分析和获取有效的写长度*/
	if (p >= 5*sizeof(int))
		return 0;
	if (count > 5*sizeof(int) - p)
		count = 5*sizeof(int) - p;
    
	/*从用户空间写入数据*/
	if (copy_from_user(register_addr + p, buf, count))
		ret = -EFAULT;
	else
	{
		*ppos += count;
		ret = count;
	}

	return ret;
}

/* seek文件定位函数 */
static loff_t mem_llseek(struct file *filp, loff_t offset, int whence)
{ 
	loff_t newpos;

	switch(whence) 
	{
		case SEEK_SET: 
		newpos = offset;
		break;

		case SEEK_CUR: 
		newpos = filp->f_pos + offset;
		break;

		case SEEK_END: 
		newpos = 5*sizeof(int)-1 + offset;
		break;

		default: 
		return -EINVAL;
}
	if ((newpos<0) || (newpos>5*sizeof(int)))
		return -EINVAL;
    	
	filp->f_pos = newpos;
	return newpos;
}

long mem_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	switch (cmd)
	{
		case MEM_RESTART:
			printk("restart device!\n");
			return 0;
            
		case MEM_SET:
			printk("arg is %lu\n",arg);
			return 0;
            
		default:
			return -EINVAL;   	
	}		
}

/*文件操作结构体*/
static const struct file_operations mem_fops =
{
	.llseek = mem_llseek,
	.read = mem_read,
	.write = mem_write,
	.open = mem_open,
	.release = mem_release,
	.unlocked_ioctl = mem_ioctl,
};

/*设备驱动模块加载函数*/
static int memdev_init(void)
{
	/*初始化cdev结构*/
	cdev_init(&cdev, &mem_fops);
  
	/* 注册字符设备 */
	alloc_chrdev_region(&devno, 0, 2, "memdev");
	cdev_add(&cdev, devno, 2);

	return 0;
}

/*模块卸载函数*/
static void memdev_exit(void)
{
	cdev_del(&cdev);   /*注销设备*/
	unregister_chrdev_region(devno, 2); /*释放设备号*/
}

MODULE_LICENSE("GPL");

module_init(memdev_init);
module_exit(memdev_exit);

operation result

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_22847457/article/details/91354488