1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_REFCOUNT_H
3 #define _LINUX_REFCOUNT_H
5 #include <linux/atomic.h>
6 #include <linux/mutex.h>
7 #include <linux/spinlock.h>
8 #include <linux/kernel.h>
11 * struct refcount_t - variant of atomic_t specialized for reference counts
12 * @refs: atomic_t counter field
14 * The counter saturates at UINT_MAX and will not move once
15 * there. This avoids wrapping the counter and causing 'spurious'
16 * use-after-free bugs.
18 typedef struct refcount_struct
{
22 #define REFCOUNT_INIT(n) { .refs = ATOMIC_INIT(n), }
25 * refcount_set - set a refcount's value
27 * @n: value to which the refcount will be set
29 static inline void refcount_set(refcount_t
*r
, unsigned int n
)
31 atomic_set(&r
->refs
, n
);
35 * refcount_read - get a refcount's value
38 * Return: the refcount's value
40 static inline unsigned int refcount_read(const refcount_t
*r
)
42 return atomic_read(&r
->refs
);
45 #ifdef CONFIG_REFCOUNT_FULL
46 extern __must_check
bool refcount_add_not_zero(unsigned int i
, refcount_t
*r
);
47 extern void refcount_add(unsigned int i
, refcount_t
*r
);
49 extern __must_check
bool refcount_inc_not_zero(refcount_t
*r
);
50 extern void refcount_inc(refcount_t
*r
);
52 extern __must_check
bool refcount_sub_and_test(unsigned int i
, refcount_t
*r
);
54 extern __must_check
bool refcount_dec_and_test(refcount_t
*r
);
55 extern void refcount_dec(refcount_t
*r
);
57 # ifdef CONFIG_ARCH_HAS_REFCOUNT
58 # include <asm/refcount.h>
60 static inline __must_check
bool refcount_add_not_zero(unsigned int i
, refcount_t
*r
)
62 return atomic_add_unless(&r
->refs
, i
, 0);
65 static inline void refcount_add(unsigned int i
, refcount_t
*r
)
67 atomic_add(i
, &r
->refs
);
70 static inline __must_check
bool refcount_inc_not_zero(refcount_t
*r
)
72 return atomic_add_unless(&r
->refs
, 1, 0);
75 static inline void refcount_inc(refcount_t
*r
)
80 static inline __must_check
bool refcount_sub_and_test(unsigned int i
, refcount_t
*r
)
82 return atomic_sub_and_test(i
, &r
->refs
);
85 static inline __must_check
bool refcount_dec_and_test(refcount_t
*r
)
87 return atomic_dec_and_test(&r
->refs
);
90 static inline void refcount_dec(refcount_t
*r
)
94 # endif /* !CONFIG_ARCH_HAS_REFCOUNT */
95 #endif /* CONFIG_REFCOUNT_FULL */
97 extern __must_check
bool refcount_dec_if_one(refcount_t
*r
);
98 extern __must_check
bool refcount_dec_not_one(refcount_t
*r
);
99 extern __must_check
bool refcount_dec_and_mutex_lock(refcount_t
*r
, struct mutex
*lock
);
100 extern __must_check
bool refcount_dec_and_lock(refcount_t
*r
, spinlock_t
*lock
);
102 #endif /* _LINUX_REFCOUNT_H */