summaryrefslogtreecommitdiff
path: root/crates/alloc_vma_tree/src/lib.rs
blob: 38dd3129d019befd422e354ea65dc84a843826fb (plain)
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
//! A data structure to manage virtual address ranges.
#![no_std]

use allocator_api2::alloc::{AllocError, Allocator, Layout};
use contracts::{ensures, requires};
use core::{marker::PhantomData, mem::MaybeUninit, ops::Range, ptr::NonNull};
use vernos_utils::cold;

/// A data structure to manage virtual address ranges.
///
/// This is a pair of sorted trees of virtual memory areas. The two trees contain the same nodes,
/// but one is sorted by size (so we can find a best-fit allocation) and one is sorted by the start
/// address (so we can find a neighbor to merge free VMAs with).
#[derive(Default)]
pub struct VMATree<const PAGE_SIZE_BITS: usize, ALLOCATOR: Allocator> {
    roots: Option<(
        VMARef<PAGE_SIZE_BITS, AddrTree>,
        VMARef<PAGE_SIZE_BITS, SizeTree>,
    )>,
    allocator: ALLOCATOR,
}

impl<const PAGE_SIZE_BITS: usize, ALLOCATOR: Allocator> VMATree<PAGE_SIZE_BITS, ALLOCATOR> {
    /// Creates a new VMATree that will use the given allocator.
    pub const fn new_in(allocator: ALLOCATOR) -> VMATree<PAGE_SIZE_BITS, ALLOCATOR> {
        VMATree {
            roots: None,
            allocator,
        }
    }

    /// Adds a new VMA to the tree.
    ///
    /// The VMA will be marked as free.
    #[requires(addrs.start & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    #[requires(addrs.end & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    pub fn add(&mut self, addrs: Range<usize>) -> Result<(), AllocError> {
        if let Some((addr_root, size_root)) = &mut self.roots {
            todo!()
        } else {
            cold();
            let node = VMANode::new_in(addrs, &self.allocator)?;
            self.roots = Some((VMARef(node, PhantomData), VMARef(node, PhantomData)));
            Ok(())
        }
    }
}

impl<const PAGE_SIZE_BITS: usize, ALLOCATOR: Allocator> Drop
    for VMATree<PAGE_SIZE_BITS, ALLOCATOR>
{
    fn drop(&mut self) {
        todo!()
    }
}

unsafe impl<const PAGE_SIZE_BITS: usize, ALLOCATOR: Allocator> Send
    for VMATree<PAGE_SIZE_BITS, ALLOCATOR>
where
    ALLOCATOR: Send,
{
}

/// A non-null pointer to a VMA node in one of the two trees.
struct VMARef<const PAGE_SIZE_BITS: usize, KIND: TreeKind>(
    NonNull<VMANode<PAGE_SIZE_BITS>>,
    PhantomData<KIND>,
);

impl<const PAGE_SIZE_BITS: usize, KIND: TreeKind> VMARef<PAGE_SIZE_BITS, KIND> {
    /// Returns the parent, if there was one.
    ///
    /// # Safety
    ///
    /// - The pointer must be valid.
    pub unsafe fn parent(self) -> Option<VMARef<PAGE_SIZE_BITS, KIND>> {
        let ptr = KIND::parent(self.0);
        if self == ptr {
            None
        } else {
            Some(ptr)
        }
    }

    /// Returns the left child, if there was one.
    ///
    /// # Safety
    ///
    /// - The pointer must be valid.
    pub unsafe fn left(self) -> Option<VMARef<PAGE_SIZE_BITS, KIND>> {
        let ptr = KIND::left(self.0);
        if self == ptr {
            None
        } else {
            Some(ptr)
        }
    }

    /// Returns the right child, if there was one.
    ///
    /// # Safety
    ///
    /// - The pointer must be valid.
    pub unsafe fn right(self) -> Option<VMARef<PAGE_SIZE_BITS, KIND>> {
        let ptr = KIND::right(self.0);
        if self == ptr {
            None
        } else {
            Some(ptr)
        }
    }
}

impl<const PAGE_SIZE_BITS: usize, KIND: TreeKind> Clone for VMARef<PAGE_SIZE_BITS, KIND> {
    fn clone(&self) -> VMARef<PAGE_SIZE_BITS, KIND> {
        *self
    }
}

impl<const PAGE_SIZE_BITS: usize, KIND: TreeKind> Copy for VMARef<PAGE_SIZE_BITS, KIND> {}

impl<const PAGE_SIZE_BITS: usize, KIND: TreeKind> Eq for VMARef<PAGE_SIZE_BITS, KIND> {}

impl<const PAGE_SIZE_BITS: usize, KIND: TreeKind> PartialEq for VMARef<PAGE_SIZE_BITS, KIND> {
    fn eq(&self, other: &VMARef<PAGE_SIZE_BITS, KIND>) -> bool {
        self.0 == other.0
    }
}

/// A "physical" VMA node.
struct VMANode<const PAGE_SIZE_BITS: usize> {
    addr_and_state: usize,
    size_and_balance: usize,

    /// A self-pointer if we're the root.
    addr_parent: VMARef<PAGE_SIZE_BITS, AddrTree>,

    /// A self-pointer if we have no left child.
    addr_left_child: VMARef<PAGE_SIZE_BITS, AddrTree>,

