2 * kref.c - library routines for handling generic reference counted objects
4 * Copyright (C) 2004 Greg Kroah-Hartman <greg@kroah.com>
5 * Copyright (C) 2004 IBM Corp.
7 * based on lib/kobject.c which was:
8 * Copyright (C) 2002-2003 Patrick Mochel <mochel@osdl.org>
10 * This file is released under the GPLv2.
14 #include <linux/kref.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
19 * kref_set - initialize object and set refcount to requested number.
20 * @kref: object in question.
21 * @num: initial reference counter
23 void kref_set(struct kref
*kref
, int num
)
25 atomic_set(&kref
->refcount
, num
);
30 * kref_init - initialize object.
31 * @kref: object in question.
33 void kref_init(struct kref
*kref
)
39 * kref_get - increment refcount for object.
42 void kref_get(struct kref
*kref
)
44 WARN_ON(!atomic_read(&kref
->refcount
));
45 atomic_inc(&kref
->refcount
);
46 smp_mb__after_atomic_inc();
50 * kref_put - decrement refcount for object.
52 * @release: pointer to the function that will clean up the object when the
53 * last reference to the object is released.
54 * This pointer is required, and it is not acceptable to pass kfree
55 * in as this function.
57 * Decrement the refcount, and if 0, call release().
58 * Return 1 if the object was removed, otherwise return 0. Beware, if this
59 * function returns 0, you still can not count on the kref from remaining in
60 * memory. Only use the return value if you want to see if the kref is now
63 int kref_put(struct kref
*kref
, void (*release
)(struct kref
*kref
))
65 WARN_ON(release
== NULL
);
66 WARN_ON(release
== (void (*)(struct kref
*))kfree
);
68 if (atomic_dec_and_test(&kref
->refcount
)) {
75 EXPORT_SYMBOL(kref_set
);
76 EXPORT_SYMBOL(kref_init
);
77 EXPORT_SYMBOL(kref_get
);
78 EXPORT_SYMBOL(kref_put
);