【问题标题】:linux device driver container_of macro when using arrays使用数组时的linux设备驱动程序container_of宏
【发布时间】:2016-11-23 13:28:36
【问题描述】:

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

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 和其他与分配相关的调用。现在在带有签名int open(struct inode *inode, struct file *filp)open 文件操作中,我可以访问cdev 结构,因此可以访问inner_struct_containing_cdev。但我想获得指向outer_struct 的指针。在open 调用中,我不知道我收到了指向inner_struct_containing_cdev 结构的哪个数组索引。 在这种情况下可以使用container_of 宏吗?还是需要重新设计结构?

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

【问题讨论】:

    标签: c linux linux-kernel driver


    【解决方案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,然后当它启动单个设备时,它使每个指向该对象。使用核心内核的引用计数逻辑来了解何时释放它们。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2013-07-08
      相关资源
      最近更新 更多