PCIe驱动开发(3)— 驱动设备文件的创建与操作

news2024/9/24 17:13:01

PCIe驱动开发(3)— 驱动设备文件的创建与操作

一、前言

在 Linux 中一切皆为文件,驱动加载成功以后会在“/dev”目录下生成一个相应的文件,应用程序通过对这个名为“/dev/xxx” (xxx 是具体的驱动文件名字)的文件进行相应的操作即可实现对硬件的操作。

二、创建设备文件

PCIe设备属于字符设备,我们按如下步骤创建一个字符设备:

	/* 1、Request device number */
	ret = alloc_chrdev_region(&hello_pci_info.dev_id, 0, 1, "hello_pcie");
	
	/* 2、Initial char_dev */
	hello_pci_info.cdev.owner = THIS_MODULE;
	cdev_init(&hello_pci_info.char_dev, &hello_pci_fops);
	
	/* 3、add char_dev */
	cdev_add(&hello_pci_info.char_dev, hello_pci_info.dev_id, 1);

	/* 4、create class */
	hello_pci_info.class = class_create(THIS_MODULE, "hello_pcie");
	if (IS_ERR(hello_pci_info.class)) {
		return PTR_ERR(hello_pci_info.class);
	}

	/* 5、create device */
	hello_pci_info.device = device_create(hello_pci_info.class, NULL, hello_pci_info.dev_id, NULL, "hello_pcie");
	if (IS_ERR(newchrled.device)) {
		return PTR_ERR(newchrled.device);
	}

其中需要定义一个设备文件操作函数结构体,可以暂时定义为如下所示:

/* device file operations function */
static struct file_operations hello_pcie_fops = {
	.owner = THIS_MODULE,
};

将上述创建一个字符设备的操作加在hello_pci_init函数里,同时hello_pci_exit添加对应的卸载操作:

static void __exit hello_pci_exit(void)
{
	if(hello_pci_info.dev != NULL) {
		cdev_del(&hello_pci_info.char_dev);						/* del cdev */
		unregister_chrdev_region(hello_pci_info.dev_id, 1); 	/* unregister device number */

		device_destroy(hello_pci_info.class, hello_pci_info.dev_id);
		class_destroy(hello_pci_info.class);
	}
	
	pci_unregister_driver(&hello_pci_driver);
}

然后编译加载驱动,便可以看到在/dev下有我们创建的hello_pcie设备了:
在这里插入图片描述

三、添加文件操作函数

如下所示,添加文件的open,close,write,read函数:

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/cdev.h>
#include <linux/device.h>

#define HELLO_PCI_DEVICE_ID     0x11e8
#define HELLO_PCI_VENDOR_ID     0x1234
#define HELLO_PCI_REVISION_ID   0x10

static struct pci_device_id ids[] = {
    { PCI_DEVICE(HELLO_PCI_VENDOR_ID, HELLO_PCI_DEVICE_ID), },
    { 0 , }
};

static struct hello_pci_info_t {
    dev_t dev_id;
    struct cdev char_dev;
    struct class *class;
    struct device *device;
    struct pci_dev *dev;
    void __iomem *address_bar0;
    atomic_t compute_running;
	wait_queue_head_t r_wait;
} hello_pci_info;

MODULE_DEVICE_TABLE(pci, ids);

static irqreturn_t hello_pci_irq_handler(int irq, void *dev_info)
{
    struct hello_pci_info_t *_pci_info = dev_info;
    uint32_t irq_status;

    // get irq_stutas
    irq_status = *((uint32_t *)(_pci_info->address_bar0 + 0x24));
    printk("hello_pcie: get irq status: 0x%0x\n", irq_status);
    // clean irq
    *((uint32_t *)(_pci_info->address_bar0 + 0x64)) = irq_status;

    // get irq_stutas
    irq_status = *((uint32_t *)(_pci_info->address_bar0 + 0x24));
    if(irq_status == 0x00){
        printk("hello_pcie: receive irq and clean success. \n");
    }else{
        printk("hello_pcie: receive irq but clean failed !!! \n");
        return IRQ_NONE;
    }

    atomic_set(&(_pci_info->compute_running), 0);
    wake_up_interruptible(&(_pci_info->r_wait));

    return IRQ_HANDLED;
}

