1150629Sjhb/*-
2150629Sjhb * Copyright (c) 2005 John Baldwin <jhb@FreeBSD.org>
3150629Sjhb * All rights reserved.
4150629Sjhb *
5150629Sjhb * Redistribution and use in source and binary forms, with or without
6150629Sjhb * modification, are permitted provided that the following conditions
7150629Sjhb * are met:
8150629Sjhb * 1. Redistributions of source code must retain the above copyright
9150629Sjhb *    notice, this list of conditions and the following disclaimer.
10150629Sjhb * 2. Redistributions in binary form must reproduce the above copyright
11150629Sjhb *    notice, this list of conditions and the following disclaimer in the
12150629Sjhb *    documentation and/or other materials provided with the distribution.
13150629Sjhb *
14150629Sjhb * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15150629Sjhb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16150629Sjhb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17150629Sjhb * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18150629Sjhb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19150629Sjhb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20150629Sjhb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21150629Sjhb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22150629Sjhb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23150629Sjhb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24150629Sjhb * SUCH DAMAGE.
25150629Sjhb *
26150629Sjhb * $FreeBSD$
27150629Sjhb */
28150629Sjhb
29150629Sjhb#ifndef __SYS_REFCOUNT_H__
30150629Sjhb#define __SYS_REFCOUNT_H__
31150629Sjhb
32238828Sglebius#include <sys/limits.h>
33180762Sdes#include <machine/atomic.h>
34180762Sdes
35180762Sdes#ifdef _KERNEL
36180762Sdes#include <sys/systm.h>
37180762Sdes#else
38180762Sdes#define	KASSERT(exp, msg)	/* */
39180762Sdes#endif
40180762Sdes
41150629Sjhbstatic __inline void
42150629Sjhbrefcount_init(volatile u_int *count, u_int value)
43150629Sjhb{
44150629Sjhb
45150629Sjhb	*count = value;
46150629Sjhb}
47150629Sjhb
48150629Sjhbstatic __inline void
49150629Sjhbrefcount_acquire(volatile u_int *count)
50150629Sjhb{
51150629Sjhb
52238828Sglebius	KASSERT(*count < UINT_MAX, ("refcount %p overflowed", count));
53150629Sjhb	atomic_add_acq_int(count, 1);
54150629Sjhb}
55150629Sjhb
56150629Sjhbstatic __inline int
57150629Sjhbrefcount_release(volatile u_int *count)
58150629Sjhb{
59180762Sdes	u_int old;
60150629Sjhb
61180762Sdes	/* XXX: Should this have a rel membar? */
62180762Sdes	old = atomic_fetchadd_int(count, -1);
63180762Sdes	KASSERT(old > 0, ("negative refcount %p", count));
64180762Sdes	return (old == 1);
65150629Sjhb}
66150629Sjhb
67150629Sjhb#endif	/* ! __SYS_REFCOUNT_H__ */
68