mmtk/util/
rc.rs

1use std::marker::PhantomData;
2use std::sync::atomic::{AtomicU32, AtomicUsize};
3
4use crate::util::linear_scan::Region;
5use crate::util::{metadata::side_metadata::address_to_meta_address, Address};
6use crate::{
7    policy::immix::{block::Block, line::Line},
8    util::{metadata::side_metadata::SideMetadataSpec, ObjectReference},
9    vm::*,
10};
11use atomic::Ordering;
12
13/// Log2 of the number of bits used to store each object's reference count in the RC table.
14pub const LOG_REF_COUNT_BITS: usize = 1;
15/// Number of bits used to store each object's reference count in the RC table.
16pub const REF_COUNT_BITS: u8 = 1 << LOG_REF_COUNT_BITS;
17/// Bit mask covering the bits used to store a reference count.
18pub const REF_COUNT_MASK: u8 = (((1u16 << REF_COUNT_BITS) - 1) & 0xff) as u8;
19/// The maximum representable reference count. Once an object's count reaches this value it
20/// is treated as saturated/sticky and is no longer incremented or decremented.
21pub const MAX_REF_COUNT: u8 = REF_COUNT_MASK;
22
23/// Log2 of the minimum object size, i.e. the granularity at which reference counts are tracked.
24pub const LOG_MIN_OBJECT_SIZE: usize = crate::util::constants::LOG_MIN_OBJECT_SIZE as _;
25/// The minimum object size, i.e. the granularity at which reference counts are tracked.
26pub const MIN_OBJECT_SIZE: usize = 1 << LOG_MIN_OBJECT_SIZE;
27
28/// Side metadata recording which Immix lines are "straddled" by an object that spans
29/// multiple lines, so straddling objects can be identified without scanning their contents.
30pub const RC_STRADDLE_LINES: SideMetadataSpec =
31    crate::util::metadata::side_metadata::spec_defs::RC_STRADDLE_LINES;
32
33/// Side metadata spec for the per-object reference count table.
34pub const RC_TABLE: SideMetadataSpec = crate::util::metadata::side_metadata::spec_defs::RC_TABLE;
35
36static INC_BUFFER_SIZE: AtomicUsize = AtomicUsize::new(0);
37
38static TOTAL_INCS_PACKETS: AtomicU32 = AtomicU32::new(0);
39
40static TOTAL_INCS: AtomicU32 = AtomicU32::new(0);
41static ROOT_INCS: AtomicU32 = AtomicU32::new(0);
42static MATURE_INCS: AtomicU32 = AtomicU32::new(0);
43static NURSERY_INCS: AtomicU32 = AtomicU32::new(0);
44static FAST_NURSERY_INCS: AtomicU32 = AtomicU32::new(0);
45static LOS_INCS: AtomicU32 = AtomicU32::new(0);
46
47static PROMOTED_OBJECTS: AtomicU32 = AtomicU32::new(0);
48static PROMOTED_SCALARS: [AtomicU32; 3] = [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)];
49static PROMOTED_PRIM_ARRAYS: [AtomicU32; 3] =
50    [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)];
51static PROMOTED_OBJECT_ARRAYS: [AtomicU32; 3] =
52    [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)];
53
54/// A zero-sized helper type providing methods to read and update per-object reference count
55/// metadata for LXR's reference counting plan.
56#[repr(transparent)]
57#[derive(Debug, Copy)]
58pub struct RefCountHelper<VM: VMBinding>(PhantomData<VM>);
59
60impl<VM: VMBinding> RefCountHelper<VM> {
61    /// A singleton instance of `RefCountHelper` (the type is zero-sized, so it can be freely copied/cloned).
62    pub const NEW: Self = Self(PhantomData);
63    /// Whether extra reference-counting sanity checks are enabled (debug builds or the `sanity` feature).
64    pub const SANITY: bool = cfg!(debug_assertions) || cfg!(feature = "sanity");
65
66    /// Returns the current size of the global increment buffer, i.e. the number of pending
67    /// reference count increments that have been enqueued but not yet processed.
68    pub fn inc_buffer_size(&self) -> usize {
69        INC_BUFFER_SIZE.load(Ordering::Relaxed)
70    }
71
72    /// Increases the global increment buffer size counter by `delta`.
73    pub fn increase_inc_buffer_size(&self, delta: usize) {
74        let _ = INC_BUFFER_SIZE.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |x| {
75            Some(x.saturating_add(delta))
76        });
77    }
78
79    /// Resets the global increment buffer size counter to zero.
80    pub fn reset_inc_buffer_size(&self) {
81        INC_BUFFER_SIZE.store(0, Ordering::Relaxed)
82    }
83
84    /// Atomically updates the reference count of object `o` by applying `f` to its current
85    /// value, following the same semantics as `AtomicU8::fetch_update`.
86    pub fn fetch_update(
87        &self,
88        o: ObjectReference,
89        f: impl FnMut(u8) -> Option<u8>,
90    ) -> Result<u8, u8> {
91        RC_TABLE.fetch_update_atomic(o.to_raw_address(), Ordering::Relaxed, Ordering::Relaxed, f)
92    }
93
94    /// Returns `true` if object `o`'s reference count has saturated at `MAX_REF_COUNT` (sticky).
95    pub fn is_stuck(&self, o: ObjectReference) -> bool {
96        self.count(o) == MAX_REF_COUNT
97    }
98
99    /// Forces object `o`'s reference count to `MAX_REF_COUNT`, permanently marking it as sticky
100    /// so it is never reclaimed by reference counting.
101    pub fn stick(&self, o: ObjectReference) -> Result<u8, u8> {
102        self.fetch_update(o, |x| {
103            debug_assert!(x <= MAX_REF_COUNT);
104            if x == MAX_REF_COUNT {
105                None
106            } else {
107                Some(MAX_REF_COUNT)
108            }
109        })
110    }
111
112    /// Increments object `o`'s reference count by one, leaving it unchanged (saturating) once
113    /// it has reached `MAX_REF_COUNT`.
114    pub fn inc(&self, o: ObjectReference) -> Result<u8, u8> {
115        #[cfg(feature = "vo_bit")]
116        debug_assert!(
117            crate::util::metadata::vo_bit::is_vo_bit_set(o),
118            "{o}: VO bit not set",
119        );
120
121        self.fetch_update(o, |x| {
122            debug_assert!(x <= MAX_REF_COUNT);
123            if x == MAX_REF_COUNT {
124                None
125            } else {
126                Some(x + 1)
127            }
128        })
129    }
130
131    /// Decrements object `o`'s reference count by one, unless it is already zero or has
132    /// saturated at `MAX_REF_COUNT` (sticky), in which case it is left unchanged.
133    pub fn dec(&self, o: ObjectReference) -> Result<u8, u8> {
134        #[cfg(feature = "vo_bit")]
135        debug_assert!(
136            crate::util::metadata::vo_bit::is_vo_bit_set(o),
137            "{o}: VO bit not set",
138        );
139
140        self.fetch_update(o, |x| {
141            debug_assert!(x <= MAX_REF_COUNT);
142            if x == 0 || x == MAX_REF_COUNT
143            /* sticky */
144            {
145                None
146            } else {
147                Some(x - 1)
148            }
149        })
150    }
151
152    /// Atomically sets object `o`'s reference count to `count`.
153    pub fn set(&self, o: ObjectReference, count: u8) {
154        RC_TABLE.store_atomic(o.to_raw_address(), count, Ordering::Relaxed)
155    }
156
157    /// Sets object `o`'s reference count to `count` using a non-atomic store, for use where the
158    /// caller can guarantee there is no concurrent access.
159    pub fn set_relaxed(&self, o: ObjectReference, count: u8) {
160        unsafe { RC_TABLE.store(o.to_raw_address(), count) }
161    }
162
163    /// Sets the reference count for the line containing object `o` to `count` using a non-atomic store,
164    /// for use where the caller can guarantee there is no concurrent access.
165    pub fn set_line_relaxed(&self, line: Line, count: u8) {
166        unsafe { RC_TABLE.store(line.start(), count) }
167    }
168
169    /// Returns object `o`'s current reference count.
170    pub fn count(&self, o: ObjectReference) -> u8 {
171        RC_TABLE.load_atomic(o.to_raw_address(), Ordering::Relaxed)
172    }
173
174    /// Returns the reference count stored in the RC table at address `addr`. If this
175    /// returns a non-zero value, it indicates that `addr` is the address of an object reference,
176    /// or the start of a straddle line.
177    pub fn count_by_address(&self, addr: Address) -> u8 {
178        RC_TABLE.load_atomic(addr, Ordering::Relaxed)
179    }
180
181    /// Returns `true` if the RC table entry at `o`'s address is zero. Used for both individual
182    /// objects and line-granularity entries (e.g. straddle line markers), which share the same table.
183    pub fn object_or_line_is_dead(&self, o: ObjectReference) -> bool {
184        RC_TABLE.load_byte(o.to_raw_address()) == 0
185    }
186
187    /// Returns a slice view over the raw RC table memory covering block `b`, reinterpreted as an
188    /// array of `UInt`, allowing the block's reference counts to be scanned in bulk.
189    pub fn rc_table_range<UInt: Sized>(&self, b: Block) -> &'static [UInt] {
190        debug_assert!({
191            let log_bits_in_uint: usize =
192                (std::mem::size_of::<UInt>() << 3).trailing_zeros() as usize;
193            Block::LOG_BYTES - super::rc::LOG_MIN_OBJECT_SIZE + super::rc::LOG_REF_COUNT_BITS
194                >= log_bits_in_uint
195        });
196        let start = address_to_meta_address(&super::rc::RC_TABLE, b.start()).to_ptr::<UInt>();
197        let limit = address_to_meta_address(&super::rc::RC_TABLE, b.end()).to_ptr::<UInt>();
198        let rc_table = unsafe { std::slice::from_raw_parts(start, limit.offset_from(start) as _) };
199        rc_table
200    }
201
202    /// Returns `true` if object `o`'s reference count is zero.
203    #[allow(unused)]
204    pub fn is_dead(&self, o: ObjectReference) -> bool {
205        let v: u8 = RC_TABLE.load_atomic(o.to_raw_address(), Ordering::Relaxed);
206        v == 0
207    }
208
209    /// Returns `true` if object `o`'s reference count is zero (dead) or has saturated at
210    /// `MAX_REF_COUNT` (sticky).
211    pub fn is_dead_or_stuck(&self, o: ObjectReference) -> bool {
212        let v: u8 = RC_TABLE.load_atomic(o.to_raw_address(), Ordering::Relaxed);
213        v == 0 || v == MAX_REF_COUNT
214    }
215
216    /// Returns `true` if object `o` is in a straddle line. The function does not check rc table.
217    pub fn object_is_in_straddle_line_no_rc_check(&self, o: ObjectReference) -> bool {
218        // This directly reads line-granularity straddle line metadata with an unaligned address.
219        // It is still correct, but may break side metadata assertions.
220        unsafe { RC_STRADDLE_LINES.load::<u8>(o.to_raw_address()) != 0 }
221    }
222
223    /// Returns `true` if address `a` falls within a live object whose containing line is marked
224    /// as a straddle line.
225    pub fn object_is_in_straddle_line(&self, o: ObjectReference) -> bool {
226        let line = Line::from_unaligned_address(o.to_raw_address());
227        self.count(o) != 0 && unsafe { RC_STRADDLE_LINES.load::<u8>(line.start()) != 0 }
228    }
229
230    fn mark_straddle_object_with_size(&self, o: ObjectReference, size: usize) {
231        debug_assert!(size > Line::BYTES);
232        let start = o.to_object_start::<VM>();
233        let end = start + size;
234        // Skip the line holding the object's reference address. As we currently conservatively skip
235        // the last line in a hole and do not use that line, we don't need to mark lines at object start here
236        // (as the line would be convervatively kept alive). See: https://github.com/mmtk/mmtk-core/pull/1576
237        // TODO: if we use a different solution to handle object start, we may need to mark lines
238        // at object start here.
239        let start_line = Line::from_unaligned_address(o.to_raw_address()).next();
240        let end_line = Line::from_unaligned_address(end);
241        // Note that `end_line` may be the last line overlapping with `o`.
242        // In that case, `end_line` will not be marked.
243        // It is OK because when searching for available lines (`rc_get_next_available_lines`),
244        // it always skips the first line in a hole.
245        let mut line = start_line;
246        while line < end_line {
247            unsafe { RC_STRADDLE_LINES.store(line.start(), 1u8) };
248            self.set_line_relaxed(line, 1);
249            line = line.next();
250        }
251    }
252
253    /// Marks every line (other than the first) spanned by object `o` as a straddle line, so the
254    /// object can be identified from any of the lines it straddles.
255    pub fn mark_straddle_object(&self, o: ObjectReference) {
256        let size = VM::VMObjectModel::get_current_size(o);
257        self.mark_straddle_object_with_size(o, size)
258    }
259
260    /// Clears the straddle-line and reference-count markers set by `mark_straddle_object` for
261    /// every line (other than the first) spanned by object `o`.
262    pub fn unmark_straddle_object(&self, o: ObjectReference) {
263        // debug_assert!(crate::args::RC_NURSERY_EVACUATION);
264        let size = VM::VMObjectModel::get_current_size(o);
265        if size > Line::BYTES {
266            let start = o.to_object_start::<VM>();
267            let end = start + size;
268            // Must match `mark_straddle_object_with_size` exactly; see the comments there.
269            let start_line = Line::from_unaligned_address(o.to_raw_address()).next();
270            let end_line = Line::from_unaligned_address(end);
271            // Note that `end_line` may be the last line overlapping with `o`.
272            // In that case, `end_line` will not be marked.
273            // It is OK because when searching for available lines (`rc_get_next_available_lines`),
274            // it always skips the first line in a hole.
275            let mut line = start_line;
276            while line < end_line {
277                self.set_line_relaxed(line, 0);
278                unsafe { RC_STRADDLE_LINES.store(line.start(), 0u8) };
279                line = line.next();
280            }
281        }
282    }
283
284    /// Debug assertion that every `MIN_OBJECT_SIZE` granule within object `o` has a reference
285    /// count of zero, used to verify that a reclaimed object has been fully cleared.
286    pub fn assert_zero_ref_count(&self, o: ObjectReference) {
287        let size = VM::VMObjectModel::get_current_size(o);
288        for i in (0..size).step_by(MIN_OBJECT_SIZE) {
289            let a = o.to_raw_address() + i;
290            assert_eq!(0, self.count_by_address(a));
291        }
292    }
293
294    /// Called when object `o` is promoted to mature space; marks it as a straddle object if it
295    /// spans more than one line, deriving its size from the VM binding.
296    pub fn promote(&self, o: ObjectReference) {
297        let size = o.get_size::<VM>();
298        if size > Line::BYTES {
299            self.mark_straddle_object_with_size(o, size);
300        }
301    }
302
303    /// Same as `promote`, but with the object's size supplied by the caller instead of being
304    /// queried from the VM binding.
305    pub fn promote_with_size(&self, o: ObjectReference, size: usize) {
306        if size > Line::BYTES {
307            self.mark_straddle_object_with_size(o, size);
308        }
309    }
310}
311
312impl<VM: VMBinding> Clone for RefCountHelper<VM> {
313    fn clone(&self) -> Self {
314        Self(PhantomData)
315    }
316}