regorus-mimalloc 2.2.9

Vendored mimalloc allocator for regorus
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
404
405
406
407
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Memory allocation tracking helpers used by the mimalloc shim.
//! When the `allocator-memory-limits` feature is enabled the shim keeps
//! process-wide counters of bytes allocated through the Rust global allocator.
//! Otherwise the functions become no-ops so the rest of the crate can call
//! them unconditionally.

use core::cell::Cell;
use core::sync::atomic::{AtomicI64, Ordering};
use std::thread_local;

// Total memory allocated through the global allocator.
static GLOBAL_ALLOCATED: AtomicI64 = AtomicI64::new(0);

// Peak memory allocated through the global allocator.
static GLOBAL_PEAK: AtomicI64 = AtomicI64::new(0);

const DEFAULT_THREAD_FLUSH_THRESHOLD: i64 = 1024 * 1024;
static THREAD_FLUSH_THRESHOLD: AtomicI64 = AtomicI64::new(DEFAULT_THREAD_FLUSH_THRESHOLD);

thread_local! {
    // Suspendable execution usage is copied into and out of this cell at segment boundaries.
    static CURRENT_MEMORY_BUDGET_USAGE: Cell<Option<MemoryBudgetUsage>> =
        const { Cell::new(None) };
    // Each thread tracks its own allocations and deallocations. Periodically the thread's
    // stats are flushed into the global counters. Such a design minimizes contention on the
    // global atomic variables on each allocation/free operation.
    static THREAD_COUNTERS: ThreadAllocationCounters = const { ThreadAllocationCounters::new() };
    // Marks that this thread published allocator deltas since the last limit check.
    static THREAD_FLUSHED_SINCE_CHECK: Cell<bool> = const { Cell::new(false) };
}

/// Gross requested bytes retained by a suspendable VM between execution segments.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MemoryBudgetUsage {
    requested_bytes: u64,
    overflowed: bool,
}

impl MemoryBudgetUsage {
    /// Return the gross requested bytes charged to this execution.
    pub const fn requested_bytes(self) -> u64 {
        self.requested_bytes
    }

    /// Return whether this usage exceeds the configured limit, including arithmetic overflow.
    pub const fn exceeds_limit(self, limit: u64) -> bool {
        self.overflowed || self.requested_bytes > limit
    }

    fn record_allocation(&mut self, size: usize) {
        let Ok(size) = u64::try_from(size) else {
            self.requested_bytes = u64::MAX;
            self.overflowed = true;
            return;
        };

        match self.requested_bytes.checked_add(size) {
            Some(requested_bytes) => self.requested_bytes = requested_bytes,
            None => {
                self.requested_bytes = u64::MAX;
                self.overflowed = true;
            }
        }
    }
}

/// Select a suspendable execution's usage while one synchronous segment runs.
///
/// The guard captures the segment's final usage on both return and unwind, then restores the
/// previously-selected execution. Callers own the captured scalar and persist it with their VM.
#[doc(hidden)]
pub fn with_memory_budget_usage_scope<R>(
    initial: Option<MemoryBudgetUsage>,
    updated: &mut Option<MemoryBudgetUsage>,
    operation: impl FnOnce() -> R,
) -> R {
    let previous = CURRENT_MEMORY_BUDGET_USAGE.with(|selected| selected.replace(initial));
    let _scope = MemoryBudgetUsageScope { previous, updated };
    operation()
}

struct MemoryBudgetUsageScope<'a> {
    previous: Option<MemoryBudgetUsage>,
    updated: &'a mut Option<MemoryBudgetUsage>,
}

impl Drop for MemoryBudgetUsageScope<'_> {
    fn drop(&mut self) {
        *self.updated = CURRENT_MEMORY_BUDGET_USAGE.with(Cell::get);
        CURRENT_MEMORY_BUDGET_USAGE.with(|selected| selected.set(self.previous));
    }
}

/// Select no execution budget for the duration of an independent synchronous operation.
#[doc(hidden)]
pub fn with_unowned_memory_budget_scope<R>(operation: impl FnOnce() -> R) -> R {
    let mut ignored = None;
    with_memory_budget_usage_scope(None, &mut ignored, operation)
}

/// Return the usage of the currently-selected suspendable execution segment.
#[doc(hidden)]
pub fn current_memory_budget_usage() -> Option<MemoryBudgetUsage> {
    CURRENT_MEMORY_BUDGET_USAGE.with(Cell::get)
}

/// Add the successful allocation's requested size to the active TLS usage scalar.
pub(crate) fn record_memory_budget_alloc(size: usize) {
    CURRENT_MEMORY_BUDGET_USAGE.with(|selected| {
        if let Some(mut usage) = selected.get() {
            usage.record_allocation(size);
            selected.set(Some(usage));
        }
    });
}