/*
 * @description     : 打开设备
 * @param - inode   : 传递给驱动的inode
 * @param - file    : 设备文件,file结构体有个叫做private_data的成员变量
 *                    一般在open的时候将private_data指向设备结构体。
 * @return          : 0 成功;其他 失败
 */
static int hello_pcie_open(struct inode *inode, struct file *file)
{
    printk("hello_pcie: open dev file.\n");

    init_waitqueue_head(&hello_pci_info.r_wait);

    return 0;
}

/*
 * @description     : 关闭/释放设备
 * @param - file    : 要关闭的设备文件(文件描述符)
 * @return          : 0 成功;其他 失败
 */
static int hello_pcie_close(struct inode *inode, struct file *file)
{
    printk("hello_pcie: close dev file.\n");

    return 0;
}



/*
 * @description     : 向设备写数据 
 * @param - filp    : 设备文件,表示打开的文件描述符
 * @param - buf     : 要写给设备写入的数据
 * @param - cnt     : 要写入的数据长度
 * @param - offt    : 相对于文件首地址的偏移
 * @return          : 写入的字节数,如果为负值,表示写入失败
 */
static ssize_t hello_pcie_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
    int retvalue;
    unsigned char databuf[4] = {0, 0, 0, 0};
    uint32_t compute_value;

    retvalue = copy_from_user(databuf, buf, cnt);
    if(retvalue < 0) {
        printk("hello_pcie: write failed!\n");
        return -EFAULT;
    }

    atomic_set(&hello_pci_info.compute_running, 1);

    compute_value = ((databuf[0]) | (databuf[1]<<8) | (databuf[2]<<16) | (databuf[3]<<24));
    *((uint32_t *)(hello_pci_info.address_bar0 + 0x08)) = compute_value;

    return 0;
}

/*
 * @description     : 从设备读取数据 
 * @param – filp    : 要打开的设备文件(文件描述符)
 * @param – buf     : 返回给用户空间的数据缓冲区
 * @param – cnt     : 要读取的数据长度
 * @param – offt    : 相对于文件首地址的偏移
 * @return          : 读取的字节数,如果为负值,表示读取失败
 */
static ssize_t hello_pcie_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
{
    int ret;
    uint32_t compute_result = 0;

    /* 加入等待队列,当有按键按下或松开动作发生时,才会被唤醒 */
    ret = wait_event_interruptible(hello_pci_info.r_wait, 0 == atomic_read(&hello_pci_info.compute_running));
    if(ret)
        return ret;

    compute_result = *((uint32_t *)(hello_pci_info.address_bar0 + 0x08));
    printk("hello_pcie: get compute_result: %0d\n", compute_result);

    /* 将按键状态信息发送给应用程序 */
    ret = copy_to_user(buf, &compute_result, sizeof(int));

    return ret;
}

/* device file operations function */
static struct file_operations hello_pcie_fops = {
    .owner      = THIS_MODULE,
    .open       = hello_pcie_open,
    .release    = hello_pcie_close,
    .read       = hello_pcie_read,
    .write      = hello_pcie_write,
};


static int hello_pcie_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
    int bar = 0;
    int ret;
    resource_size_t len;
    
    ret = pci_enable_device(dev);
    if(ret) {
        return ret;
    }
    
    len = pci_resource_len(dev, bar);
    hello_pci_info.address_bar0 = pci_iomap(dev, bar, len);
    hello_pci_info.dev = dev;
    
    // register interrupt
    ret = request_irq(dev->irq, hello_pci_irq_handler, IRQF_SHARED, "hello_pci", &hello_pci_info);
    if(ret) {
        printk("request IRQ failed.\n");
        return ret;
    }
    // enable irq for finishing factorial computation
    *((uint32_t *)(hello_pci_info.address_bar0 + 0x20)) = 0x80;
    
    return 0;
}

