0

刚开始学习linux内核,看平台设备内核代码的时候很迷茫,为什么不直接把device作为platform_device struct的第一个成员,而是使用to_platform_device(),转移到struct start呢?

struct platform_device {
    const char  * name;
    int     id;
    struct device   dev;
    u32     num_resources;
    struct resource * resource;

    const struct platform_device_id *id_entry;

    /* MFD cell pointer */
    struct mfd_cell *mfd_cell;

    /* arch specific additions */
    struct pdev_archdata    archdata;
};

#define to_platform_device(x) container_of((x), struct platform_device, dev)
4

2 回答 2

1

从 /Documentation/driver-api/driver-model/overview.rst :

另请注意,该 struct device dev 不一定在 pci_dev 结构的前面定义。这是为了让人们在总线驱动程序和全局驱动程序之间切换时思考他们在做什么,并阻止两者之间的无意义和不正确的转换。

于 2021-01-28T13:26:14.100 回答
0

主要是便携性。您不控制结构定义,它可能会在后续版本的 linux 内核中发生变化。而且,如果您首先依赖开发人员,那么设备将突然在内核的更新版本上中断。

container_of 是一个常量表达式,因此它是在编译时计算的,并且没有任何开销。

于 2013-07-07T05:47:33.403 回答