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