使用数组

时间:2016-11-23 13:28:36

标签: c linux linux-kernel driver

在我使用的其中一个遗留设备驱动程序中,我的结构格式如下 -

struct inner_struct_containing_cdev {
   struct cdev cdev;
   ....
   ....
   /* more variables */
};

struct outer_struct {
    /* because I need 10 devices */
    struct inner_struct_containing_cdev inner[10];
    ....
    ....
    /* more variables which are common to all the 10 devices. */
};

现在在我的init_module中,我正在调用alloc_chrdev_region和其他与分配相关的调用。现在,在我的open文件操作中,签名为int open(struct inode *inode, struct file *filp),我可以访问cdev结构,从而访问inner_struct_containing_cdev。但我希望得到指向outer_struct的指针。在open调用中,我不知道我收到指针的inner_struct_containing_cdev结构的哪个数组索引。 在这种情况下是否可以使用container_of宏?或者需要重新设计结构?

目前我正在使用全局变量来处理这种情况。但这阻止了我进行多次实例化。

1 个答案:

答案 0 :(得分:1)

您无法使用container_ofinner_struct_containing_cdev转到outer_struct;你自己说明了这个原因,你不知道你正在看哪个阵列的索引。

您需要组织这样的数据结构:

 struct driver_instance {
    /* variables shared among all N devices go here */
 };

 struct device_instance {
    struct cdev cdev;
    /* variables particular to only one device */
    struct driver_instance *driver;
 };

您只能使用container_ofcdev转到device_instance;然后取消引用driver指针以获取driver_instance。在初始化驱动程序时分配driver_instance,然后当它旋转单个设备时,它会使每个指向该对象。使用核心内核的引用计数逻辑来知道何时解除分配它们。

除了这个,你知道,工作之外,这意味着你不必在编译时硬连接设备的数量。

相关问题