~mht/cmr

ref: 5b585576fd05856862c7b665eecadc83bccfc1dd cmr/src/alloc.rs -rw-r--r-- 11.0 KiB
5b585576 — Martin Hafskjold Thoresen Add fences around the allocator wrappers 4 years ago
                                                                                
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
//! This module contains wrapping types for `Box`, `Rc`, and `Arc`. We need to make these types and
//! not use the ones from `std` because we are not allowed to move these types. The typical use
//! case for this is to allocate an `Arc<MsQueue>`, such that we know that the `MsQueue` struct
//! will never be moved out of the `Arc`.
//!
//! Due to how `Box` works in Rust, it is possible (and really easy) to obtain `T` from `Box<T>`:
//!
//! ```
//! let b: Box<Vec<i32>> = Box::new(Vec::new());
//! let vec: Vec<i32> = *b;
//! ```

use std::alloc::{GlobalAlloc, Layout};
use std::boxed::Box as B;
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::Ordering::SeqCst;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::Arc as StdArc;
#[cfg(feature = "sanitize")]
use std::sync::Mutex;
#[cfg(feature = "sanitize")]
use std::collections::HashSet;

use alloc_system::System;
use jemallocator::Jemalloc;

use jemalloc_free_hack;

use ptr;
use consolidate;
use ptr::Ptr;
use signalvec;

// Every `THRESHOLD`th allocation, do some cleanup
#[cfg(feature = "threshold_1")]
const THRESHOLD: usize = 1 * 1024;
#[cfg(feature = "threshold_2")]
const THRESHOLD: usize = 2 * 1024;
#[cfg(feature = "threshold_4")]
const THRESHOLD: usize = 4 * 1024;
#[cfg(feature = "threshold_8")]
const THRESHOLD: usize = 8 * 1024;
#[cfg(feature = "threshold_16")]
const THRESHOLD: usize = 16 * 1024;
#[cfg(feature = "threshold_32")]
const THRESHOLD: usize = 32 * 1024;
#[cfg(feature = "threshold_64")]
const THRESHOLD: usize = 64 * 1024;
#[cfg(feature = "threshold_128")]
const THRESHOLD: usize = 128 * 1024;
#[cfg(feature = "threshold_256")]
const THRESHOLD: usize = 256 * 1024;
#[cfg(feature = "threshold_512")]
const THRESHOLD: usize = 512 * 1024;
#[cfg(not(any(feature = "threshold_1024", feature = "threshold_1",
                  feature = "threshold_2", feature = "threshold_4", feature = "threshold_8",
                  feature = "threshold_16", feature = "threshold_32",
                  feature = "threshold_64", feature = "threshold_128",
                  feature = "threshold_256", feature = "threshold_512")))]
const THRESHOLD: usize = 1024 * 32;



thread_local! {
    /// Local cached list of allocations done by this thread. This has to be a `SignalVec`, as the
    /// consolidator wants to steal its contents, potentially while we are trying to insert into
    /// it, but got interrupted by a signal.
    pub(crate) static ALLOC: StdArc<UnsafeCell<signalvec::SignalVec>> = {
        StdArc::new(UnsafeCell::new(signalvec::SignalVec::with_capacity(THRESHOLD + 2)))
    };
    /// Count how many times this thread has allocated since last time it was the consolidator.
    /// We need unsafe cell here for interior mutability. (`LocalKey::with` gives `&T`)
    pub(crate) static ALLOC_COUNT: UnsafeCell<usize> = UnsafeCell::new(0);
}

#[cfg(feature = "sanitize")]
lazy_static! {
    pub static ref ALLOCATIONS: Mutex<HashSet<usize>> = Mutex::new(HashSet::new());
    pub static ref FREES: Mutex<HashSet<usize>> = Mutex::new(HashSet::new());
}

