我正在为 PCIE 硬件开发 Linux 驱动程序。内核是
v4.13
。
对于每个设备对象,都有一堆用 pci_set_drvdata(struct pci_dev *pdev, void *data)
存储的数据。
在
IOCtl()
服务例程中,如何使用struct file * pFile
取回数据?
long IOCtlService(struct file * pFile, unsigned int cmd, unsigned long arg)
谢谢
如果您有不止一台设备,您可能会使用 IDR 来分配和跟踪次要开发节点 ID。对
idr_alloc
的调用接受一个指针来存储 ID 以供将来使用。
在 ioctl 处理程序中,您可以使用
idr_find
从 idr 查找指针。例如:
分配 IDR 并用它存储
info
全局定义
DEFINE_MUTEX(minor_lock);
DEFINE_IDR(mydev_idr);
在您的 PCI 探针处理程序中
struct my_dev * info;
info = kzalloc(sizeof(struct mydev_info), GFP_KERNEL);
if (!info)
return -ENOMEM;
mutex_lock(&minor_lock);
info->minor = idr_alloc(&mydev_idr, info, 0, MYDEV_MAX_DEVICES, GFP_KERNEL);
if (info->minor < 0)
{
mutex_unlock(&minor_lock);
goto out_unreg;
}
mutex_unlock(&minor_lock);
pci_set_drvdata(dev, info);
从IDR中查找存储的指针
unsigned minor = iminor(flip->f_inode);
struct my_dev * dev = (struct my_dev *)idr_find(&mydev_idr, minor);
if (!dev)
return -EINVAL;
确保在删除设备时释放您的 IDR
mutex_lock(&minor_lock);
idr_remove(&mydev_idr, info->minor);
mutex_unlock(&minor_lock);
使用
ioctl()
驱动程序将接受命令并按这些命令工作
ioctl(fd, cmd , INPARAM or OUTPARAM);
如何使用 struct file * pFile 取回数据?您想执行什么操作?为此,您可以使用
ioctl.h
中提供的命令。
例如 IOR
(如果命令需要从内核读取一些东西
空间)
struct file
也有 private_data
,因此您可以将 pci_dev
存储在那里,就像 struct miscdev
的作用一样:
static int misc_open(struct inode *inode, struct file *file)
{
......
struct miscdevice *c;
......
/*
* Place the miscdevice in the file's
* private_data so it can be used by the
* file operations, including f_op->open below
*/
file->private_data = c;
}