blob: 6d19f690380b8e3020b3a74e8fac3d2713055d0e [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>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090016#include <linux/slab.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017
18/**
Evgeniy Polyakov41ca28a2007-12-10 23:03:43 +030019 * kref_set - initialize object and set refcount to requested number.
20 * @kref: object in question.
21 * @num: initial reference counter
22 */
23void kref_set(struct kref *kref, int num)
24{
25 atomic_set(&kref->refcount, num);
26 smp_mb();
27}
28
29/**
Linus Torvalds1da177e2005-04-16 15:20:36 -070030 * kref_init - initialize object.
31 * @kref: object in question.
32 */
33void kref_init(struct kref *kref)
34{
Evgeniy Polyakov41ca28a2007-12-10 23:03:43 +030035 kref_set(kref, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -070036}
37
38/**
39 * kref_get - increment refcount for object.
40 * @kref: object.
41 */
42void kref_get(struct kref *kref)
43{
44 WARN_ON(!atomic_read(&kref->refcount));
45 atomic_inc(&kref->refcount);
Oliver Neukum1b0b3b92007-04-02 14:47:59 +020046 smp_mb__after_atomic_inc();
Linus Torvalds1da177e2005-04-16 15:20:36 -070047}
48
49/**
50 * kref_put - decrement refcount for object.
51 * @kref: 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.
56 *
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
61 * gone, not present.
62 */
63int kref_put(struct kref *kref, void (*release)(struct kref *kref))
64{
65 WARN_ON(release == NULL);
66 WARN_ON(release == (void (*)(struct kref *))kfree);
67
Venkatesh Pallipadif334b602006-12-19 13:01:29 -080068 if (atomic_dec_and_test(&kref->refcount)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -070069 release(kref);
70 return 1;
71 }
72 return 0;
73}
74
Evgeniy Polyakov41ca28a2007-12-10 23:03:43 +030075EXPORT_SYMBOL(kref_set);
Linus Torvalds1da177e2005-04-16 15:20:36 -070076EXPORT_SYMBOL(kref_init);
77EXPORT_SYMBOL(kref_get);
78EXPORT_SYMBOL(kref_put);