跳转至

01.字符设备驱动开发框架

驱动就是获取原始数据,原始数据会提交给应用程序。linux开发一般包含应用程序和驱动程序。我们的驱动很多时候只是提供功能,策略由应用实现。

旧设备驱动基本框架

框架思路

1、注册一个设备操作函数结构体 struct file_operations,并注册内部函数。

2、编写入口函数,在这个里面注册设备,并将前面定义的file_operations结构体传入注册函数。

3、编写出口函数,将设备注销。

4、其他,可以在入口函数的时候,自动分配设备节点,这样就不用加载驱动后再写命令分配,自动分配节点需要创建类后创建设备节点。再出口函数的时候记得删除类和设备节点。

驱动代码

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

#define HELLO_DEV_MAJOR        200
#define HELLO_DEV_NAME         "hello"
#define HELLO_DEV_CLASS_NAME   "hello_class"
#define HELLO_DEV_NODE_NAME    "hello" 

struct hello_dev{       
    struct class *class;        
    struct device *device;  
    int major;              
    int minor;              
};

struct hello_dev hello; /* led设备 */

static char kernel_buf[1024];
#define MIN(a, b) (a < b ? a : b)

static int hello_drv_open(struct inode *inode, struct file *file)
{
    printk("%s %s line %d\r\n", __FILE__, __FUNCTION__, __LINE__);
    return 0;
}

static ssize_t hello_drv_read(struct file *file, char __user *buf, size_t size, loff_t *offset)
{
    int err;
    printk("%s %s line %d\r\n", __FILE__, __FUNCTION__, __LINE__);
    err = copy_to_user(buf, kernel_buf, MIN(1024, size));
    return MIN(1024, size);
}

static ssize_t hello_drv_write(struct file *file, const char __user *buf, size_t size, loff_t *offset)
{
    int err;
    printk("%s %s line %d\r\n", __FILE__, __FUNCTION__, __LINE__);
    err = copy_from_user(kernel_buf, buf, MIN(1024, size));
    return MIN(1024, size);
}

static int hello_drv_release(struct inode *inode, struct file *file)
{
    printk("%s %s line %d\r\n", __FILE__, __FUNCTION__, __LINE__);
    return 0;
}

static struct file_operations hello_drv_fops = {
    .owner = THIS_MODULE,   
    .open = hello_drv_open,
    .read = hello_drv_read,
    .write = hello_drv_write,
    .release = hello_drv_release,
};

static int __init hello_drv_init(void)
{
    int ret;
    printk("%s %s line %d\r\n", __FILE__, __FUNCTION__, __LINE__);

    ret = register_chrdev(HELLO_DEV_MAJOR, HELLO_DEV_NAME, &hello_drv_fops);

    if(ret < 0){
        printk("hello driver register failed\r\n");
        return ret;
    }

    if(0 == HELLO_DEV_MAJOR)
    {
        hello.major = ret;
    }else
    {
        hello.major = HELLO_DEV_MAJOR;
    }
    printk("hello.major = %d\r\n",hello.major);

    //创建类
    hello.class = class_create(THIS_MODULE, HELLO_DEV_CLASS_NAME);
    if (IS_ERR(hello.class)) {
        return PTR_ERR(hello.class);
    }
    //创建设备
    hello.device = device_create(hello.class, NULL, MKDEV(hello.major, 0), NULL, HELLO_DEV_NODE_NAME); 
    if (IS_ERR(hello.device)) {
        return PTR_ERR(hello.device);
    }
    return 0;
}

static void __exit hello_drv_exit(void)
{
    printk("%s %s line %d\r\n", __FILE__, __FUNCTION__, __LINE__);
    unregister_chrdev(hello.major, HELLO_DEV_NAME);

    //删除类、删除设备
    device_destroy(hello.class, MKDEV(hello.major, 0));
    class_destroy(hello.class);
}

module_init(hello_drv_init);
module_exit(hello_drv_exit);

MODULE_LICENSE("GPL");

注意register_chrdev这个API如果将设备号处填为0,就会自己分配设备号,并将设备号返回。如果是给定的设备号,如果成功,就返回0。

makefile文件

KERNELDIR := /home/lqh/linux/imx6ull/linux-imx-alientek
CURRENT_PATH := $(shell pwd)

obj-m := hello_drv.o

build: kernel_modules

