Team LiB
Previous Section Next Section

Managing and Manipulating kobjects

With the basic internals of kobjects and friends behind you, it's time to look at the exported interfaces used for managing and manipulating kobjects. Most of the time, driver writers will not have to deal with kobjects directly. Instead, kobjects will be embedded in some class-specific structure (as you saw with the character device structure) and managed "behind the scenes" by the associated driver subsystem. Nonetheless, kobjects are not intended to remain hidden and may seep through into driver code or you may be hacking on the driver subsystem itself.

The first step in using a kobject is declaring and initializing it. kobjects are initialized via the function kobject_init, which is defined in <linux/kobject.h>:

void kobject_init(struct kobject *kobj);

The function's lone parameter is the kobject to initialize. Before calling this function, the kobject must be zeroed. This may normally happen during the initialization of the larger function in which the kobject is embedded. If not, a simple call to memset() does the trick:

memset(kobj, 0, sizeof (*kobj));

It is safe to initialize parent and kset after the zeroing. For example,

kobj = kmalloc(sizeof (*kobj), GFP_KERNEL);
if (!kobj)
        return -ENOMEM; 
memset(kobj, 0, sizeof (*kobj));
kobj->kset = kset;
kobj->parent = parent_kobj;

After initialization, you must set the kobject's name via kobject_set_name():

int kobject_set_name(struct kobject * kobj, const char * fmt, ...);

This function uses a variable argument list in the style of printf() and printk() to set the name of the provided kobject. As you saw, k_name points to the kobject's name. If the name is small enough, it is stored in the static array name, so it makes sense to not needlessly provide a huge name.

After allocating a kobject and proving it with a name, you need to set its kset field and optionally its ktype field. You need to set the ktype only if the kset does not provide one. Otherwise, the ktype in the kset takes precedence. If you are wondering why kobjects even have ktype fields, welcome to the club.

    Team LiB
    Previous Section Next Section