blob: a6dc3ec328e05fc8da4d69d185d13a5758ac0464 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
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
17/**
18 * kref_init - initialize object.
19 * @kref: object in question.
20 */
21void kref_init(struct kref *kref)
22{
23 atomic_set(&kref->refcount,1);
Oliver Neukum1b0b3b92007-04-02 14:47:59 +020024 smp_mb();
Linus Torvalds1da177e2005-04-16 15:20:36 -070025}
26
27/**
28 * kref_get - increment refcount for object.
29 * @kref: object.
30 */
31void kref_get(struct kref *kref)
32{
33 WARN_ON(!atomic_read(&kref->refcount));
34 atomic_inc(&kref->refcount);
Oliver Neukum1b0b3b92007-04-02 14:47:59 +020035 smp_mb__after_atomic_inc();
Linus Torvalds1da177e2005-04-16 15:20:36 -070036}
37
38/**
39 * kref_put - decrement refcount for object.
40 * @kref: object.
41 * @release: pointer to the function that will clean up the object when the
42 * last reference to the object is released.
43 * This pointer is required, and it is not acceptable to pass kfree
44 * in as this function.
45 *
46 * Decrement the refcount, and if 0, call release().
47 * Return 1 if the object was removed, otherwise return 0. Beware, if this
48 * function returns 0, you still can not count on the kref from remaining in
49 * memory. Only use the return value if you want to see if the kref is now
50 * gone, not present.
51 */
52int kref_put(struct kref *kref, void (*release)(struct kref *kref))
53{
54 WARN_ON(release == NULL);
55 WARN_ON(release == (void (*)(struct kref *))kfree);
56
Venkatesh Pallipadif334b602006-12-19 13:01:29 -080057 if (atomic_dec_and_test(&kref->refcount)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -070058 release(kref);
59 return 1;
60 }
61 return 0;
62}
63
64EXPORT_SYMBOL(kref_init);
65EXPORT_SYMBOL(kref_get);
66EXPORT_SYMBOL(kref_put);