本文最后更新于371 天前,其中的信息可能已经过时,如有错误请发送邮件到273925452@qq.com
驱动编写的3种方法
以 LED 驱动为例。
传统写法:
-使用哪个引脚,怎么操作引脚,都写死在代码中。
-最简单,不考虑扩展性,可以快速实现功能。
-修改引脚时,需要重新编译。

总线设备驱动模型:

- 引入 platform_device/platform_driver,将“资源”与“驱动”分离开来。
- 代码稍微复杂,但是易于扩展。
- 冗余代码太多,修改引脚时设备端的代码需要重新编译。
- 更换引脚时,图 9.3 中的 led_drv.c 基本不用改,但是需要修改 led_dev.c。
Bus/Dev/Drv 模型:
- 在内核里面有一个结构体(虚拟总线):platform_bus_type
- 这个总线抽象了2个链表:
- 驱动链表:platform_driver
- 设备链表:platform_device
如下图:

- 设备链表的每个设备要注册硬件资源(比如寄存器地址,内存地址,中断号):
- platform_device_add(struct platform_device *pdev) (用于在链表创建设备)
- 驱动链表的每个驱动要注册通用代码(比如注册字符驱动程序)
- platform_driver_reqister(drv)
- 每次注册新的驱动内核会自动去匹配设备,匹配成功就调用引脚编号等硬件资源,然后注册字符驱动。
- 每次注册新设备时内核也会自动去匹配驱动。

设备树:
- 因为Bus/Dev/Drv 模型也是用的.c文件,每次修改完后都需要重新编译,如果.c文件太多,内核会非常庞大。
- 在设备树里面加入设备节点,内核会自动构造 platform_deivce。
- 在板子启动的时候,需要一个
uboot文件
,他的作用是:
- 把SD卡里面的 dtb 文件放入内存;
- 把SD里面的 uImage 放入内存;
- 启动内核(把设备树地址传入内核,内核会把设备树文件解析成各种platform_deivce);
- 以后修改了板子,只需要修改设备树dtb就可以了。