/// Process-wide view of allocator usage at the moment of sampling.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GlobalAllocationStats {
    /// Total bytes currently live across all threads.
    pub allocated: u64,
    /// Highest live byte count observed so far.
    pub peak: u64,
}

/// Per-thread view of allocator usage at the moment of sampling.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ThreadAllocationStats {
    /// Current live bytes for this thread. May be negative if this thread freed
    /// allocations that originated elsewhere.
    pub allocated: i64,
    /// Thread-local peak live bytes reached since thread start.
    pub peak: i64,
}

/// Per-thread accumulator that buffers allocation deltas before flushing.
struct ThreadAllocationCounters {
    // Live bytes tracked for this thread.
    // Incremented on allocation, decremented on free.
    // Note that a thread may free memory allocated by another thread, and thus
    // this value may go negative.
    allocated: Cell<i64>,
    // Highest live byte count observed for this thread.
    peak: Cell<i64>,
    // Value most recently flushed into the global counters.
    last_flushed: Cell<i64>,
}

impl ThreadAllocationCounters {
    /// Creates an empty counter set for a new thread.
    const fn new() -> Self {
        Self {
            allocated: Cell::new(0),
            peak: Cell::new(0),
            last_flushed: Cell::new(0),
        }
    }

    /// Records an allocation and updates the thread peak.
    fn on_alloc(&self, size: i64) {
        if size == 0 {
            return;
        }

        let new_total = self.allocated.get().saturating_add(size);
        self.allocated.set(new_total);
        // Track the highest live byte count the thread has seen.
        self.peak.set(self.peak.get().max(new_total));
        self.flush_if_threshold_exceeded();
    }

    /// Records a free possibly making the thread total negative.
    fn on_free(&self, size: i64) {
        if size == 0 {
            return;
        }

        let new_total = self.allocated.get().saturating_sub(size);
        self.allocated.set(new_total);
        self.flush_if_threshold_exceeded();
    }

    /// Captures the thread-local stats without flushing.
    fn snapshot(&self) -> ThreadAllocationStats {
        ThreadAllocationStats {
            allocated: self.allocated.get(),
            peak: self.peak.get(),
        }
    }

    /// Pushes thread stats into the global counters.
    fn flush(&self) -> Option<(i64, i64)> {
        // Snapshot the latest per-thread total and remember it as the new baseline.
        let thread_total = self.allocated.get();
        let last_flushed_total = self.last_flushed.replace(thread_total);
        // The delta accounts for allocations or frees since the previous flush.
        let delta = thread_total - last_flushed_total;
        if delta != 0 {
            // Apply the delta to the process-wide totals.
            let global_total = GLOBAL_ALLOCATED.fetch_add(delta, Ordering::Relaxed) + delta;
            // Ensure the recorded global peak stays monotonic.
            let peak = update_global_peak(global_total);
            THREAD_FLUSHED_SINCE_CHECK.with(|flag| flag.set(true));
            Some((global_total, peak))
        } else {
            None
        }
    }

    fn flush_if_threshold_exceeded(&self) {
        let threshold = THREAD_FLUSH_THRESHOLD.load(Ordering::Relaxed);
        if threshold <= 0 {
            return;
        }

        let current_total = self.allocated.get();
        let last_flushed_total = self.last_flushed.get();
        let delta = current_total - last_flushed_total;
        if delta >= threshold || delta <= -threshold {
            let _ = self.flush();
        }
    }

    fn pending_delta(&self) -> i64 {
        self.allocated.get() - self.last_flushed.get()
    }
}

/// Record a new allocation of `size` bytes for the current thread.
pub fn record_alloc(size: usize) {
    if size == 0 {
        return;
    }

    let size = size.min(i64::MAX as usize) as i64;

    THREAD_COUNTERS.with(|counters| counters.on_alloc(size));
}

/// Record that `size` bytes were freed by the current thread.
pub fn record_free(size: usize) {
    if size == 0 {
        return;
    }

    let size = size.min(i64::MAX as usize) as i64;

    THREAD_COUNTERS.with(|counters| counters.on_free(size));
}

/// Flush the current thread's counters into the global aggregates.
pub fn flush_thread_counters() {
    THREAD_COUNTERS.with(|counters| {
        counters.flush();
    });
}

/// Returns true if this thread published allocator deltas since the last call.
pub fn take_thread_flushed_since_check_flag() -> bool {
    THREAD_COUNTERS.with(|_| {
        THREAD_FLUSHED_SINCE_CHECK.with(|flag| {
            let flagged = flag.get();
            if flagged {
                flag.set(false);
            }
            flagged
        })
    })
}

