linux 设备驱动程序 container_of 使用数组时的宏

linux device driver container_of macro when using arrays

在我使用的旧版设备驱动程序之一中,我的结构格式如下 -

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 宏?或者需要重新设计结构?

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

您不能使用 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_ofcdevdevice_instance;然后取消引用 driver 指针以获取 driver_instance。您在初始化驱动程序时分配一个 driver_instance ,然后当它启动各个设备时,它使每个指向该对象。使用核心内核的引用计数逻辑来了解何时释放它们。

除了这个,你知道,有效,这意味着你不必在编译时硬连接设备数量。