/*
* kset and ktype example
*/
#include <linux/kobject.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
/*
* This module shows how to create a kset in sysfs called
* /sys/kernel/ks_a
*/
/*
* This is our "object" that we will create a few of and register them with
* sysfs.
*/
struct fu_obj {
struct kobject kobj;
int par;
};
#define to_fu_obj(x) container_of(x, struct fu_obj, kobj)
/*
* The release function for our object. This is REQUIRED by the kernel to
* have. We free the memory held in our object here.
*
* NEVER try to get away with just a "blank" release function to try to be
* smarter than the kernel. Turns out, no one ever is...
*/
static void fu_release(struct kobject *kobj)
{
struct fu_obj *fu;
fu = to_fu_obj(kobj);
kfree(fu);
}
/*
* Our own ktype for our kobjects. Here we only specify the
* release function.
*/
static struct kobj_type fu_ktype = {
.release = fu_release,
};
static struct kset *ks_a;
static struct fu_obj *fu_a1;
static struct fu_obj *fu_a2;
static struct fu_obj *fu_a3;
static struct fu_obj *create_fu_obj(const char *name)
{
struct fu_obj *fu;
int retval;
/* allocate the memory for the whole object */
fu = kzalloc(sizeof(*fu), GFP_KERNEL);
if (!fu)
return NULL;
/*
* As we have a kset for this kobject, we need to set it before calling
* the kobject core.
*/
fu->kobj.kset = ks_a;
/*
* Initialize and add the kobject to the kernel. All the default files
* will be created here. As we have already specified a kset for this
* kobject, we don't have to set a parent for the kobject, the kobject
* will be placed beneath that kset automatically.
*/
retval = kobject_init_and_add(&fu->kobj, &fu_ktype, NULL, "%s", name);
if (retval) {
kobject_put(&fu->kobj);
return NULL;
}
return fu;
}
static void destroy_fu_obj(struct fu_obj *fu)
{
kobject_put(&fu->kobj);
}
static int __init example_init(void)
{
/*
* Create a kset with the name of "ks_a",
* located under /sys/kernel/
*/
ks_a = kset_create_and_add("ks_a", NULL, kernel_kobj);
if (!ks_a)
return -ENOMEM;
/*
* Create three objects and register them with our kset
*/
fu_a1 = create_fu_obj("fu_a1");
if (!fu_a1)
goto err_fu_a1;
fu_a2 = create_fu_obj("fu_a2");
if (!fu_a2)
goto err_fu_a2;
fu_a3 = create_fu_obj("fu_a3");
if (!fu_a3)
goto err_fu_a3;
return 0;
err_fu_a3:
destroy_fu_obj(fu_a2);
err_fu_a2:
destroy_fu_obj(fu_a1);
err_fu_a1:
kset_unregister(ks_a);
return -EINVAL;
}
static void __exit example_exit(void)
{
destroy_fu_obj(fu_a3);
destroy_fu_obj(fu_a2);
destroy_fu_obj(fu_a1);
kset_unregister(ks_a);
}
module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");