kernel_modules:
    $(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules

clean:
    $(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean

应用代码

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

/*
 * ./hello_drv_test -w abc
 * ./hello_drv_test -r
 */
int main(int argc, char **argv)
{
    int fd;
    char buf[1024];
    int len;

    /* 1. 判断参数 */
    if (argc < 2)
    {
        printf("Usage: %s -w <string>\n", argv[0]);
        printf(" %s -r\n", argv[0]);
        return -1;
    }

    /* 2. 打开文件 */
    fd = open("/dev/hello", O_RDWR);
    if (fd == -1)
    {
        printf("can not open file /dev/hello\n");
        return -1;
    }

    /* 3. 写文件或读文件 */
    if ((0 == strcmp(argv[1], "-w")) && (argc == 3))
    {
        len = strlen(argv[2]) + 1;
        len = len < 1024 ? len : 1024;
        write(fd, argv[2], len);
    }
    else
    {
        len = read(fd, buf, 1024);
        buf[1023] = '\0';
        printf("APP read : %s\n", buf);
    }

    close(fd);

    return 0;
}

应用程序编译

arm-linux-gnueabihf-gcc hello_drv_app.c -o hello_drv_app

旧设备驱动加载

使用之前配置好了的nfs

sudo cp hello.ko hello /home/lqh/linux/nfs/rootfs/lib/modules/4.1.15/ -f

然后加载驱动文件

insmod hello.ko

或者

modprobe hello.ko #这个可能需要输入depmod生成“modules.dep”

lsmod可以查看有哪些模块。cat /proc/devices可以查看当前已有设备

创建设备节点文件,“c”表示这是个字符设备,“200”是设备的主设备号,“0”是设备的次设备号。如果代码中写了自动创建,就不需要这一步了。

mknod /dev/hello c 200 0

卸载驱动模块

rmmod hello.ko

例子 LED 字符设备的驱动

主要思路需要修改的就是在init的时候加一个io的虚拟地址映射,然后就是控制io。然后在write的时候,修改io虚拟映射寄存器的相关值。

主要与上面不同的相关代码,除了把所有的hello改成了led,还有其他的修改如下。

驱动代码

/* 寄存器物理地址 */
#define CCM_CCGR1_BASE              (0X020C406C)    
#define SW_MUX_GPIO1_IO03_BASE      (0X020E0068)
#define SW_PAD_GPIO1_IO03_BASE      (0X020E02F4)
#define GPIO1_DR_BASE               (0X0209C000)
#define GPIO1_GDIR_BASE             (0X0209C004)

/* 映射后的寄存器虚拟地址指针 */
static void __iomem *IMX6U_CCM_CCGR1;
static void __iomem *SW_MUX_GPIO1_IO03;
static void __iomem *SW_PAD_GPIO1_IO03;
static void __iomem *GPIO1_DR;
static void __iomem *GPIO1_GDIR;

#define LEDOFF  0               /* 关灯 */
#define LEDON   1               /* 开灯 */

void led_switch(uint8_t sta)
{
    uint32_t val = 0;
    if(sta == LEDON) {
        val = readl(GPIO1_DR);
        val &= ~(1 << 3);   
        writel(val, GPIO1_DR);
    }else if(sta == LEDOFF) {
        val = readl(GPIO1_DR);
        val|= (1 << 3); 
        writel(val, GPIO1_DR);
    }   
}

static ssize_t led_drv_write(struct file *file, const char __user *buf, size_t size, loff_t *offset)
{
    int err;
    char val;
    printk("%s %s line %d\r\n", __FILE__, __FUNCTION__, __LINE__);
    err = copy_from_user(&val, buf, 1);
    if(LEDON == val)
    {
        led_switch(LEDON);
    }else 
    {
        led_switch(LEDOFF);
    }
    return 0;
}


void led_io_init(void)
{
    uint32_t val = 0;
    /* 初始化LED */
    /* 1、寄存器地址映射 */
    IMX6U_CCM_CCGR1   = ioremap(CCM_CCGR1_BASE, 4);
    SW_MUX_GPIO1_IO03 = ioremap(SW_MUX_GPIO1_IO03_BASE, 4);
    SW_PAD_GPIO1_IO03 = ioremap(SW_PAD_GPIO1_IO03_BASE, 4);
    GPIO1_DR          = ioremap(GPIO1_DR_BASE, 4);
    GPIO1_GDIR        = ioremap(GPIO1_GDIR_BASE, 4);

    /* 2、使能GPIO1时钟 */
    val = readl(IMX6U_CCM_CCGR1);
    val &= ~(3 << 26);  /* 清楚以前的设置 */
    val |= (3 << 26);   /* 设置新值 */
    writel(val, IMX6U_CCM_CCGR1);

    /* 3、设置GPIO1_IO03的复用功能,将其复用为
     *    GPIO1_IO03,最后设置IO属性。
     */
    writel(5, SW_MUX_GPIO1_IO03);

    /*寄存器SW_PAD_GPIO1_IO03设置IO属性
     *bit 16:0 HYS关闭
     *bit [15:14]: 00 默认下拉
     *bit [13]: 0 kepper功能
     *bit [12]: 1 pull/keeper使能
     *bit [11]: 0 关闭开路输出
     *bit [7:6]: 10 速度100Mhz
     *bit [5:3]: 110 R0/6驱动能力
     *bit [0]: 0 低转换率
     */
    writel(0x10B0, SW_PAD_GPIO1_IO03);

    /* 4、设置GPIO1_IO03为输出功能 */
    val = readl(GPIO1_GDIR);
    val &= ~(1 << 3);   /* 清除以前的设置 */
    val |= (1 << 3);    /* 设置为输出 */
    writel(val, GPIO1_GDIR);

    /* 5、默认关闭LED */
    val = readl(GPIO1_DR);
    val |= (1 << 3);    
    writel(val, GPIO1_DR);
}

static int __init led_drv_init(void)
{
    int ret;
    led_io_init();
    /*字符设备注册*/
}

应用代码

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#define LEDOFF  0
#define LEDON   1

/*
 * ./led_drv_app on
 * ./led_drv_app off
 */
int main(int argc, char **argv)
{
    int fd;
    char buf[1];
    int len;

    /* 1. 判断参数 */
    if (argc < 2)
    {
        printf("Usage: \n");
        printf(" %s on\n", argv[0]);
        printf(" %s off\n", argv[0]);
        return -1;
    }

    /* 2. 打开文件 */
    fd = open("/dev/led", O_RDWR);
    if (fd == -1)
    {
        printf("can not open file /dev/led\n");
        return -1;
    }

    /* 3. 写文件 */
    if ((0 == strcmp(argv[1], "on")) && (argc == 2))
    {
        buf[0] = LEDON;
        write(fd, buf , 1);
    }
    else
    {
        buf[0] = LEDOFF;
        write(fd, buf , 1);
    }

    close(fd);

    return 0;
}

应用程序编译

arm-linux-gnueabihf-gcc led_drv_app.c -o led_drv_app

新设备驱动基本框架

#define NEWCHRLED_CNT           1           /* 设备号个数 */
#define NEWCHRLED_NAME          "newchrled" /* 名字 */

/* newchrled设备结构体 */
struct newchrled_dev{
    dev_t devid;            /* 设备号   */
    struct cdev cdev;       /* cdev     */
    struct class *class;        /* 类        */
    struct device *device;  /* 设备    */
    int major;              /* 主设备号   */
    int minor;              /* 次设备号   */
};

struct newchrled_dev newchrled; /* led设备 */

static int led_open(struct inode *inode, struct file *filp)
{
    filp->private_data = &newchrled; /* 设置私有数据 */
    return 0;
}

static ssize_t led_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
{
    return 0;
}

static ssize_t led_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
    return 0;
}

static int led_release(struct inode *inode, struct file *filp)
{
    return 0;
}

/* 设备操作函数 */
static struct file_operations newchrled_fops = {
    .owner = THIS_MODULE,
    .open = led_open,
    .read = led_read,
    .write = led_write,
    .release =  led_release,
};

static int __init led_init(void)
{
    /* 注册字符设备驱动 */
    /* 1、创建设备号 */
    if (newchrled.major) {      /*  定义了设备号 */
        newchrled.devid = MKDEV(newchrled.major, 0);
        register_chrdev_region(newchrled.devid, NEWCHRLED_CNT, NEWCHRLED_NAME);
    } else {                        /* 没有定义设备号 */
        alloc_chrdev_region(&newchrled.devid, 0, NEWCHRLED_CNT, NEWCHRLED_NAME);    /* 申请设备号 */
        newchrled.major = MAJOR(newchrled.devid);   /* 获取分配号的主设备号 */
        newchrled.minor = MINOR(newchrled.devid);   /* 获取分配号的次设备号 */
    }

    /* 2、初始化cdev */
    newchrled.cdev.owner = THIS_MODULE;
    cdev_init(&newchrled.cdev, &newchrled_fops);

    /* 3、添加一个cdev */
    cdev_add(&newchrled.cdev, newchrled.devid, NEWCHRLED_CNT);

    /* 4、创建类 */
    newchrled.class = class_create(THIS_MODULE, NEWCHRLED_NAME);
    if (IS_ERR(newchrled.class)) {
        return PTR_ERR(newchrled.class);
    }

    /* 5、创建设备 */
    newchrled.device = device_create(newchrled.class, NULL, newchrled.devid, NULL, NEWCHRLED_NAME);
    if (IS_ERR(newchrled.device)) {
        return PTR_ERR(newchrled.device);
    }

    return 0;
}

static void __exit led_exit(void)
{
    /* 注销字符设备驱动 */
    cdev_del(&newchrled.cdev);/*  删除cdev */
    unregister_chrdev_region(newchrled.devid, NEWCHRLED_CNT); /* 注销设备号 */

    device_destroy(newchrled.class, newchrled.devid);
    class_destroy(newchrled.class);
}

module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("liqinghua");

创建类就是在使用mdev自动创建节点

新设备驱动加载

加载方式和旧的加载方式是一样的

depmod #第一次加载驱动的时候需要运行此命令
modprobe newchrled.ko #加载驱动
ls /dev/newchrled -l  #检查节点设备是否存在
rmmod newchrled.ko    #卸载节点设备