# frame.rs - source
Source of the Rust file `/home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/buddy_system_allocator-0.6.0/src/frame.rs`.
Keywords: rust, rustlang, rust-lang

    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

    use super::prev_power_of_two;
    use alloc::collections::BTreeSet;
    use core::cmp::min;
    use core::ops::Range;

    #[cfg(feature = "use_spin")]
    use core::ops::Deref;
    #[cfg(feature = "use_spin")]
    use spin::Mutex;

    /// A frame allocator that uses buddy system,
    /// requiring a global allocator
    ///
    /// # Usage
    ///
    /// Create a frame allocator and add some frames to it:
    /// ```
    /// use buddy_system_allocator::*;
    /// let mut frame = FrameAllocator::new();
    /// assert!(frame.alloc(1).is_none());
    ///
    /// frame.add_frame(0, 3);
    /// let num = frame.alloc(1);
    /// assert_eq!(num, Some(2));
    /// let num = frame.alloc(2);
    /// assert_eq!(num, Some(0));
    /// ```
    pub struct FrameAllocator {
        // buddy system with max order of 32
        free_list: [BTreeSet<usize>; 32],

        // statistics
        allocated: usize,
        total: usize,
    }

    impl FrameAllocator {
        /// Create an empty frame allocator
        pub fn new() -> Self {
            FrameAllocator {
                free_list: Default::default(),
                allocated: 0,
                total: 0,
            }
        }

        /// Add a range of frame number [start, end) to the allocator
        pub fn add_frame(&mut self, start: usize, end: usize) {
            assert!(start <= end);

            let mut total = 0;
            let mut current_start = start;

            while current_start < end {
                let lowbit = if current_start > 0 {
                    current_start & (!current_start + 1)
                } else {
                    32
                };
                let size = min(lowbit, prev_power_of_two(end - current_start));
                total += size;

                self.free_list[size.trailing_zeros() as usize].insert(current_start);
                current_start += size;
            }

            self.total += total;
        }

        /// Add a range of frame to the allocator
        pub fn insert(&mut self, range: Range<usize>) {
            self.add_frame(range.start, range.end);
        }

        /// Alloc a range of frames from the allocator, return the first frame of the allocated range
        pub fn alloc(&mut self, count: usize) -> Option<usize> {
            let size = count.next_power_of_two();
            let class = size.trailing_zeros() as usize;
            for i in class..self.free_list.len() {
                // Find the first non-empty size class
                if !self.free_list[i].is_empty() {
                    // Split buffers
                    for j in (class + 1..i + 1).rev() {
                        if let Some(block_ref) = self.free_list[j].iter().next() {
                            let block = *block_ref;
                            self.free_list[j - 1].insert(block + (1 << (j - 1)));
                            self.free_list[j - 1].insert(block);
                            self.free_list[j].remove(&block);
                        } else {
                            return None;
                        }
                    }

                    let result = self.free_list[class].iter().next().clone();
                    if let Some(result_ref) = result {
                        let result = *result_ref;
                        self.free_list[class].remove(&result);
                        self.allocated += size;
                        return Some(result);
                    } else {
                        return None;
                    }
                }
            }
            None
        }

        /// Dealloc a range of frames [frame, frame+count) from the frame allocator.
        /// The range should be exactly the same when it was allocated, as in heap allocator
        pub fn dealloc(&mut self, frame: usize, count: usize) {
            let size = count.next_power_of_two();
            let class = size.trailing_zeros() as usize;

            // Put back into free list
            self.free_list[class].insert(frame);

            // Merge free buddy lists
            let mut current_ptr = frame;
            let mut current_class = class;
            while current_class < self.free_list.len() {
                let buddy = current_ptr ^ (1 << current_class);
                if self.free_list[current_class].remove(&buddy) == true {
                    // Free buddy found
                    current_ptr = min(current_ptr, buddy);
                    current_class += 1;
                    self.free_list[current_class].insert(current_ptr);
                } else {
                    break;
                }
            }

            self.allocated -= size;
        }
    }

    /// A locked version of `FrameAllocator`
    ///
    /// # Usage
    ///
    /// Create a locked frame allocator and add frames to it:
    /// ```
    /// use buddy_system_allocator::*;
    /// let mut frame = LockedFrameAllocator::new();
    /// assert!(frame.lock().alloc(1).is_none());
    ///
    /// frame.lock().add_frame(0, 3);
    /// let num = frame.lock().alloc(1);
    /// assert_eq!(num, Some(2));
    /// let num = frame.lock().alloc(2);
    /// assert_eq!(num, Some(0));
    /// ```
    #[cfg(feature = "use_spin")]
    pub struct LockedFrameAllocator(Mutex<FrameAllocator>);

    #[cfg(feature = "use_spin")]
    impl LockedFrameAllocator {
        /// Creates an empty heap
        pub fn new() -> LockedFrameAllocator {
            LockedFrameAllocator(Mutex::new(FrameAllocator::new()))
        }
    }

    #[cfg(feature = "use_spin")]
    impl Deref for LockedFrameAllocator {
        type Target = Mutex<FrameAllocator>;

        fn deref(&self) -> &Mutex<FrameAllocator> {
            &self.0
        }
    }