- 通过配置文件──设备树来定义“资源”。
- 代码稍微复杂,但是易于扩展。
- 无冗余代码,修改引脚时只需要修改 dts 文件并编译得到 dtb 文件,把它传给内核。
- 无需重新编译内核/驱动。
模板代码
demo_drv.c
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/kmod.h>
#include <linux/gfp.h>
#include <linux/gpio/consumer.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/timer.h>
struct gpio_desc{
int gpio;
int irq;
char name[128];
int value;
struct timer_list demo_timer;
} ;
static struct gpio_desc *gpios;
static int count; // 引脚个数
/* 主设备号 */
static int major = 0;
static struct class *gpio_class;
/* 环形缓冲区 */
#define BUF_LEN 128
static int g_demos[BUF_LEN];
static int r, w;
struct fasync_struct *demo_fasync;
#define NEXT_POS(x) ((x+1) % BUF_LEN)
static int is_demo_buf_empty(void)
{
return (r == w);
}
static int is_demo_buf_full(void)
{
return (r == NEXT_POS(w));
}
static void put_demo(int value)
{
if (!is_demo_buf_full())
{
g_demos[w] = value;
w = NEXT_POS(w);
}
}
static int get_demo(void)
{
int value = 0;
if (!is_demo_buf_empty())
{
value = g_demos[r];
r = NEXT_POS(r);
}
return value;
}
static DECLARE_WAIT_QUEUE_HEAD(gpio_wait);
// static void demo_timer_expire(struct timer_list *t)
/* 定时器回调函数 */
static void demo_timer_expire(unsigned long data)
{
/* data ==> gpio */
// struct gpio_desc *gpio_desc = from_timer(gpio_desc, t, demo_timer);
struct gpio_desc *gpio_desc = (struct gpio_desc *)data;
int get_val;
int ture_val;
/* 获取引脚值 */
get_val = gpio_get_value(gpio_desc->gpio);
//printk("demo_timer_expire key %d %d\n", gpio_desc->gpio, val);
ture_val = (gpio_desc->value) | (get_val << 8);
/* 放入缓冲区 */
put_demo(ture_val);
/* 唤醒等待的进程*/
wake_up_interruptible(&gpio_wait);
/*取消异步I/O操作 */
kill_fasync(&demo_fasync, SIGIO, POLL_IN);
}
/* 实现对应的open/read/write等函数,填入file_operations结构体 */
static ssize_t demo_read (struct file *file, char __user *buf, size_t size, loff_t *offset)
{
//printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
int err;
int get_val;
/* 缓冲区是为空 并且为非阻塞模式 则立刻返回错误*/
if (is_demo_buf_empty() && (file->f_flags & O_NONBLOCK))
return -EAGAIN;
/* 把这个进程挂入等待队列,等待缓冲区非空 */
wait_event_interruptible(gpio_wait, !is_demo_buf_empty());
/* 从缓冲区获取引脚值 */
get_val = get_demo();
/* 把数据拷贝到用户空间 */
err = copy_to_user(buf, &get_val, 4);
return 4;
}
static ssize_t demo_write(struct file *file, const char __user *buf, size_t size, loff_t *offset)
{
unsigned char ker_buf[2];
int err;
if (size != 2)
return -EINVAL;
/* 获取用户空间数据(2字节) */
err = copy_from_user(ker_buf, buf, size);
/* 用户输入的引脚超过引脚个数 */
if (ker_buf[0] >= sizeof(gpios)/sizeof(gpios[0]))
return -EINVAL;
/* 设置引脚值 */
gpio_set_value(gpios[ker_buf[0]].gpio, ker_buf[1]);
return 2;
}
static unsigned int demo_poll(struct file *fp, poll_table * wait)
{
//printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
/* 加入等待队列 */
poll_wait(fp, &gpio_wait, wait);
/* 判断缓冲区是否为空 */
return is_demo_buf_empty() ? 0 : POLLIN | POLLRDNORM;
}
static int demo_fasync_fuc(int fd, struct file *file, int on)
{
if (fasync_helper(fd, file, on, &demo_fasync) >= 0)
return 0;
else
return -EIO;
}
/* 定义自己的file_operations结构体 */
static struct file_operations demo_drv = {
.owner = THIS_MODULE,
.read = demo_read,
.write = demo_write,
.poll = demo_poll,
.fasync = demo_fasync_fuc,
};
/* 中断回调函数 */
static irqreturn_t demo_isr(int irq, void *dev_id)
{
/* 从设备树获取引脚值 */
struct gpio_desc *gpio_desc = dev_id;
printk("demo_isr key %d irq happened\n", gpio_desc->gpio);
/* 开启定时器 */
mod_timer(&gpio_desc->demo_timer, jiffies + HZ/5);
return IRQ_HANDLED;
}
/* 在入口函数 */
static int gpio_drv_probe(struct platform_device *pdev)
{
int err = 0;
int i;
struct device_node *np = pdev->dev.of_node; // 取出设备树节点
struct resource *res;
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
/* 从platfrom_device获得引脚信息
* 1. pdev来自c文件
* 2. pdev来自设备树
*/
if (np)
{
/* pdev来自设备树 : 示例
reg_usb_ltemodule: regulator@1 {
compatible = "100ask,gpiodemo";
gpios = <&gpio5 5 GPIO_ACTIVE_HIGH>, <&gpio5 3 GPIO_ACTIVE_HIGH>;
};
*/
/* 获取引脚个数 */
count = of_gpio_count(np);
if (!count)
return -EINVAL;
/* 申请内存 */
gpios = kmalloc(count * sizeof(struct gpio_desc), GFP_KERNEL);
/* 获取引脚 */
for (i = 0; i < count; i++)
{
gpios[i].gpio = of_get_gpio(np, i);
sprintf(gpios[i].name, "%s_pin_%d", np->name, i); // 设置名字
}
}
else
{
/* pdev来自c文件
static struct resource omap16xx_gpio3_resources[] = {
{
.start = 115,
.end = 115,
.flags = IORESOURCE_IRQ,
},
{
.start = 118,
.end = 118,
.flags = IORESOURCE_IRQ,
}, };
*/
count = 0;
while (1)
{
/* 获取引脚 */
res = platform_get_resource(pdev, IORESOURCE_IRQ, count);
if (res)
{
count++;
}
else
{
break;
}
}
if (!count)
return -EINVAL;
/* 申请内存 */
gpios = kmalloc(count * sizeof(struct gpio_desc), GFP_KERNEL);
for (i = 0; i < count; i++)
{
res = platform_get_resource(pdev, IORESOURCE_IRQ, i); // 获取引脚
gpios[i].gpio = res->start; // 设置引脚
sprintf(gpios[i].name, "%s_pin_%d", pdev->name, i); // 设置名字
}
}
for (i = 0; i < count; i++)
{
/* 获取中断号 */
gpios[i].irq = gpio_to_irq(gpios[i].gpio);
/* 创建定时器 */
setup_timer(&gpios[i].demo_timer, demo_timer_expire, (unsigned long)&gpios[i]);
// timer_setup(&gpios[i].demo_timer, demo_timer_expire, 0);
/* 设置定时器超时时间 */
gpios[i].demo_timer.expires = ~0;
/* 添时器加定 */
add_timer(&gpios[i].demo_timer);
/* 注册中断 */
err = request_irq(gpios[i].irq, demo_isr, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "100ask_demo", &gpios[i]);
}
/* 注册file_operations */
major = register_chrdev(0, "100ask_demo", &demo_drv); /* /dev/gpio_desc */
gpio_class = class_create(THIS_MODULE, "100ask_demo_class");
if (IS_ERR(gpio_class)) {
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
unregister_chrdev(major, "100ask_demo");
return PTR_ERR(gpio_class);
}
device_create(gpio_class, NULL, MKDEV(major, 0), NULL, "100ask_demo"); /* /dev/100ask_demo */
return err;
}
/* 有入口函数就应该有出口函数:卸载驱动程序时,就会去调用这个出口函数
*/
static int gpio_drv_remove(struct platform_device *pdev)
{
int i;
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
device_destroy(gpio_class, MKDEV(major, 0));
class_destroy(gpio_class);
unregister_chrdev(major, "100ask_demo");
for (i = 0; i < count; i++)
{
free_irq(gpios[i].irq, &gpios[i]);
del_timer(&gpios[i].demo_timer);
}
return 0;
}
/* 设备树匹配结构体 */
static const struct of_device_id gpio_dt_ids[] = {
{ .compatible = "100ask,gpiodemo", },
{ /* sentinel */ }
};
static struct platform_driver gpio_platform_driver = {
.driver = {
.name = "100ask_gpio_plat_drv",
.of_match_table = gpio_dt_ids,
},
.probe = gpio_drv_probe,
.remove = gpio_drv_remove,
};
static int __init gpio_drv_init(void)
{
/* 注册platform_driver */
return platform_driver_register(&gpio_platform_driver);
}
static void __exit gpio_drv_exit(void)
{
/* 反注册platform_driver */
platform_driver_unregister(&gpio_platform_driver);
}
/* 7. 其他完善:提供设备信息,自动创建设备节点 */
module_init(gpio_drv_init);
module_exit(gpio_drv_exit);
MODULE_LICENSE("GPL");
demo_test.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <poll.h>
#include <signal.h>
static int fd;
/*
* ./demo_test /dev/100ask_demo
*
*/
int main(int argc, char **argv)
{
int val;
struct pollfd fds[1];
int flags;
int i;
/* 1. 判断参数 */
if (argc != 2)
{
printf("Usage: %s <dev>\n", argv[0]);
return -1;
}
/* 2. 打开文件 */
fd = open(argv[1], O_RDWR | O_NONBLOCK);
if (fd == -1)
{
printf("can not open file %s\n", argv[1]);
return -1;
}
for (i = 0; i < 10; i++)
{
if (read(fd, &val, 4) == 4)
printf("get demo: 0x%x\n", val);
else
printf("get demo: -1\n");
}
flags = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
while (1)
{
if (read(fd, &val, 4) == 4)
printf("get demo: 0x%x\n", val);
else
printf("while get demo: -1\n");
}
close(fd);
return 0;
}
Code language: PHP (php)
Makefile
# 1. 使用不同的开发板内核时, 一定要修改KERN_DIR
# 2. KERN_DIR中的内核要事先配置、编译, 为了能编译内核, 要先设置下列环境变量:
# 2.1 ARCH, 比如: export ARCH=arm64
# 2.2 CROSS_COMPILE, 比如: export CROSS_COMPILE=aarch64-linux-gnu-
# 2.3 PATH, 比如: export PATH=$PATH:/home/book/100ask_roc-rk3399-pc/ToolChain-6.3.1/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin
# 注意: 不同的开发板不同的编译器上述3个环境变量不一定相同,
# 请参考各开发板的高级用户使用手册
KERN_DIR = /home/book/100ask_imx6ull-sdk/Linux-4.9.88 # 板子所用内核源码的目录
all:
make -C $(KERN_DIR) M=`pwd` modules
$(CROSS_COMPILE)gcc -o demo_test demo_test.c
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.order demo_test
# 参考内核源码drivers/char/ipmi/Makefile
# 要想把a.c, b.c编译成ab.ko, 可以这样指定:
# ab-y := a.o b.o
# obj-m += ab.o
obj-m += demo_drv.o
Code language: PHP (php)
评论