0%

杂项设备

杂项设备的使用流程

1、杂项设备(misc device)
  • 概念:

    杂项设备是linux内核提供的一种字符设备驱动矿建,用于管理那些功能比较简单、数量较少的设备。

  • 特点:

    主设备号固定为10,通过次设备号来区分不同的杂项设备。

    结构简单

    提供基本的读写操作接口

2、驱动开发流程及其讲解

​ 1、包含头文件

1
2
3
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>

​ 2、定义文件操作结构体

1
2
3
4
5
6
const struct file_operations led_fops = {
.owner = THIS_MODULE,
.open = led_pdrv_open,
.write = led_pdrv_write,
.release = led_pdrv_close,
};

​ 3、定义杂项设备结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
struct miscdevice misc;

struct miscdevice {
int minor;
const char *name;
const struct file_operations *fops;
struct list_head list;
struct device *parent;
struct device *this_device;
const struct attribute_group **groups;
const char *nodename;
umode_t mode;
};

​ 参数:

	* minor:次设备号。
	* name:设备节点名称。
	* fops:文件操作结构体指针。
	* 其他的用到的不多,用到可以在搜。

​ 4、注册杂项设备

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
    ret = misc_register(&led_dev->misc);
if (ret) {
printk("misc register failed\n");
goto err_kfree;
}

int misc_register(struct miscdevice *misc)
{
dev_t dev;
int err = 0;
bool is_dynamic = (misc->minor == MISC_DYNAMIC_MINOR);

INIT_LIST_HEAD(&misc->list);

mutex_lock(&misc_mtx);

if (is_dynamic) {
int i = find_first_zero_bit(misc_minors, DYNAMIC_MINORS);

if (i >= DYNAMIC_MINORS) {
err = -EBUSY;
goto out;
}
misc->minor = DYNAMIC_MINORS - i - 1;
set_bit(i, misc_minors);
} else {
struct miscdevice *c;

list_for_each_entry(c, &misc_list, list) {
if (c->minor == misc->minor) {
err = -EBUSY;
goto out;
}
}
}

dev = MKDEV(MISC_MAJOR, misc->minor);

misc->this_device =
device_create_with_groups(misc_class, misc->parent, dev,
misc, misc->groups, "%s", misc->name);
if (IS_ERR(misc->this_device)) {
if (is_dynamic) {
int i = DYNAMIC_MINORS - misc->minor - 1;

if (i < DYNAMIC_MINORS && i >= 0)
clear_bit(i, misc_minors);
misc->minor = MISC_DYNAMIC_MINOR;
}
err = PTR_ERR(misc->this_device);
goto out;
}

/*
* Add it to the front, so that later devices can "override"
* earlier defaults
*/
list_add(&misc->list, &misc_list);
out:
mutex_unlock(&misc_mtx);
return err;
}

​ 5、注销杂项设备

1
misc_deregister(&led_dev->misc);
3、杂项设备的使用
  • 创建设备节点:

    注册杂项设备后,在系统的/dev/目录下会自动创建一个设备节点。

  • 应用程序访问:

    应用程序可以通过系统调用(如open、write、read)来访问该设备节点,从而与驱动进行交互。