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
pub use alloc::alloc::{GlobalAlloc, Layout};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use hal_core::{
    boot::BootInfo,
    mem::{
        self,
        page::{self, Alloc as PageAlloc},
    },
    PAddr,
};
use mycelium_alloc::{buddy, bump};
use mycelium_util::fmt;

#[derive(Debug)]
pub struct Allocator {
    bump: bump::Alloc<BUMP_REGION_SIZE>,
    allocator: buddy::Alloc<32>,
    /// If true, only the bump region is active.
    bump_mode: AtomicBool,
    allocating: AtomicUsize,
    deallocating: AtomicUsize,
}

/// 1k is enough for anyone.
const BUMP_REGION_SIZE: usize = 1024;

#[derive(Debug, Copy, Clone)]
pub struct State {
    pub(crate) allocating: usize,
    pub(crate) deallocating: usize,
    pub(crate) heap_size: usize,
    pub(crate) allocated: usize,
    pub(crate) min_size: usize,
    pub(crate) bump_mode: bool,
    pub(crate) bump_allocated: usize,
    pub(crate) bump_size: usize,
}

impl Allocator {
    pub const fn new() -> Self {
        Self {
            bump: bump::Alloc::new(),
            bump_mode: AtomicBool::new(true),
            allocator: buddy::Alloc::new(32),
            allocating: AtomicUsize::new(0),
            deallocating: AtomicUsize::new(0),
        }
    }

    pub fn state(&self) -> State {
        State {
            allocating: self.allocating.load(Ordering::Acquire),
            deallocating: self.deallocating.load(Ordering::Acquire),
            bump_mode: self.bump_mode.load(Ordering::Acquire),
            heap_size: self.allocator.total_size(),
            allocated: self.allocator.allocated_size(),
            min_size: self.allocator.min_size(),
            bump_allocated: self.bump.allocated_size(),
            bump_size: self.bump.total_size(),
        }
    }

    pub(crate) fn init(&self, _bootinfo: &impl BootInfo) {
        // XXX(eliza): this sucks
        self.allocator.set_vm_offset(crate::arch::mm::vm_offset());
        tracing::info!("initialized allocator");
    }

    #[inline]
    pub(crate) unsafe fn add_region(&self, region: mem::Region) {
        self.deallocating.fetch_add(1, Ordering::Release);
        tracing::trace!(?region, "adding to page allocator");
        let added = self.allocator.add_region(region).is_ok();
        tracing::trace!(added);
        self.deallocating.fetch_sub(1, Ordering::Release);
        if self.bump_mode.swap(false, Ordering::Release) {
            tracing::debug!("disabled bump allocator mode");
        }
    }

    #[inline]
    pub fn dump_free_lists(&self) {
        self.allocator.dump_free_lists();
    }
}

unsafe impl GlobalAlloc for Allocator {
    #[inline]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        self.allocating.fetch_add(1, Ordering::Release);
        let ptr = if self.bump_mode.load(Ordering::Acquire) {
            GlobalAlloc::alloc(&self.bump, layout)
        } else {
            GlobalAlloc::alloc(&self.allocator, layout)
        };
        self.allocating.fetch_sub(1, Ordering::Release);
        ptr
    }

    #[inline]
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        self.deallocating.fetch_add(1, Ordering::Release);
        if !self.bump.owns(ptr) {
            GlobalAlloc::dealloc(&self.allocator, ptr, layout);
        } else {
            // TODO(eliza): should this be a debug assertion?
            tracing::warn!(
                ?ptr,
                ?layout,
                "an allocation in the bump region was deallocated! this is not \
                great: the bump region should not be used for short-lived \
                allocations"
            );
        }
        self.deallocating.fetch_sub(1, Ordering::Release);
    }
}

unsafe impl<S> PageAlloc<S> for Allocator
where
    buddy::Alloc<32>: PageAlloc<S>,
    S: page::Size,
{
    #[inline]
    fn alloc_range(
        &self,
        size: S,
        len: usize,
    ) -> Result<page::PageRange<PAddr, S>, page::AllocErr> {
        self.allocating.fetch_add(1, Ordering::Release);
        let res = self.allocator.alloc_range(size, len);
        self.allocating.fetch_sub(1, Ordering::Release);
        res
    }

    #[inline]
    fn dealloc_range(&self, range: page::PageRange<PAddr, S>) -> Result<(), page::AllocErr> {
        self.deallocating.fetch_add(1, Ordering::Release);
        let res = self.allocator.dealloc_range(range);
        self.deallocating.fetch_sub(1, Ordering::Release);
        res
    }
}

// === impl State ===

impl State {
    #[inline]
    #[must_use]
    pub fn in_allocator(&self) -> bool {
        self.allocating > 0 || self.deallocating > 0
    }
}

impl fmt::Display for State {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let &Self {
            allocating,
            deallocating,
            heap_size,
            allocated,
            min_size,
            bump_mode,
            bump_allocated,
            bump_size,
        } = self;
        f.write_str("heap stats:\n")?;
        writeln!(f, "  {allocating} cores allocating")?;
        writeln!(f, "  {deallocating} cores deallocating")?;

        if bump_mode {
            writeln!(f, "  bump allocator mode only")?;
        } else {
            let digits = {
                let digits = (heap_size).checked_ilog(10).unwrap_or(0) + 1;
                digits as usize
            };
            let free = heap_size - allocated;
            writeln!(f, "buddy heap:")?;

            writeln!(f, "  {free:>digits$} B free")?;

            writeln!(f, "  {heap_size:>digits$} B total")?;
            writeln!(f, "  {free:>digits$} B free")?;
            writeln!(f, "  {allocated:>digits$} B busy")?;
            writeln!(f, "  {min_size:>digits$} B minimum allocation",)?;
        }

        writeln!(f, "bump region:")?;
        let bump_digits = {
            let digits = (bump_size).checked_ilog(10).unwrap_or(0) + 1;
            digits as usize
        };
        let bump_free = bump_size - bump_allocated;

        writeln!(f, "  {bump_free:>bump_digits$} B free",)?;
        writeln!(f, "  {bump_allocated:>bump_digits$} B used",)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use mycotest::*;

    decl_test! {
        fn basic_alloc() -> TestResult {
            // Let's allocate something, for funsies
            use alloc::vec::Vec;
            let mut v = Vec::new();
            tracing::info!(vec = ?v, vec.addr = ?v.as_ptr());
            v.push(5u64);
            tracing::info!(vec = ?v, vec.addr = ?v.as_ptr());
            v.push(10u64);
            tracing::info!(vec=?v, vec.addr=?v.as_ptr());
            mycotest::assert_eq!(v.pop(), Some(10));
            mycotest::assert_eq!(v.pop(), Some(5));

            Ok(())
        }
    }

    decl_test! {
        fn alloc_big() {
            use alloc::vec::Vec;
            let mut v = Vec::new();

            for i in 0..2048 {
                v.push(i);
            }

            tracing::info!(vec = ?v);
        }
    }
}