kernel/sync/refcount.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Atomic reference counting.
4//!
5//! C header: [`include/linux/refcount.h`](srctree/include/linux/refcount.h)
6
7use crate::build_assert;
8use crate::sync::atomic::Atomic;
9use crate::types::Opaque;
10
11/// Atomic reference counter.
12///
13/// This type is conceptually an atomic integer, but provides saturation semantics compared to
14/// normal atomic integers. Values in the negative range when viewed as a signed integer are
15/// saturation (bad) values. For details about the saturation semantics, please refer to top of
16/// [`include/linux/refcount.h`](srctree/include/linux/refcount.h).
17///
18/// Wraps the kernel's C `refcount_t`.
19#[repr(transparent)]
20pub struct Refcount(Opaque<bindings::refcount_t>);
21
22impl Refcount {
23 /// Construct a new [`Refcount`] from an initial value.
24 ///
25 /// The initial value should be non-saturated.
26 #[inline]
27 pub fn new(value: i32) -> Self {
28 build_assert!(value >= 0, "initial value saturated");
29 // SAFETY: There are no safety requirements for this FFI call.
30 Self(Opaque::new(unsafe { bindings::REFCOUNT_INIT(value) }))
31 }
32
33 #[inline]
34 fn as_ptr(&self) -> *mut bindings::refcount_t {
35 self.0.get()
36 }
37
38 /// Get the underlying atomic counter that backs the refcount.
39 ///
40 /// NOTE: Usage of this function is discouraged as it can circumvent the protections offered by
41 /// `refcount.h`. If there is no way to achieve the result using APIs in `refcount.h`, then
42 /// this function can be used. Otherwise consider adding a binding for the required API.
43 #[inline]
44 pub fn as_atomic(&self) -> &Atomic<i32> {
45 let ptr = self.0.get().cast();
46 // SAFETY: `refcount_t` is a transparent wrapper of `atomic_t`, which is an atomic 32-bit
47 // integer that is layout-wise compatible with `Atomic<i32>`. All values are valid for
48 // `refcount_t`, despite some of the values being considered saturated and "bad".
49 unsafe { &*ptr }
50 }
51
52 /// Set a refcount's value.
53 #[inline]
54 pub fn set(&self, value: i32) {
55 // SAFETY: `self.as_ptr()` is valid.
56 unsafe { bindings::refcount_set(self.as_ptr(), value) }
57 }
58
59 /// Increment a refcount.
60 ///
61 /// It will saturate if overflows and `WARN`. It will also `WARN` if the refcount is 0, as this
62 /// represents a possible use-after-free condition.
63 ///
64 /// Provides no memory ordering, it is assumed that caller already has a reference on the
65 /// object.
66 #[inline]
67 pub fn inc(&self) {
68 // SAFETY: self is valid.
69 unsafe { bindings::refcount_inc(self.as_ptr()) }
70 }
71
72 /// Decrement a refcount.
73 ///
74 /// It will `WARN` on underflow and fail to decrement when saturated.
75 ///
76 /// Provides release memory ordering, such that prior loads and stores are done
77 /// before.
78 #[inline]
79 pub fn dec(&self) {
80 // SAFETY: `self.as_ptr()` is valid.
81 unsafe { bindings::refcount_dec(self.as_ptr()) }
82 }
83
84 /// Decrement a refcount and test if it is 0.
85 ///
86 /// It will `WARN` on underflow and fail to decrement when saturated.
87 ///
88 /// Provides release memory ordering, such that prior loads and stores are done
89 /// before, and provides an acquire ordering on success such that memory deallocation
90 /// must come after.
91 ///
92 /// Returns true if the resulting refcount is 0, false otherwise.
93 ///
94 /// # Notes
95 ///
96 /// A common pattern of using `Refcount` is to free memory when the reference count reaches
97 /// zero. This means that the reference to `Refcount` could become invalid after calling this
98 /// function. This is fine as long as the reference to `Refcount` is no longer used when this
99 /// function returns `false`. It is not necessary to use raw pointers in this scenario, see
100 /// <https://github.com/rust-lang/rust/issues/55005>.
101 #[inline]
102 #[must_use = "use `dec` instead if you do not need to test if it is 0"]
103 pub fn dec_and_test(&self) -> bool {
104 // SAFETY: `self.as_ptr()` is valid.
105 unsafe { bindings::refcount_dec_and_test(self.as_ptr()) }
106 }
107}
108
109// SAFETY: `refcount_t` is thread-safe.
110unsafe impl Send for Refcount {}
111
112// SAFETY: `refcount_t` is thread-safe.
113unsafe impl Sync for Refcount {}