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
//! Memory management including heap and physical memory.
mod alloc;
mod slob_allocator;

use crate::addressing::{Pa, Va, PAGE_MASK, PAGE_SHIFT};
use crate::sync::SpinLock;
use ::alloc::vec::Vec;
use abyss::boot::Regions;
use core::ops::Range;

/// Initialize the physical memory allocator.
pub unsafe fn init_mm(regions: Regions) {
    extern "C" {
        static __edata_end: u64;
    }

    let edata_end = Va::new(&__edata_end as *const _ as usize).unwrap();

    info!("initialize memory...");
    for region in regions.iter() {
        if region.usable {
            let Range { start, end } = region.addr;
            let (start, end) = (start.into_va().max(edata_end), end.into_va());
            if start < end {
                info!("    Arena: {:?}~{:?}", start, end);
                PALLOC.lock().foster(start, end);
            }
        }
    }
}

// Physical memory allocators.

struct Arena {
    // 0: used, 1: unused
    bitmap: &'static mut [u64],
    start: Va,
    end: Va,
}

impl Arena {
    const EMPTY: Option<Self> = None;
    fn set_used(&mut self, index: usize) {
        let (pos, ofs) = (index / 64, index % 64);
        debug_assert_ne!(self.bitmap[pos] & (1 << ofs), 0);
        self.bitmap[pos] &= !(1 << ofs);
        debug_assert_eq!(self.bitmap[pos] & (1 << ofs), 0);
    }
    fn set_unused(&mut self, index: usize) {
        let (pos, ofs) = (index / 64, index % 64);
        debug_assert_eq!(self.bitmap[pos] & (1 << ofs), 0);
        self.bitmap[pos] |= 1 << ofs;
        debug_assert_ne!(self.bitmap[pos] & (1 << ofs), 0);
    }
    fn alloc(&mut self, cnt: usize, align: usize) -> Option<Va> {
        let mut search = 0;
        while search < self.bitmap.len() * 64 {
            let (mut pos, ofs) = (search / 64, search % 64);
            // search first qword that contains one.
            if ofs % 64 == 0 {
                while self.bitmap[pos] == 0 {
                    pos += 1;
                }
                search = pos * 64;
            }

            let mut cont = 0;
            if align != 0
                && ((unsafe { self.start.into_usize() } >> PAGE_SHIFT) + search) % align != 0
            {
                search += 1;
            } else {
                let start = search;
                loop {
                    // Found!
                    if cont == cnt {
                        for i in start..start + cnt {
                            self.set_used(i);
                        }
                        return Some(self.start + (start << PAGE_SHIFT));
                    }

                    let (pos, ofs) = (search / 64, search % 64);
                    search += 1;
                    if self.bitmap[pos] & (1 << ofs) != 0 {
                        // usable
                        cont += 1;
                    } else {
                        break;
                    }
                }
            }
        }
        None
    }
    fn dealloc(&mut self, va: Va, cnt: usize) {
        let ofs = unsafe { (va.into_usize() - self.start.into_usize()) >> PAGE_SHIFT };
        for i in ofs..ofs + cnt {
            self.set_unused(i);
        }
    }
}

struct PhysicalAllocator {
    inner: [Option<Arena>; 64],
    max_idx: usize,
}

static PALLOC: SpinLock<PhysicalAllocator> = SpinLock::new(PhysicalAllocator {
    inner: [Arena::EMPTY; 64],
    max_idx: 0,
});

impl PhysicalAllocator {
    unsafe fn foster(&mut self, start: Va, end: Va) {
        // Calculate usable page of this region.
        let usable_pages = (end.into_usize() - start.into_usize()) >> PAGE_SHIFT;
        // Each region has alloc bitmap on first N pages.
        let bitmap = core::slice::from_raw_parts_mut(
            start.into_usize() as *mut u64,
            (usable_pages + 63) / 64,
        );
        let len = bitmap.len();
        bitmap.fill(u64::MAX);
        let mut arena = Arena { bitmap, start, end };
        // Pad front.
        for i in 0..((len * 8 + PAGE_MASK) >> PAGE_SHIFT) {
            arena.set_used(i);
        }
        // Pad back.
        for i in usable_pages..((usable_pages + 63) & !63) {
            arena.set_used(i);
        }
        self.inner[self.max_idx] = Some(arena);
        self.max_idx += 1;
    }
}

/// A Page representation.
pub struct Page {
    inner: ContigPages,
}

impl Page {
    /// Allocate a page.
    #[inline]
    pub fn new() -> Option<Self> {
        ContigPages::new(0x1000).map(|inner| Self { inner })
    }

