Tuesday, February 22, 2022

[SOLVED] container_of sample code in lwn.net

Issue

When seeing:

void my_object_release(struct kobject *kobj)
{
   struct my_object *mine = container_of(kobj, struct my_object, kobj);

   /* Perform any additional cleanup on this object, then... */
   kfree (mine);
}

in LWN’s The zen of kobjects, it seems incorrect in the third parameter kobj. I think it should be kobject.


Solution

The given code is correct: the third argument is the name of the container structure member to which the pointer points, not its type, so kobj is right. The example is somewhat confusing since the first kobj doesn’t correspond to the same thing as the second kobj: the first is the pointer in the caller’s scope.

Here’s a diagram to hopefully clarify the parameters of container_of:

container_of(kobj, struct my_object, kobj)
              |            |          |
              |            |          |
              \------------+----------+--------------------------------\
                           |          |                                |
                           |          |                                |
         /-----------------/          |                                |
         |                            |                                |
         V              /-------------/                                |
+------------------+    |                                              |
| struct my_object | {  |                                              |
+------------------+    V                                              V
                   +------+                                         +------+
    struct kobject | kobj |; <-- You have a pointer to this, called | kobj |
                   +------+                                         +------+
    ...
};

container_of allows you to pass around a kobject pointer and find the containing object (as long as you know what the containing object is) — it allows you to use your knowledge of “what” to answer “where”.

It’s worth pointing out that container_of is a macro, which is how it can do seemingly impossible things (for developers not used to meta-programming).



Answered By - Stephen Kitt
Answer Checked By - Willingham (WPSolving Volunteer)