    /// A self-pointer if we have no right child.
    addr_right_child: VMARef<PAGE_SIZE_BITS, AddrTree>,

    /// A self-pointer if we're the root.
    size_parent: VMARef<PAGE_SIZE_BITS, SizeTree>,

    /// A self-pointer if we have no left child.
    size_left_child: VMARef<PAGE_SIZE_BITS, SizeTree>,

    /// A self-pointer if we have no right child.
    size_right_child: VMARef<PAGE_SIZE_BITS, SizeTree>,
}

impl<const PAGE_SIZE_BITS: usize> VMANode<PAGE_SIZE_BITS> {
    /// Allocates a new node in the given allocator.
    ///
    /// The node has the given range of addresses and is in the `Free` state. All of its pointers
    /// are self-pointers.
    #[requires(PAGE_SIZE_BITS > 0)]
    #[requires(addrs.start & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    #[requires(addrs.end & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    pub fn new_in<ALLOCATOR: Allocator>(
        addrs: Range<usize>,
        allocator: &ALLOCATOR,
    ) -> Result<NonNull<VMANode<PAGE_SIZE_BITS>>, AllocError> {
        let layout = Layout::new::<MaybeUninit<Self>>();
        let mut ptr: NonNull<MaybeUninit<Self>> = allocator.allocate(layout)?.cast();

        // SAFETY: This needs to be OK for the allocator to meet the conditions of its trait.
        VMANode::init_in(unsafe { ptr.as_mut() }, addrs);

        Ok(ptr.cast())
    }

    /// Initializes a node.
    ///
    /// The node has the given range of addresses and is in the `Free` state. All of its pointers
    /// are self-pointers.
    #[requires(PAGE_SIZE_BITS > 0)]
    #[requires(addrs.start & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    #[requires(addrs.end & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    pub fn init_in(maybe_uninit: &mut MaybeUninit<VMANode<PAGE_SIZE_BITS>>, addrs: Range<usize>) {
        let ptr = NonNull::from(&*maybe_uninit).cast();
        maybe_uninit.write(VMANode {
            addr_and_state: addrs.start,
            size_and_balance: (addrs.end - addrs.start)
                | ((Balance::Balanced as usize) << 2)
                | (Balance::Balanced as usize),
            addr_parent: VMARef(ptr, PhantomData),
            addr_left_child: VMARef(ptr, PhantomData),
            addr_right_child: VMARef(ptr, PhantomData),
            size_parent: VMARef(ptr, PhantomData),
            size_left_child: VMARef(ptr, PhantomData),
            size_right_child: VMARef(ptr, PhantomData),
        });
    }

    /// Returns the range of addresses represented by this node.
    #[ensures(ret.start & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    #[ensures(ret.end & ((1 << PAGE_SIZE_BITS) - 1) == 0)]
    pub fn addrs(&self) -> Range<usize> {
        let addr = self.addr_and_state & !((1 << PAGE_SIZE_BITS) - 1);
        let size = self.size_and_balance & !((1 << PAGE_SIZE_BITS) - 1);
        addr..addr + size
    }

    /// Returns the state of the addresses represented by this node.
    #[requires(PAGE_SIZE_BITS >= 1)]
    pub fn state(&self) -> State {
        match self.addr_and_state & 1 {
            0 => State::Free,
            _ => State::Used,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Balance {
    LeftHeavy = 0,
    Balanced = 1,
    RightHeavy = 2,
}

impl Balance {
    pub fn from_bits(bits: usize) -> Balance {
        match bits {
            0 => Balance::LeftHeavy,
            1 => Balance::Balanced,
            2 => Balance::RightHeavy,
            _ => panic!("invalid Balance: {bits}"),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum State {
    Free,
    Used,
}

trait TreeKind: Sized {
    unsafe fn balance<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> Balance;

    unsafe fn parent<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self>;

    unsafe fn left<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self>;

    unsafe fn right<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self>;
}

enum AddrTree {}

impl TreeKind for AddrTree {
    #[requires(PAGE_SIZE_BITS >= 4)]
    unsafe fn balance<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> Balance {
        let size_and_balance = (*node.as_ptr()).size_and_balance;
        Balance::from_bits(size_and_balance & 0b11)
    }

    unsafe fn parent<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self> {
        (*node.as_ptr()).addr_parent
    }

    unsafe fn left<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self> {
        (*node.as_ptr()).addr_left_child
    }

    unsafe fn right<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self> {
        (*node.as_ptr()).addr_right_child
    }
}

enum SizeTree {}

impl TreeKind for SizeTree {
    #[requires(PAGE_SIZE_BITS >= 4)]
    unsafe fn balance<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> Balance {
        let size_and_balance = (*node.as_ptr()).size_and_balance;
        Balance::from_bits((size_and_balance >> 2) & 0b11)
    }

    unsafe fn parent<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self> {
        (*node.as_ptr()).size_parent
    }

    unsafe fn left<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self> {
        (*node.as_ptr()).size_left_child
    }

    unsafe fn right<const PAGE_SIZE_BITS: usize>(
        node: NonNull<VMANode<PAGE_SIZE_BITS>>,
    ) -> VMARef<PAGE_SIZE_BITS, Self> {
        (*node.as_ptr()).size_right_child
    }
}