diff --git a/Makefile b/Makefile index 01d4d25..c897ed5 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,7 @@ KDIR=/usr/src/kernels/$(shell uname -r) obj-m += demo.o obj-m += blk_kprobe.o +obj-m += kobject-example.o all: make -C $(KDIR) M=$(shell pwd) modules diff --git a/kobject-example.c b/kobject-example.c new file mode 100644 index 0000000..bb904cf --- /dev/null +++ b/kobject-example.c @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include + +static int foo; +static int baz; +static int bar; + +static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr, + char *buf) +{ + return sysfs_emit(buf, "%d\n", foo); +} + +static ssize_t foo_store(struct kobject *kobj, struct kobj_attribute *attr, + const char *buf, size_t count) +{ + int ret; + + ret = kstrtoint(buf, 10, &foo); + if (ret < 0) + return ret; + + return count; +} + +static struct kobj_attribute foo_attribute = + __ATTR(foo, 0664, foo_show, foo_store); + +static ssize_t b_show(struct kobject *kobj, struct kobj_attribute *attr, + char *buf) +{ + int var; + + if (strcmp(attr->attr.name, "baz") == 0) + var = baz; + else + var = bar; + return sysfs_emit(buf, "%d\n", var); +} + +static ssize_t b_store(struct kobject *kobj, struct kobj_attribute *attr, + const char *buf, size_t count) +{ + int var, ret; + + ret = kstrtoint(buf, 10, &var); + if (ret < 0) + return ret; + + if (strcmp(attr->attr.name, "baz") == 0) + baz = var; + else + bar = var; + return count; +} + +static struct kobj_attribute baz_attribute = + __ATTR(baz, 0664, b_show, b_store); +static struct kobj_attribute bar_attribute = + __ATTR(bar, 0664, b_show, b_store); + +static struct attribute *attrs[] = { + &foo_attribute.attr, + &baz_attribute.attr, + &bar_attribute.attr, + NULL, /* need to NULL terminate the list of attributes */ +}; + +static struct attribute_group attr_group = { + .attrs = attrs, +}; + +static struct kobject *example_kobj; + +static int __init example_init(void) +{ + int retval; + + example_kobj = kobject_create_and_add("kobject_example", kernel_kobj); + if (!example_kobj) + return -ENOMEM; + + retval = sysfs_create_group(example_kobj, &attr_group); + if (retval) + kobject_put(example_kobj); + + return retval; +} + +static void __exit example_exit(void) +{ + kobject_put(example_kobj); +} + +module_init(example_init); +module_exit(example_exit); +MODULE_LICENSE("GPL v2"); +MODULE_AUTHOR("Greg Kroah-Hartman ");