2 .\" Copyright (c) 2010, The DragonFly Project.
4 .\" This software is derived from software contributed to the DragonFly Project
5 .\" by Venkatesh Srinivas <me@endeavour.zapto.org>.
7 .\" Permission to use, copy, modify, or distribute this software for any
8 .\" purpose with or without fee is hereby granted, provided that the above
9 .\" copyright notice and this permission notice appear in all copies.
11 .\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 .\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 .\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 .\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR OTHER DAMAGES
15 .\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN
16 .\" ACTION OF CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 .Nd lightweight reference counts
30 .Fn kref_init "struct kref *ref" "int count"
32 .Fn kref_inc "struct kref *ref"
34 .Fn kref_dec "struct kref *ref" "void (*deconstruct)(void *, void *)" \
35 "void *priv1" "void *priv2"
38 Kref is a lightweight reference counting system applicable to many dynamically
39 allocated structures. The space overhead of a reference count is only one
44 function initializes a reference to the value
49 function increments a reference atomically with respect to preemption and to
56 function decrements a reference atomically with respect to preemption and to
59 calls. If the reference transitions from 1 to 0, the
61 function is called with
69 returns 0 if it sees a 1 to 0 transition, 1 otherwise.
72 An object cannot synchronize its own visibility. Therefore care must be taken
73 when interleaving calls to kref_inc and kref_dec; higher level synchronization
76 Simple use of kref with a
85 struct interesting *thing = kmalloc(sizeof(struct interesting), M_DEVBUF);
86 /* Setup reference to 1 */
87 kref_init(&thing->ref, 1);
89 /* 1 -> 2 transition */
90 kref_inc(&thing->ref);
92 /* 2 -> 1 transition ; don't call deconstruct (kfree) */
93 kref_dec(&thing->ref, kfree, thing, M_DEVBUF);
95 /* 1 -> 0 transition, so call kfree to release thing */
96 kref_dec(&thing->ref, kfree, thing, M_DEVBUF);
99 The kref implementation is in
100 .Pa /sys/kern/kern_ref.c .
102 kref first appeared in