2011年12月26日 星期一

Note about kobjects, ksets, and ktypes.

kobject, quoted form kernek documentation: (example in samples/kobject/kobject-example.c)
1. A kobject must be initialized. for example
void kobject_init(struct kobject *kobj, struct kobj_type *ktype);
The ktype is required for a kobject to be created properly, as every kobject
must have an associated kobj_type.

2. After calling kobject_init(), to regsiter the kobject with sysfs, kobject_add() must be called
int kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...);
This setup the parrent of the kobject and the name for the kobject properly. If the kobject is to be associated with a specific kset, kobj->kset must be assigned before calling kobject_add(). If a kset is associated with a kobject, then the parent for the kobject can be set to NULL in the call to kobject_add() andthen the kobject's parent will be the kset itself.
or call int kobject_init_and_add(struct kobject *kobj, struct kobj_type *ktype,
struct kobject *parent, const char *fmt, ...); to init and add kobject to the kernel at the same time.

3. To inform userspace that a kobj has been created, call
int kobject_uevent(struct kobject *kobj, enum kobject_action action);

4. To create a simple directory in the sysfs hierarchy and not to mess with the whole complication of ksets, show and store functions, call
struct kobject *kobject_create_and_add(char *name, struct kobject *parent);
It creates a kobject and place it in sysfs in the location underneath the specified parent kobject.

5. To release a kobject, don't do kfree() but kobject_put(). A good practice is to use kobject_put() as an error check after kobject_init() to avoid errors creeping in.

6. Every kobject must have a release() method and the release() method is not stored in the kobject itself but associated with the ktype. for example:
struct kobj_type {
void (*release)(struct kobject *);
const struct sysfs_ops *sysfs_ops;
struct attribute **default_attrs;
};
This structure must be referenced when you call kobject_init() or kobject_init_and_add()..