static void hello_pcie_remove(struct pci_dev *dev)
{
    // disable irq for finishing factorial computation
    *((uint32_t *)(hello_pci_info.address_bar0 + 0x20)) = 0x01;
    
    free_irq(dev->irq, &hello_pci_info);
    
    pci_iounmap(dev, hello_pci_info.address_bar0);
    
    pci_disable_device(dev);
}


static struct pci_driver hello_pci_driver = {
    .name       = "hello_pcie",
    .id_table   = ids,
    .probe      = hello_pcie_probe,
    .remove     = hello_pcie_remove,
};

static int __init hello_pci_init(void)
{
    int ret = pci_register_driver(&hello_pci_driver);

    if(hello_pci_info.dev == NULL){
        printk("hello_pci: probe pcie device failed!\n");
        return ret;
    }

    /* 1、Request device number */
    ret = alloc_chrdev_region(&hello_pci_info.dev_id, 0, 1, "hello_pcie");
    
    /* 2、Initial char_dev */
    hello_pci_info.char_dev.owner = THIS_MODULE;
    cdev_init(&hello_pci_info.char_dev, &hello_pcie_fops);
    
    /* 3、add char_dev */
    cdev_add(&hello_pci_info.char_dev, hello_pci_info.dev_id, 1);

    /* 4、create class */
    hello_pci_info.class = class_create(THIS_MODULE, "hello_pcie");
    if (IS_ERR(hello_pci_info.class)) {
        return PTR_ERR(hello_pci_info.class);
    }

    /* 5、create device */
    hello_pci_info.device = device_create(hello_pci_info.class, NULL, hello_pci_info.dev_id, NULL, "hello_pcie");
    if (IS_ERR(hello_pci_info.device)) {
        return PTR_ERR(hello_pci_info.device);
    }
    
    return ret;
}

static void __exit hello_pci_exit(void)
{
    if(hello_pci_info.dev != NULL) {
        cdev_del(&hello_pci_info.char_dev);                     /* del cdev */
        unregister_chrdev_region(hello_pci_info.dev_id, 1);     /* unregister device number */

        device_destroy(hello_pci_info.class, hello_pci_info.dev_id);
        class_destroy(hello_pci_info.class);
    }
    
    pci_unregister_driver(&hello_pci_driver);
}


module_init(hello_pci_init);
module_exit(hello_pci_exit);
MODULE_LICENSE("GPL");
MODULE_INFO(intree, "Y");


四、编写用户程序

编写用户测试程序testapp.c如下:

#include "stdio.h"
#include "stdint.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"

int main(int argc, char *argv[])
{
    int fd, retvalue;
    char *filename = "/dev/hello_pcie";
    uint32_t data_val = 6;
    int read_val;

    /* 打开驱动设备文件 */
    fd = open(filename, O_RDWR);
    if(fd < 0){
        printf("file %s open failed!\n", filename);
        return -1;
    }

    /* 向/dev/hello_pcie文件写入数据 */
    retvalue = write(fd, &data_val, sizeof(int));
    if(retvalue < 0){
        printf("Open %s Failed!\n", filename);
        close(fd);
        return -1;
    }

    read(fd, &read_val, sizeof(int));
    printf("factorial computation result : %0d \n", read_val);

    retvalue = close(fd); /* 关闭文件 */
    if(retvalue < 0){
        printf("file %s close failed!\r\n", filename);
        return -1;
    }

    return 0;
}


五、运行测试

编译加载驱动,
在这里插入图片描述
使用如下命令编译测试程序:

gcc testapp.c 

然后运行测试程序,我们可以看到计算得到的阶乘结果为720,即6*5*4*3*2*1=720,符合预期结果
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1932056.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Azure Repos 仓库管理

从远端仓库克隆到本地 前提:本地要安装git,并且登录了账户 1.在要放这个远程仓库的路径下,打git 然后 git clone https://.. 如果要登录验证,那就验证下,点 generate git credentials,复制password 克隆完后,cd 到克隆的路径, 可以用 git branch -a //查看分…

