Skip to main content

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    // Always inline to optimize out error path of `build_assert`.
27    #[inline(always)]
28    pub fn new(value: i32) -> Self {
29        build_assert!(value >= 0, "initial value saturated");
30        // SAFETY: There are no safety requirements for this FFI call.
31        Self(Opaque::new(unsafe { bindings::REFCOUNT_INIT(value) }))
32    }
33
34    #[inline]
35    fn as_ptr(&self) -> *mut bindings::refcount_t {
36        self.0.get()
37    }
38
39    /// Get the underlying atomic counter that backs the refcount.
40    ///
41    /// NOTE: Usage of this function is discouraged as it can circumvent the protections offered by
42    /// `refcount.h`. If there is no way to achieve the result using APIs in `refcount.h`, then
43    /// this function can be used. Otherwise consider adding a binding for the required API.
44    #[inline]
45    pub fn as_atomic(&self) -> &Atomic<i32> {
46        let ptr = self.0.get().cast();
47        // SAFETY: `refcount_t` is a transparent wrapper of `atomic_t`, which is an atomic 32-bit
48        // integer that is layout-wise compatible with `Atomic<i32>`. All values are valid for
49        // `refcount_t`, despite some of the values being considered saturated and "bad".
50        unsafe { &*ptr }
51    }
52
53    /// Set a refcount's value.
54    #[inline]
55    pub fn set(&self, value: i32) {
56        // SAFETY: `self.as_ptr()` is valid.
57        unsafe { bindings::refcount_set(self.as_ptr(), value) }
58    }
59
60    /// Increment a refcount.
61    ///
62    /// It will saturate if overflows and `WARN`. It will also `WARN` if the refcount is 0, as this
63    /// represents a possible use-after-free condition.
64    ///
65    /// Provides no memory ordering, it is assumed that caller already has a reference on the
66    /// object.
67    #[inline]
68    pub fn inc(&self) {
69        // SAFETY: self is valid.
70        unsafe { bindings::refcount_inc(self.as_ptr()) }
71    }
72
73    /// Decrement a refcount.
74    ///
75    /// It will `WARN` on underflow and fail to decrement when saturated.
76    ///
77    /// Provides release memory ordering, such that prior loads and stores are done
78    /// before.
79    #[inline]
80    pub fn dec(&self) {
81        // SAFETY: `self.as_ptr()` is valid.
82        unsafe { bindings::refcount_dec(self.as_ptr()) }
83    }
84
85    /// Decrement a refcount and test if it is 0.
86    ///
87    /// It will `WARN` on underflow and fail to decrement when saturated.
88    ///
89    /// Provides release memory ordering, such that prior loads and stores are done
90    /// before, and provides an acquire ordering on success such that memory deallocation
91    /// must come after.
92    ///
93    /// Returns true if the resulting refcount is 0, false otherwise.
94    ///
95    /// # Notes
96    ///
97    /// A common pattern of using `Refcount` is to free memory when the reference count reaches
98    /// zero. This means that the reference to `Refcount` could become invalid after calling this
99    /// function. This is fine as long as the reference to `Refcount` is no longer used when this
100    /// function returns `false`. It is not necessary to use raw pointers in this scenario, see
101    /// <https://github.com/rust-lang/rust/issues/55005>.
102    #[inline]
103    #[must_use = "use `dec` instead if you do not need to test if it is 0"]
104    pub fn dec_and_test(&self) -> bool {
105        // SAFETY: `self.as_ptr()` is valid.
106        unsafe { bindings::refcount_dec_and_test(self.as_ptr()) }
107    }
108}
109
110// SAFETY: `refcount_t` is thread-safe.
111unsafe impl Send for Refcount {}
112
113// SAFETY: `refcount_t` is thread-safe.
114unsafe impl Sync for Refcount {}