rsgc 1.1.0

Concurrent GC library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::{error::Error, time::Instant};

use atomic::{Atomic, Ordering};

use crate::formatted_size;

use self::heap::heap;

pub mod bitmap;
pub mod card_table;
pub mod concurrent_gc;
pub mod concurrent_thread;
pub mod controller;
pub mod degenerated_gc;
pub mod free_list;
pub mod free_set;
pub mod full_gc;
pub mod heap;
pub mod heuristics;
pub mod mark;
pub mod mark_bitmap;
pub mod marking_context;
pub mod memory_region;
pub mod obj_storage;
pub mod pacer;
pub mod reference_queue;
pub mod region;
pub mod root_processor;
pub mod safepoint;
pub mod shared_vars;
pub mod signals;
pub mod stack;
pub mod sweeper;
pub mod thread;
pub mod timer;
pub mod tlab;
pub mod tracer;
pub mod virtual_memory;
pub mod worker_policy;
pub mod write_barrier;

#[inline(always)]
pub const fn align_down(addr: usize, align: usize) -> usize {
    addr & !align.wrapping_sub(1)
}
#[inline(always)]
pub const fn align_up(addr: usize, align: usize) -> usize {
    // See https://github.com/rust-lang/rust/blob/e620d0f337d0643c757bab791fc7d88d63217704/src/libcore/alloc.rs#L192
    addr.wrapping_sub(align).wrapping_sub(1) & !align.wrapping_sub(1)
}
#[inline(always)]
pub const fn is_aligned(addr: usize, align: usize) -> bool {
    addr & align.wrapping_sub(1) == 0
}

/// rounds the given value `val` up to the nearest multiple
/// of `align`.
#[inline(always)]
pub const fn align_usize(value: usize, align: usize) -> usize {
    ((value.wrapping_add(align).wrapping_sub(1)).wrapping_div(align)).wrapping_mul(align)
    //((value + align - 1) / align) * align
}

#[inline]
pub fn which_power_of_two(value: usize) -> usize {
    value.trailing_zeros() as _
}

pub fn round_up_to_power_of_two32(mut value: u32) -> u32 {
    if value > 0 {
        value -= 1;
    }
    1 << (32 - value.leading_zeros())
}
#[inline]
pub fn round_down_to_power_of_two32(value: u32) -> u32 {
    if value > 0x80000000 {
        return 0x80000000;
    }

    let mut result = round_up_to_power_of_two32(value);
    if result > value {
        result >>= 1;
    }
    result
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum AllocType {
    ForLAB,
    Shared,
}

pub struct AllocRequest {
    min_size: usize,
    requested_size: usize,
    actual_size: usize,
    typ: AllocType,
}

impl AllocRequest {
    pub const fn new(typ: AllocType, min_size: usize, requested_size: usize) -> Self {
        Self {
            typ,
            min_size,
            requested_size,
            actual_size: 0,
        }
    }

    pub fn for_lab(&self) -> bool {
        self.typ == AllocType::ForLAB
    }

    pub const fn size(&self) -> usize {
        self.requested_size
    }

    pub const fn min_size(&self) -> usize {
        self.min_size
    }

    pub const fn actual_size(&self) -> usize {
        self.actual_size
    }

    pub fn set_actual_size(&mut self, actual_size: usize) {
        self.actual_size = actual_size;
    }
}

#[derive(Debug)]
pub struct DynBitmap {
    buffer: Vec<u8>,
    bit_count: usize,
}

impl DynBitmap {
    pub fn contained(bits: usize) -> Self {
        Self {
            buffer: vec![0u8; Self::bytes_required(bits)],
            bit_count: bits,
        }
    }
    pub const fn bytes_required(bits: usize) -> usize {
        (bits + 7) / 8
    }

    /// Index of contained bit byte.
    fn contained_byte_index(bit_index: usize) -> usize {
        bit_index / 8
    }

    /// Bit position in byte.
    const fn position_in_byte(bit_index: usize) -> u8 {
        (bit_index % 8) as u8
    }

    fn get_byte(&self, bit_index: usize) -> u8 {
        unsafe {
            self.buffer
                .get(Self::contained_byte_index(bit_index))
                .copied()
                .unwrap_unchecked()
        }
    }

    fn get_byte_mut(&mut self, bit_index: usize) -> &mut u8 {
        unsafe {
            self.buffer
                .get_mut(Self::contained_byte_index(bit_index))
                .unwrap_unchecked()
        }
    }

    /// Get `value` from `byte` for exact bit-`index`.
    #[inline(always)]
    fn get_value(byte: u8, index: u8) -> bool {
        // We shift byte-value on `index`-bit and apply bit **and**-operation
        // with `0b0000_0001`.
        ((byte >> index) & 0b0000_0001) == 1
    }

    pub fn get(&self, bit_index: usize) -> bool {
        let byte: u8 = self.get_byte(bit_index);
        let position_in_byte = Self::position_in_byte(bit_index);
        Self::get_value(byte, position_in_byte)
    }

    /// Set `value` in `byte` for exact bit-`index`.
    #[inline(always)]
    fn set_value(byte: u8, value: bool, index: u8) -> u8 {
        // Unset `index` bit and set value.
        byte & !(1 << index) | ((value as u8) << index)
    }

    pub fn set(&mut self, bit_index: usize, value: bool) {
        let byte: &mut u8 = self.get_byte_mut(bit_index);
        let position: u8 = Self::position_in_byte(bit_index);
        *byte = Self::set_value(*byte, value, position);
    }

    pub fn write<W: std::io::Write>(&self, mut writer: W) -> std::io::Result<()> {
        writer.write_all(&self.buffer)
    }

    pub fn byte_size(&self) -> usize {
        self.buffer.len()
    }

    pub fn arity(&self) -> usize {
        self.bit_count
    }

    pub fn iter(&self) -> impl Iterator<Item = bool> + '_ {
        self.buffer
            .iter()
            .flat_map(|&byte| (0..=7).map(move |idx| Self::get_value(byte, idx)))
            .take(self.arity())
    }

    pub fn clear(&mut self) {
        self.buffer.fill(0); // TODO: Can't use sloppy_memset here??
    }

    pub fn count_ones(&self) -> usize {
        self.buffer.iter().map(|x| x.count_ones() as usize).sum()
    }
}