/// Register the pointer as allocated. If a pointer is allocated without being registered it will
/// not be freed. This should be called after putting the pointer in a `Guard`.
pub fn register<'a, P, T>(p: P)
where
    T: 'a + ptr::Trace,
    P: Into<ptr::NullablePtr<'a, T>>,
{
    #[cfg(feature = "noop")]
    {
        return;
    }

    let ptr: ptr::Ptr<T> = p.into().ptr().unwrap();
    let r: &ptr::Trace = &*ptr;
    let trait_object: ::std::raw::TraitObject = unsafe { ::std::mem::transmute(r) };

    ALLOC_COUNT.with(|ac| unsafe {
        let n = ac.get();
        *n += 1;
        if *n > THRESHOLD {
            *n %= THRESHOLD;
            #[cfg(feature = "disable-reclamation")] return;
            // timed!("consolidate", {

            consolidate();
            // };);
        }
    });
    ALLOC.with(|v| {
        let sv = unsafe { &mut *v.get() };
        sv.push(trait_object);
    });
}

/// Heap allocate the value `t`.
pub fn alloc<'a, T>(t: T) -> Ptr<'a, T>
where
    T: ptr::Trace,
{
    #[cfg(feature = "noop")]
    {
        return unsafe { Ptr::new(B::into_raw(B::new(t)) as usize) };
    }
    let addr = B::into_raw(B::new(t)) as usize;
    #[cfg(feature = "sanitize")]
    {
        // println!("alloc({:x})", addr);
        let mut a = ALLOCATIONS.lock().unwrap();
        assert!(a.insert(addr));
        let mut f = FREES.lock().unwrap();
        f.remove(&addr);
    }
    unsafe { Ptr::new(addr) }
}

/// This actuallly frees the memory at address `addr`.
pub fn free(addr: usize) {
    #[cfg(feature = "sanitize")]
    {
        // println!("free({:x})", addr);
        let mut a = ALLOCATIONS.lock().unwrap();
        assert!(a.contains(&addr));
        a.remove(&addr);
        let mut f = FREES.lock().unwrap();
        f.insert(addr);
    }
    unsafe {
        let b: B<usize> = B::from_raw(addr as *mut usize);
        ::std::mem::drop(b);
    }
}

/// This is an owned heap allocated object. It is pretty much like a `Box<T>`. We have this type
/// since we must sometimes guarantee that some values are never moved. This is not possible with a
/// `std::boxed::Box`, for weird reasons.
pub struct Box<T>(B<T>);

impl<T> Box<T> {
    /// Construct a new box.
    pub fn new(t: T) -> Self {
        Box(B::new(t))
    }
}

impl<T> Deref for Box<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl<T> DerefMut for Box<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self.0
    }
}

unsafe impl<T> Send for Box<T>
where
    T: Send,
{
}
unsafe impl<T> Sync for Box<T>
where
    T: Sync,
{
}

pub struct Rc<T>(::std::rc::Rc<T>);

impl<T> Rc<T> {
    pub fn new(t: T) -> Rc<T> {
        Rc(::std::rc::Rc::new(t))
    }
}

impl<T> Deref for Rc<T> {
    type Target = ::std::rc::Rc<T>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Rc<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

pub struct Arc<T>(::std::sync::Arc<T>);

impl<T> Arc<T> {
    pub fn new(t: T) -> Arc<T> {
        Arc(::std::sync::Arc::new(t))
    }
}

impl<T> Deref for Arc<T> {
    type Target = ::std::sync::Arc<T>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Arc<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Call the given closure without risking deadlocking if we're signaled during its execution. This
/// happens when function calls calls `malloc` internally, as the consolidator _needs_ to be able
/// to allocate while threads are stuck in the signal handler.
///
/// Examples of functions that needs to be called inside here includes `std::thread::spawn`.
pub fn without_reclamation<R, F: FnOnce() -> R>(f: F) -> R {
    #[cfg(feature = "noop")]
    {
        return f();
    }
    let lock = SOME_LOCK.lock();
    ::std::sync::atomic::compiler_fence(SeqCst);
    let ret = f();
    ::std::sync::atomic::compiler_fence(SeqCst);
    drop(lock);
    ret
}

use std::sync::atomic::AtomicPtr;
thread_local! {
    /// Every thread stores a pointer to a static bool, which is in the array
    /// `cmr::THREAD_BOOLS`; This is an array that contains a single bool for
    /// each thread in the system, which signals whether that thread is
    /// currently allocating or not.
    pub(crate) static SOME_LOCK_MARKER: AtomicPtr<AtomicBool> =
        AtomicPtr::new(::std::ptr::null_mut());
}
pub(crate) static SOME_LOCK: Asd = Asd::new();

pub(crate) struct Asd {
    lock: AtomicBool,
    owner: AtomicUsize,
}

pub struct AsdGuard;

impl Drop for AsdGuard {
    fn drop(&mut self) {
        SOME_LOCK.unlock();
    }
}

impl Asd {
    const fn new() -> Self {
        Asd {
            lock: AtomicBool::new(false),
            owner: AtomicUsize::new(0),
        }
    }