    /// Get virtual address of this page.
    #[inline]
    pub fn va(&self) -> Va {
        self.inner.va
    }

    /// Get physical address of this page.
    #[inline]
    pub fn pa(&self) -> Pa {
        self.inner.va.into_pa()
    }

    /// Consumes the page, returning a pa of the page.
    ///
    /// After calling this function, the caller is responsible for the memory previously managed by the Page.
    /// In particular, the caller should properly release the page by calling the `Page::from_pa`.
    #[inline]
    pub fn into_raw(self) -> Pa {
        core::mem::ManuallyDrop::new(self).pa()
    }

    /// Constructs a page from a pa.
    ///
    /// For this to be safe, the pa must have been taken by `Page::into_raw`.
    ///
    /// ## Safety
    /// This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.
    #[inline]
    pub unsafe fn from_pa(pa: Pa) -> Self {
        let va = pa.into_va();
        let allocator = PALLOC.lock();
        Page {
            inner: ContigPages {
                arena_idx: allocator
                    .inner
                    .iter()
                    .take(allocator.max_idx)
                    .enumerate()
                    .find_map(|(idx, arena)| {
                        let Arena { start, end, .. } = arena.as_ref().unwrap();
                        if (*start..*end).contains(&va) {
                            Some(idx)
                        } else {
                            None
                        }
                    })
                    .expect("Failed to find arena index."),
                va,
                cnt: 1,
            },
        }
    }

    /// Get reference of underlying slice of the Page.
    pub unsafe fn inner(&self) -> &[u8] {
        core::slice::from_raw_parts(self.va().into_usize() as *const u8, 4096)
    }

    /// Get mutable reference of underlying sliceof the Page.
    pub unsafe fn inner_mut(&mut self) -> &mut [u8] {
        core::slice::from_raw_parts_mut(self.va().into_usize() as *mut u8, 4096)
    }
}

/// A contiguous pages representation.
pub struct ContigPages {
    arena_idx: usize,
    va: Va,
    cnt: usize,
}

impl ContigPages {
    /// Allocate a page.
    #[inline]
    pub fn new(size: usize) -> Option<Self> {
        Self::new_with_align(size, 0x1000)
    }

    /// Allocate a page with align
    #[inline]
    pub fn new_with_align(size: usize, align: usize) -> Option<Self> {
        if size != 0 {
            // align up to page size.
            let cnt = (size + PAGE_MASK) >> PAGE_SHIFT;
            let mut allocator = PALLOC.lock();
            let max_idx = allocator.max_idx;
            for (arena_idx, arena) in allocator.inner.iter_mut().take(max_idx).enumerate() {
                if let Some(va) = arena.as_mut().unwrap().alloc(cnt, align >> PAGE_SHIFT) {
                    unsafe {
                        core::slice::from_raw_parts_mut(
                            va.into_usize() as *mut u64,
                            cnt * 0x1000 / core::mem::size_of::<u64>(),
                        )
                        .fill(0);
                    }
                    return Some(Self { arena_idx, va, cnt });
                }
            }
        }
        None
    }

    /// Get virtual address of this page.
    #[inline]
    pub fn va(&self) -> Va {
        self.va
    }

    /// Get physical address of this page.
    #[inline]
    pub fn pa(&self) -> Pa {
        self.va.into_pa()
    }

    /// Split the ContigPages into multiple pages.
    pub fn split(self) -> Vec<Page> {
        let mut out = Vec::new();
        let this = core::mem::ManuallyDrop::new(self);
        for i in 0..this.cnt {
            out.push(Page {
                inner: ContigPages {
                    arena_idx: this.arena_idx,
                    va: this.va + i * 0x1000,
                    cnt: 1,
                },
            })
        }
        out
    }
    /// Constructs a page from a va.
    ///
    /// ## Safety
    /// This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.
    #[inline]
    pub unsafe fn from_va(va: Va, size: usize) -> Self {
        let allocator = PALLOC.lock();
        ContigPages {
            arena_idx: allocator
                .inner
                .iter()
                .take(allocator.max_idx)
                .enumerate()
                .find_map(|(idx, arena)| {
                    let Arena { start, end, .. } = arena.as_ref().unwrap();
                    if (*start..*end).contains(&va) {
                        Some(idx)
                    } else {
                        None
                    }
                })
                .expect("Failed to find arena index."),
            va,
            cnt: size / 4096,
        }
    }
}

impl Drop for ContigPages {
    fn drop(&mut self) {
        let mut allocator = PALLOC.lock();
        allocator.inner[self.arena_idx]
            .as_mut()
            .unwrap()
            .dealloc(self.va, self.cnt);
    }
}

/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
    (addr + align - 1) & !(align - 1)
}