7_生成设备节点

在dev目录下生成可操作的设备节点文件

Posted by Jerry Chen on June 20, 2019

本节设备是注册到杂项设备的设备节点,所以需要关注三个文件:

  • drivers/char/misc.c
  • include/linux/miscdevice.h
  • include/linux/fs.h

miscdevice杂项设备设备节点相关参数

关键结构体:miscdevice

常用参数

  • .minor设备号 可以通过一个宏让系统自动分配
  • .name 生成设备节点的名称(/dev/下的文件名称)
  • .fops指向一个设备节点文件

常用函数

  • misc_register
  • misc_deregister

fs文件系统相关参数

关键结构体:file_operations

必选参数:

  • .owner 一般是THIS_MODULE
  • .open打开文件函数
  • . release关闭/释放文件函数

其他参数:

  • .unlocked_ioctl 对GPIO进行操作

模板

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
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>

/*注册杂项设备设备节点的头文件*/
#include <linux/miscdevice.h>
/*文件操作的头文件*/
#include <linux/fs.h>

MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("jerry");

#define DRV_NAME "platform_hello"
#define DRV_NODE_NAME "hello_dev"

static int hello_open(struct inode *inode, struct file *file){
	printk(KERN_EMERG "hello_open ok!\n");
	return 0;
}
static int hello_release(struct inode *inode, struct file *file){
	printk(KERN_EMERG "hello_release ok!\n");
	return 0;
}
static long hello_ioctl(struct file *file, unsigned int cmd, unsigned long arg){
	printk(KERN_EMERG "cmd is %d;arg is %d;\n",cmd,arg);
	return 0;
}

static struct file_operations hello_ops = {
	.owner	= THIS_MODULE,
	.open	= hello_open,
	.release	= hello_release,
	.unlocked_ioctl	= hello_ioctl,
};

static struct miscdevice misc_hello = {
	.minor	= MISC_DYNAMIC_MINOR,	// 自动分配
	.name	= DRV_NODE_NAME,
	.fops	= &hello_ops,
};

static int hello_probe(struct platform_device *pdv){
	printk(KERN_EMERG "hello_probe ok!\n");
	misc_register(&misc_hello);
	
	return 0;
}
static int hello_remove(struct platform_device *pdv){
	printk(KERN_EMERG "hello_remove ok!\n");
	misc_deregister(&misc_hello);
	
	return 0;
}

static void hello_shutdown(struct platform_device *pdv){
	printk(KERN_EMERG "hello_shutdown ok!\n");
}
static int hello_suspend(struct platform_device *pdv, pm_message_t state){
	printk(KERN_EMERG "hello_suspend ok!\n");
	return 0;
}
static int hello_resume(struct platform_device *pdv){
	printk(KERN_EMERG "hello_resume ok!\n");
	return 0;
}

static struct platform_driver platform_drv_hello = {
	.probe	= hello_probe,
	.remove	= hello_remove,
	.shutdown	= hello_shutdown,
	.suspend	= hello_suspend,
	.resume	= hello_resume,
	.driver	= {
		.name	= DRV_NAME,
		.owner	= THIS_MODULE,
	},
};

static int hello_init(void){
	platform_driver_register(&platform_drv_hello);
	return 0;
}
static void hello_exit(void){
	platform_driver_unregister(&platform_drv_hello);
}

module_init(hello_init);
module_exit(hello_exit);

加载设备module和上述驱动module后就会发现/dev目录下已经出现了hello_dev设备节点文件。