
一、实验程序的编写
源代码下载
bash
git clone git@gitee.com:yangxuesong314/linux-driver.git1
- 若之前已 git 拉取代码可以忽略
- 代码位于:
linux-driver/02.Linux设备模型/08.在自己的总线下注册驱动实验
我们编写驱动代码,这段代码的作用是注册一个驱动程序,该驱动程序属于名为 mydevice 的总线类型 mybus,并在探测设备时调用 mydriver_probe 函数,移除设备时调用 mydriver_remove 函数。编写完成的 driver.c 代码如下所示:
c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/configfs.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/device.h>
#include <linux/sysfs.h>
extern struct bus_type mybus;
int mydriver_remove(struct device *dev) {
printk("This is mydriver_remove\n");
return 0;
};
int mydriver_probe(struct device *dev) {
printk("This is mydriver_probe\n");
return 0;
};
struct device_driver mydriver = {
.name = "mydevice",
.bus = &mybus,
.probe = mydriver_probe,
.remove = mydriver_remove,
};
// 模块的初始化函数
static int mydriver_init(void)
{
int ret;
ret = driver_register(&mydriver);
return ret;
}
// 模块退出函数
static void mydriver_exit(void)
{
driver_unregister(&mydriver);
}
module_init(mydriver_init); // 指定模块的初始化函数
module_exit(mydriver_exit); // 指定模块的退出函数
MODULE_LICENSE("GPL"); // 模块使用的许可证
MODULE_AUTHOR("linux"); // 模块的作者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
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
二、实验
开发板启动之后,使用以下命令进行 bus.ko 驱动模块的加载:
bash
insmod bus.ko1
然后加载 device.ko 驱动模块:
bash
insmod device.ko1
驱动加载 insmod driver.ko 之后,我们进入 /sys/bus/mybus/drivers 目录下,有注册生成的设备即可。