Spring Cloud环境搭建

&#x1f3a5; 个人主页&#xff1a;Dikz12&#x1f525;个人专栏&#xff1a;Spring学习之路&#x1f4d5;格言&#xff1a;吾愚多不敏&#xff0c;而愿加学欢迎大家&#x1f44d;点赞✍评论⭐收藏 目录 1. 开发环境安装 1.1 安装JDK ​1.2 安装MySQL 2. 案列介绍 2.1 …

Linux 命令 —— top命令(查看进程资源占用)

文章目录 top 命令显示信息介绍top 命令使用 top 命令显示信息介绍 top 命令是 Linux/Unix 系统中常用的进程监控工具&#xff0c;可以实时动态显示系统中各个进程的资源占用情况&#xff0c;包括CPU、内存等。 进入 linux 系统&#xff0c;直接输入 top&#xff0c;回车&…

全网超详细Redis主从部署(附出现bug原因)

主从部署 整体架构图 需要再建两个CentOs7,过程重复单机部署 http://t.csdnimg.cn/zkpBE http://t.csdnimg.cn/lUU5gLinux环境下配置redis 查看自己ip地址命令 ifconfig 192.168.187.137 进入redis所在目录 cd /opt/software/redis cd redis-stable 进入配置文件 vim redi…

书生大模型第三关-Git基础

1.任务1: 破冰活动&#xff1a;自我介绍 目标&#xff1a; 每位参与者提交一份自我介绍。 提交地址&#xff1a;https://github.com/InternLM/Tutorial 的 camp3 分支&#xff5e; 行动&#xff1a; 首先Fork项目到自己Repo中&#xff0c;然后git clone在本地上 然后创建一个…

liunx面试题目

如何看当前Linux系统有几颗物理CPU和每颗CPU的核数&#xff1f; 查看物理cup&#xff1a; cat /proc/cpuinfo|grep -c ‘physical id’ 查看每颗cup核数 cat /proc/cpuinfo|grep -c ‘processor’ 若希望自动实现软件包的更新&#xff0c;可以使用yum-cron并启动该服务 yum -y …

【java计算机毕设】农产品仓库管理系统系统MySQL ssm JSP maven项目代码+文档 前后端一体 暑假作业

目录 1项目功能 2项目介绍 3项目地址 1项目功能 【java计算机毕设】农产品仓库管理系统系统MySQL ssm vue maven项目代码文档 前后端一体 暑假作业 2项目介绍 系统功能&#xff1a; 农产品仓库管理包括管理员、用户俩种角色。 管理员功能包括个人中心模块用于修改个人信息和…

60K起?“软件安全岗”比“网络安全岗”薪资高在哪里?

在网络世界的江湖中&#xff0c;“软件安全”与“网络安全”这两大“武林高手”都肩负着守护数字领域和平的重任。不过&#xff0c;眼尖的小伙伴们可能发现了&#xff0c;软件安全岗位的薪资待遇往往比网络安全岗位要丰厚那么一些&#xff0c;这到底是为啥呢&#xff1f;今天&a…

【AI绘画教程】Stable Diffusion 1.5 vs 2

在本文中,我们将总结稳定扩散 1 与稳定扩散 2 辩论中的所有要点。我们将在第一部分中查看这些差异存在的实际原因,但如果您想直接了解实际差异,您可以跳下否定提示部分。让我们开始吧! Stable Diffusion 2.1 发布与1.5相比,2.1旨在解决2.0的许多相对缺点。本文的内容与理解…

数字化转型“破局”:低代码开发平台如何缩短开发交付周期,提升效率

日新月异的数字时代&#xff0c;各行业正经历着前所未有的变革与转型。随着大数据、云计算、人工智能等技术的不断成熟与融合&#xff0c;数字化转型的步伐愈发坚定而迅速&#xff0c;成为企业转型升级、实现可持续发展的必由之路。然而&#xff0c;传统的软件开发模式受限于高…