impl std::iter::FromIterator<bool> for DynBitmap {
    fn from_iter<I: IntoIterator<Item = bool>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let initial_size = iter.size_hint().1.map(Self::bytes_required).unwrap_or(0);

        let mut buffer = Vec::with_capacity(initial_size);
        let mut bit_idx: u8 = 0;
        let mut byte: u8 = 0;
        let mut bit_count = 0;

        for value in iter {
            if bit_idx == 8 {
                buffer.push(byte);
                byte = 0;
                bit_idx = 0;
            }

            byte = DynBitmap::set_value(byte, value, bit_idx);
            bit_idx += 1;
            bit_count += 1;
        }

        buffer.push(byte);

        Self { buffer, bit_count }
    }
}

#[inline(always)]
pub fn atomic_load<T>(ptr: *const T, ordering: Ordering) -> T
where
    T: Copy,
{
    unsafe {
        let atomic: &Atomic<T> = std::mem::transmute(ptr);

        atomic.load(ordering)
    }
}
#[inline(always)]
pub fn atomic_store<T>(ptr: *const T, value: T, ordering: Ordering)
where
    T: Copy,
{
    unsafe {
        let atomic: &Atomic<T> = std::mem::transmute(ptr);
        atomic.store(value, ordering);
    }
}
#[inline(always)]
pub fn atomic_cmpxchg<T>(data: &T, old: T, new: T) -> T
where
    T: Copy,
{
    unsafe {
        let atomic: &Atomic<T> = std::mem::transmute(data);
        match atomic.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::SeqCst) {
            Ok(val) => val,
            Err(val) => val,
        }
    }
}

#[inline(always)]
pub fn atomic_cmpxchg_weak<T>(data: &T, old: T, new: T, ordering: Ordering) -> T
where
    T: Copy,
{
    unsafe {
        let atomic: &Atomic<T> = std::mem::transmute(data);
        match atomic.compare_exchange_weak(old, new, ordering, Ordering::Relaxed) {
            Ok(val) => val,
            Err(val) => val,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum DegenPoint {
    Unset,
    OutsideCycle,
    ConcurrentMark,
    ConcurrentSweep,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum GCHeuristic {
    Adaptive,
    Static,
}

impl GCHeuristic {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "adaptive" => GCHeuristic::Adaptive,
            "static" => GCHeuristic::Static,
            _ => panic!("Unknown GC heuristic: {}", s),
        }
    }
}

pub struct ConcurrentPhase {
    name: &'static str,
    start: Instant,
}

pub struct PausePhase {
    name: &'static str,
    start: Instant,
}

impl ConcurrentPhase {
    pub fn new(name: &'static str) -> Self {
        Self {
            name,
            start: Instant::now(),
        }
    }
}

impl Drop for ConcurrentPhase {
    fn drop(&mut self) {
        let elapsed = self.start.elapsed();
        let id = heap().controller_thread().get_gc_id();
        log::info!(target: "gc", "GC({}) Concurrent {} {}ms", id, self.name, elapsed.as_micros() as f64 / 1000.0);
    }
}

impl PausePhase {
    pub fn new(name: &'static str) -> Self {
        Self {
            name,
            start: Instant::now(),
        }
    }
}

impl Drop for PausePhase {
    fn drop(&mut self) {
        let elapsed = self.start.elapsed();
        let id = heap().controller_thread().get_gc_id();
        log::info!(target: "gc", "GC({}) Pause {} {}ms", id, self.name, elapsed.as_micros() as f64 / 1000.0);
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
#[non_exhaustive]
pub enum AllocError {
    OutOfMemory(usize),
    NonRegisteredThread,
}

impl Error for AllocError {
    fn description(&self) -> &str {
        match self {
            AllocError::OutOfMemory(_) => "Out of memory",
            AllocError::NonRegisteredThread => "Non registered thread",
        }
    }
}

impl std::fmt::Display for AllocError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AllocError::OutOfMemory(size) => {
                write!(f, "Out of memory when allocating {}", formatted_size(*size))
            }
            AllocError::NonRegisteredThread => {
                write!(f, "Trying to allocate in a non registered thread")
            }
        }
    }
}