1238106Sdes/*-
2238106Sdes * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3238106Sdes *
4238106Sdes * Copyright (c) 2005 John Baldwin <jhb@FreeBSD.org>
5238106Sdes *
6238106Sdes * Redistribution and use in source and binary forms, with or without
7238106Sdes * modification, are permitted provided that the following conditions
8238106Sdes * are met:
9238106Sdes * 1. Redistributions of source code must retain the above copyright
10238106Sdes *    notice, this list of conditions and the following disclaimer.
11238106Sdes * 2. Redistributions in binary form must reproduce the above copyright
12238106Sdes *    notice, this list of conditions and the following disclaimer in the
13238106Sdes *    documentation and/or other materials provided with the distribution.
14238106Sdes *
15238106Sdes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16238106Sdes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17238106Sdes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18238106Sdes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19238106Sdes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20238106Sdes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21238106Sdes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22238106Sdes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23238106Sdes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24238106Sdes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25238106Sdes * SUCH DAMAGE.
26238106Sdes *
27238106Sdes * $FreeBSD: stable/11/sbin/hastd/refcnt.h 367457 2020-11-07 18:10:59Z dim $
28238106Sdes */
29238106Sdes
30238106Sdes#ifndef __REFCNT_H__
31238106Sdes#define __REFCNT_H__
32238106Sdes
33238106Sdes#include <machine/atomic.h>
34238106Sdes
35238106Sdes#include "pjdlog.h"
36238106Sdes
37238106Sdestypedef unsigned int refcnt_t;
38238106Sdes
39238106Sdesstatic __inline void
40238106Sdesrefcnt_init(refcnt_t *count, unsigned int v)
41238106Sdes{
42238106Sdes
43238106Sdes	*count = v;
44238106Sdes}
45238106Sdes
46238106Sdesstatic __inline void
47249141Sdesrefcnt_acquire(refcnt_t *count)
48249141Sdes{
49249141Sdes
50238106Sdes	atomic_add_acq_int(count, 1);
51238106Sdes}
52238106Sdes
53238106Sdesstatic __inline unsigned int
54238106Sdesrefcnt_release(refcnt_t *count)
55238106Sdes{
56238106Sdes	unsigned int old;
57238106Sdes
58238106Sdes	/* XXX: Should this have a rel membar? */
59238106Sdes	old = atomic_fetchadd_int(count, -1);
60238106Sdes	PJDLOG_ASSERT(old > 0);
61238106Sdes	return (old - 1);
62238106Sdes}
63238106Sdes
64238106Sdes#endif	/* ! __REFCNT_H__ */
65238106Sdes