35.UART(通用异步收发传输器)-RS232(2)

&#xff08;1&#xff09;RS232接收模块visio框图&#xff1a; &#xff08;2&#xff09;接收模块Verilog代码编写: /* 常见波特率&#xff1a; 4800、9600、14400、115200 在系统时钟为50MHz时&#xff0c;对应计数为&#xff1a; (1/4800) * 10^9 /20 -1 10416 …

如何防止漏洞攻击

随着信息技术的日新月异&#xff0c;企业在日常运营中对网络和数字化系统的依赖日益加深。然而&#xff0c;这种高度依赖也伴随着网络安全威胁的急剧增长&#xff0c;对企业的核心资产与数据构成了严峻挑战。为了有效捍卫企业利益&#xff0c;确保运营无忧&#xff0c;积极构建…

Monaco 使用 DocumentHighlightProvider

Monaco 中有一个文字高亮的功能&#xff0c;就是选中一个单词&#xff0c;会高亮文字文档中所有出现该单词的位置&#xff0c;效果如下&#xff1a; Monaco 默认就有这个功能&#xff0c;可以根据具体需求进行定制。通过 registerDocumentHighlightProvider 进行注册 实现 pro…

无人机之图传距离的决定因素

一、发射功率&#xff1a;图传设备的发射功率越大&#xff0c;信号能够传播的距离就越远 二、工作频段&#xff1a;不同频段具有不同的传播特性&#xff0c;一些频段在相同条件下可能具有更远的传输距离。 三、天线性能&#xff1a;优质的天线可以增强信号的发送和接收能力&a…

9.11和9.9哪个数更大?所有模型测试

目录 通义千问2.5 通义千问2_0.5b kimi 智谱清言 ​编辑讯飞星火 秘塔搜索 文言一心 豆包 腾讯元宝 海螺AI ChatGPT 3.5 Gemini 1.0 通义千问72B Claude-3 天工AI 参赛选手&#xff1a;讯飞星火、文言一心、腾讯元宝、海螺AI、通义千问72B、天工AI、 通义千问2…

实验七:图像的复原处理

一、实验目的 熟悉常见的噪声及其概率密度函数。熟悉在实际应用中比较重要的图像复原技术,会对退化图像进行复原处理。二、实验原理 1. 图像复原技术,说简单点,同图像增强那样,是为了以某种预定义的方式来改进图像。在具体操作过程中用流程图表示,其过程就如下面所示: 2…

git查看历史记录方法

0 Preface/Foreword 1 git reflog git reflog显示所有的操作&#xff0c;不仅仅是commit&#xff0c;也包括git pull&#xff0c;checout等动作。 1.1 查看本地和远程仓库的区别 远程仓库&#xff1a;中间的提交是直接在web端编辑 远程仓库&#xff1a;最新的提交是在本地编…

在golang中Sprintf和Printf 的区别

最近一直在学习golang这个编程语言&#xff0c;我们这里做一个笔记就是 Sprintf和Printf 的区别 fmt.Sprintf 根据格式化参数生成格式化的字符串并返回该字符串。 fmt.Printf 根据格式化参数生成格式化的字符串并写入标准输出。由上面就可以知道&#xff0c;fmt.Sprintf返回的…

爬虫(二)——爬虫的伪装

前言 本文是爬虫系列的第二篇文章&#xff0c;主要讲解关于爬虫的简单伪装&#xff0c;以及如何爬取B站的视频。建议先看完上一篇文章&#xff0c;再来看这一篇文章。要注意的是&#xff0c;本文介绍的方法只能爬取免费视频&#xff0c;会员视频是无法爬取的哦。 爬虫的伪装 …

leetcode-三数之和

视频&#xff1a;https://www.bilibili.com/video/BV1bP411c7oJ/?spm_id_from333.788&vd_sourcedd84879fcf1be72f360461b01ecab0d6 从两数之和开始&#xff0c;排序后的两数之和&#xff0c;利用好升序的性质&#xff0c;可以将时间复杂度从on2降到on; class Solution …