2 * Copyright (c) 2010, Venkatesh Srinivas <me@endeavour.zapto.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 * Lightweight reference counts
21 #include <cpu/atomic.h>
25 kref_init(struct kref
*ref
, int count
)
27 ref
->refcount
= count
;
31 kref_inc(struct kref
*ref
)
33 atomic_add_int(&ref
->refcount
, 1);
37 * Decrement a reference count; on a 1 -> 0 transition, call the
38 * deconstruct function (if any) with priv1 and priv2. Returns 0
39 * if it sees a 1 -> 0 transition, 1 otherwise.
41 * "An object cannot synchronize its own visibility." It is not safe
42 * to interleave kref_inc and kref_dec without other synchronization.
45 kref_dec(struct kref
*ref
, void (*deconstruct
)(void *, void *),
46 void *priv1
, void *priv2
)
50 val
= atomic_fetchadd_int(&ref
->refcount
, -1);
53 deconstruct(priv1
, priv2
);