/// Return the global and current-thread allocation statistics.
pub fn allocation_stats_snapshot() -> (GlobalAllocationStats, ThreadAllocationStats) {
    let (thread_stats, global_total, global_peak) = THREAD_COUNTERS.with(|counters| {
        let (global_total, global_peak) = match counters.flush() {
            Some((total, peak)) => (total, peak),
            None => load_global_counters(),
        };
        (counters.snapshot(), global_total, global_peak)
    });

    let global_stats = GlobalAllocationStats {
        allocated: global_total.max(0) as u64,
        peak: global_peak.max(0) as u64,
    };

    (global_stats, thread_stats)
}

/// Return only the global allocation statistics.
pub fn global_allocation_stats_snapshot() -> GlobalAllocationStats {
    allocation_stats_snapshot().0
}

/// Return only the current thread allocation statistics.
pub fn current_thread_allocation_stats() -> ThreadAllocationStats {
    allocation_stats_snapshot().1
}

/// Return the current thread's live-byte count without publishing counters globally.
pub fn current_thread_live_bytes() -> i64 {
    THREAD_COUNTERS.with(|counters| counters.allocated.get())
}

/// Return the unflushed allocation delta for the current thread.
pub fn thread_allocation_pending_delta() -> i64 {
    THREAD_COUNTERS.with(|counters| counters.pending_delta())
}

/// Ensures the global peak tracks the highest observed value.
fn update_global_peak(candidate: i64) -> i64 {
    if candidate <= 0 {
        return GLOBAL_PEAK.load(Ordering::Relaxed).max(0);
    }

    let mut observed = GLOBAL_PEAK.load(Ordering::Relaxed);
    while candidate > observed {
        // Retry until we manage to publish the higher peak without blocking.
        match GLOBAL_PEAK.compare_exchange(
            observed,
            candidate,
            Ordering::Relaxed,
            Ordering::Relaxed,
        ) {
            Ok(_) => return candidate,
            Err(next) => observed = next,
        }
    }
    observed.max(candidate)
}

/// Loads the global counters without modifying thread state.
fn load_global_counters() -> (i64, i64) {
    let total = GLOBAL_ALLOCATED.load(Ordering::Relaxed);
    let peak = update_global_peak(total);
    (total, peak)
}

/// Updates the per-thread flush threshold. `None` restores the default (1 MiB).
///
/// Values larger than `i64::MAX` are saturated. Setting the threshold to zero disables automatic
/// flushing, requiring callers to publish deltas manually via [`flush_thread_counters`].
pub fn set_thread_flush_threshold(bytes: Option<u64>) {
    let value = match bytes {
        Some(bytes) => (bytes.min(i64::MAX as u64)) as i64,
        None => DEFAULT_THREAD_FLUSH_THRESHOLD,
    };
    THREAD_FLUSH_THRESHOLD.store(value, Ordering::Relaxed);
}

/// Returns the currently configured per-thread flush threshold in bytes.
///
/// A return value of `None` indicates that automatic flushing is disabled (threshold set to zero or
/// negative). Otherwise the returned number denotes the absolute delta that will trigger a flush.
pub fn thread_flush_threshold() -> Option<u64> {
    let value = THREAD_FLUSH_THRESHOLD.load(Ordering::Relaxed);
    (value > 0).then_some(value as u64)
}

#[cfg(test)]
mod tests {
    use super::{
        current_memory_budget_usage, current_thread_live_bytes, record_alloc, record_free,
        record_memory_budget_alloc, with_memory_budget_usage_scope, MemoryBudgetUsage,
    };

    #[test]
    fn current_thread_live_bytes_tracks_usage_without_a_snapshot() {
        const SIZE: usize = 4096;
        let before = current_thread_live_bytes();

        record_alloc(SIZE);
        assert_eq!(
            current_thread_live_bytes(),
            before.saturating_add(SIZE as i64)
        );

        record_free(SIZE);
        assert_eq!(current_thread_live_bytes(), before);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn requested_byte_overflow_exceeds_even_the_maximum_budget_stickily() {
        let mut exact = Some(MemoryBudgetUsage::default());
        with_memory_budget_usage_scope(exact, &mut exact, || {
            record_memory_budget_alloc(usize::MAX);
        });
        let exact = exact.expect("budgeted usage");
        assert_eq!(exact.requested_bytes(), u64::MAX);
        assert!(!exact.exceeds_limit(u64::MAX));
        assert_eq!(current_memory_budget_usage(), None);

        let mut overflowed = Some(MemoryBudgetUsage::default());
        with_memory_budget_usage_scope(overflowed, &mut overflowed, || {
            record_memory_budget_alloc(usize::MAX);
            record_memory_budget_alloc(1);
        });
        let overflowed = overflowed.expect("budgeted usage");
        assert_eq!(overflowed.requested_bytes(), u64::MAX);
        assert!(overflowed.exceeds_limit(u64::MAX));
        assert!(overflowed.exceeds_limit(0));
    }
}