From fcd4b1543f2ade695126260e5093432e682d57fb Mon Sep 17 00:00:00 2001 From: Thadeu Lima de Souza Cascardo Date: Tue, 18 May 2010 18:18:11 -0400 Subject: [PATCH] Use kref. --- hello.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/hello.c b/hello.c index f5d9670..bcf8de0 100644 --- a/hello.c +++ b/hello.c @@ -22,6 +22,7 @@ #include #include #include +#include MODULE_LICENSE("GPL"); MODULE_AUTHOR("Thadeu Lima de Souza Cascardo "); @@ -29,29 +30,42 @@ MODULE_DESCRIPTION("Hello, world"); struct hello { int times; + struct kref ref; char greeting[0]; }; -static struct hello *hello; +static struct hello *global_hello; static char default_greeting[] = "Hello, world!\n"; +static void hello_release(struct kref *ref) +{ + struct hello *hello = container_of(ref, struct hello, ref); + printk(KERN_DEBUG "releasing hello\n"); + kfree(hello); +} + static int hello_init(void) { + static struct hello *hello; hello = kmalloc(sizeof(*hello) + sizeof(default_greeting), GFP_KERNEL); if (!hello) return -ENOMEM; + kref_init(&hello->ref); + kref_get(&hello->ref); + global_hello = hello; memcpy(hello->greeting, default_greeting, sizeof(default_greeting)); printk("%s\n", hello->greeting); printk("%p %p %p\n", hello, hello->greeting, container_of(&hello->greeting, struct hello, greeting)); printk("size %d\n", ARRAY_SIZE(default_greeting)); + kref_put(&hello->ref, hello_release); return 0; } static __exit void hello_exit(void) { - kfree(hello); + kref_put(&global_hello->ref, hello_release); } module_init(hello_init); -- 2.20.1