PCIe驱动开发(3)— 驱动设备文件的创建与操作
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
设备了: