]> git.karo-electronics.de Git - mv-sheeva.git/blob - lib/kref.c
kref: add kref_test_and_get
[mv-sheeva.git] / lib / kref.c
1 /*
2  * kref.c - library routines for handling generic reference counted objects
3  *
4  * Copyright (C) 2004 Greg Kroah-Hartman <greg@kroah.com>
5  * Copyright (C) 2004 IBM Corp.
6  *
7  * based on lib/kobject.c which was:
8  * Copyright (C) 2002-2003 Patrick Mochel <mochel@osdl.org>
9  *
10  * This file is released under the GPLv2.
11  *
12  */
13
14 #include <linux/kref.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17
18 /**
19  * kref_init - initialize object.
20  * @kref: object in question.
21  */
22 void kref_init(struct kref *kref)
23 {
24         atomic_set(&kref->refcount, 1);
25         smp_mb();
26 }
27
28 /**
29  * kref_get - increment refcount for object.
30  * @kref: object.
31  */
32 void kref_get(struct kref *kref)
33 {
34         WARN_ON(!atomic_read(&kref->refcount));
35         atomic_inc(&kref->refcount);
36         smp_mb__after_atomic_inc();
37 }
38
39 /**
40  * kref_test_and_get - increment refcount for object only if refcount is not
41  * zero.
42  * @kref: object.
43  *
44  * Return non-zero if the refcount was incremented, 0 otherwise
45  */
46 int kref_test_and_get(struct kref *kref)
47 {
48         return atomic_inc_not_zero(&kref->refcount);
49 }
50
51 /**
52  * kref_put - decrement refcount for object.
53  * @kref: object.
54  * @release: pointer to the function that will clean up the object when the
55  *           last reference to the object is released.
56  *           This pointer is required, and it is not acceptable to pass kfree
57  *           in as this function.
58  *
59  * Decrement the refcount, and if 0, call release().
60  * Return 1 if the object was removed, otherwise return 0.  Beware, if this
61  * function returns 0, you still can not count on the kref from remaining in
62  * memory.  Only use the return value if you want to see if the kref is now
63  * gone, not present.
64  */
65 int kref_put(struct kref *kref, void (*release)(struct kref *kref))
66 {
67         WARN_ON(release == NULL);
68         WARN_ON(release == (void (*)(struct kref *))kfree);
69
70         if (atomic_dec_and_test(&kref->refcount)) {
71                 release(kref);
72                 return 1;
73         }
74         return 0;
75 }
76
77 EXPORT_SYMBOL(kref_init);
78 EXPORT_SYMBOL(kref_get);
79 EXPORT_SYMBOL(kref_put);