写个 linux的pci驱动
时间: 2023-08-09 18:05:22 浏览: 78
下面是一个简单的Linux PCI驱动程序示例。该驱动程序将为PCI设备分配一个中断,并在中断处理程序中打印一条消息。
```c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
static int my_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
int err;
printk(KERN_INFO "my_pci: probing PCI device %04x:%04x\n",
dev->vendor, dev->device);
if ((err = pci_enable_device(dev))) {
printk(KERN_ERR "my_pci: failed to enable PCI device\n");
return err;
}
if ((err = pci_request_regions(dev, "my_pci"))) {
printk(KERN_ERR "my_pci: failed to request PCI regions\n");
goto err_disable_pci;
}
if ((err = pci_enable_msi(dev))) {
printk(KERN_ERR "my_pci: failed to enable MSI\n");
goto err_release_regions;
}
return 0;
err_release_regions:
pci_release_regions(dev);
err_disable_pci:
pci_disable_device(dev);
return err;
}
static void my_pci_remove(struct pci_dev *dev)
{
printk(KERN_INFO "my_pci: removing PCI device %04x:%04x\n",
dev->vendor, dev->device);
pci_disable_msi(dev);
pci_release_regions(dev);
pci_disable_device(dev);
}
static irqreturn_t my_pci_interrupt(int irq, void *dev_id)
{
struct pci_dev *dev = (struct pci_dev *)dev_id;
printk(KERN_INFO "my_pci: got interrupt from PCI device %04x:%04x\n",
dev->vendor, dev->device);
return IRQ_HANDLED;
}
static const struct pci_device_id my_pci_id_table[] = {
{ PCI_DEVICE(0x1234, 0x5678) },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, my_pci_id_table);
static struct pci_driver my_pci_driver = {
.name = "my_pci",
.id_table = my_pci_id_table,
.probe = my_pci_probe,
.remove = my_pci_remove,
};
static int __init my_pci_init(void)
{
int err;
printk(KERN_INFO "my_pci: initializing PCI driver\n");
if ((err = pci_register_driver(&my_pci_driver))) {
printk(KERN_ERR "my_pci: failed to register PCI driver\n");
return err;
}
return 0;
}
static void __exit my_pci_exit(void)
{
printk(KERN_INFO "my_pci: exiting PCI driver\n");
pci_unregister_driver(&my_pci_driver);
}
module_init(my_pci_init);
module_exit(my_pci_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple PCI driver example");
```
在该驱动程序中,我们定义了一个`pci_driver`结构体,该结构体包含了驱动程序的名称、ID表、探测函数、移除函数等信息。在探测函数中,我们启用了PCI设备、请求了PCI区域、启用了MSI中断等操作。在移除函数中,我们释放了PCI区域、禁用了MSI中断、禁用了PCI设备等操作。在中断处理程序中,我们简单地打印了一条消息。此外,我们使用了`MODULE_DEVICE_TABLE`宏和`pci_device_id`结构体来定义PCI设备的ID表。最后,我们定义了一个模块初始化函数和一个模块退出函数,并使用`module_init`和`module_exit`宏将它们注册到内核中。
阅读全文