LJ Archive

container_of()

What exactly does the weird container_of() macro do? This macro is defined as:

#define container_of(ptr, type, member) ({ \
    const typeof( ((type *)0)->member ) \
    *__mptr = (ptr);
    (type *)( (char *)__mptr - offsetof(type,member) );})

To help explain this, let us go through the steps of what it is doing. In the include/linux/i2c.h file, the to_i2c_driver() macro is defined as:

container_of(d, struct i2c_driver, driver)
and is used in code as:
i2c_drv = to_i2c_driver(drv)

where dev is a pointer to a struct device_driver.

Replacing the above code with the first macro expansion produces:

i2c_drv = container_of(drv, struct i2c_driver,
driver);

Replacing the above code with the first macro expansion produces:

i2c_drv = container_of(drv, struct
i2c_driver, driver);

Then, the next level of expansion creates:

i2c_drv = ({
    const typeof( ((struct i2c_driver *)0)->driver)
    *__mptr = drv;
    (struct i2c_driver *)( (char *)__mptr
    - offsetof(struct i2c_driver, driver));
})

To simplify this, remember that driver is a variable within the i2c_driver function. The first line of the macro sets up a pointer that points to the struct device_driver passed to the code. The second line of the macro finds the real location in memory of the struct i2c_driver that we want to access.

To show this using real numbers, say the i2c_driver structure looks like:

struct i2c_driver {
    struct name[32];
};

The location of the driver variable usually is about 32 bytes into the structure, depending on the packing rules of the compiler at the time. For more information on how to see where variables are located in structures, see my article “Writing Portable Device Drivers” in the May/June 2002 issue of Embedded Linux Journal, available at www.linuxjournal.com/article/5783.

So, if the drv pointer is at location 0xC0101020, the __mptr variable is assigned that location in the first line of the macro. Then, the offset of the driver variable is subtracted from this address, giving us the value 0xC0101000. This would be assigned to the variable on the left side of the original assignment, i2c_drv.

In order to do this kind of pointer manipulation, the code has to know the type of pointer being passed to it. The driver core only passes in the type of driver structure registered with it, so this type of manipulation is safe. This also prevents other parts of the kernel from modifying the unique fields of the structure used to control the subsystem's code.

LJ Archive