    fn start_alloc(&self) -> Option<&AtomicBool> {
        if self.owner.load(SeqCst) == super::thread_id() {
            return None;
        }
        SOME_LOCK_MARKER.with(|b| {
            let ptr = b.load(SeqCst);
            if ptr.is_null() {
                // `start_alloc` is called by all threads, no matter if they're using CMR or not.
                // If `ptr` is `null`, it means they were never registered by `cmr::thread_activate`,
                // so it will never be signaled, and hence they don't need to tell anyone they are
                // allocating.
                return None;
            }
            let b: &AtomicBool = unsafe { &*ptr };

            // Mark that we want to allocate
            b.store(true, SeqCst);
            // If some other thread has decided to lock allocation, reset our flag
            while self.lock.load(SeqCst) {
                b.store(false, SeqCst);
                while self.lock.load(SeqCst) {}
                b.store(true, SeqCst);
            }
            Some(b)
        })
    }

    fn end_alloc(&self, b: &AtomicBool) {
        b.store(false, SeqCst);
    }

    /// Return `None` if we already had the lock.
    pub(crate) fn lock(&self) -> Option<AsdGuard> {
        if self.owner.load(SeqCst) == super::thread_id() {
            return None;
        }
        while self.lock.compare_and_swap(false, true, SeqCst) {}
        self.owner.store(super::thread_id(), SeqCst);
        // wait for all other threads to call `end_alloc`
        let thread_bools = super::THREAD_BOOLS.lock();
        for b in thread_bools.iter() {
            while b.load(SeqCst) {}
        }
        Some(AsdGuard)
    }

    pub(crate) fn unlock(&self) {
        self.owner.store(0, SeqCst);
        self.lock.store(false, SeqCst);
    }
}

/// Wrapping allocator for JeMalloc. We need this, as we must make sure that the reclamating thread
/// doesn't signal any thread while it is holding some internal lock in the allocator.
pub(crate) struct WrappedAllocator;

unsafe impl GlobalAlloc for WrappedAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        if let Some(b) = SOME_LOCK.start_alloc() {
            ::std::sync::atomic::compiler_fence(SeqCst);
            let ret = Jemalloc.alloc(layout);
            ::std::sync::atomic::compiler_fence(SeqCst);
            SOME_LOCK.end_alloc(b);
            return ret;
        }
        Jemalloc.alloc(layout)
    }

    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
        jemalloc_free_hack::free(ptr as usize);
    }
}

/// Wrapping allocator for the system allocator. This, as we must make sure that the reclamating
/// thread doesn't signal any thread while it is holding some internal lock in the allocator.
pub(crate) struct WrappedSystemAllocator;

unsafe impl GlobalAlloc for WrappedSystemAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        if let Some(b) = SOME_LOCK.start_alloc() {
            ::std::sync::atomic::compiler_fence(SeqCst);
            let ret = System.alloc(layout);
            ::std::sync::atomic::compiler_fence(SeqCst);
            SOME_LOCK.end_alloc(b);
            return ret;
        }
        System.alloc(layout)
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        System.dealloc(ptr, layout);
    }
}