1 // Copyright © 2024 Rivos Inc 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 // 5 6 use std::sync::atomic::{AtomicU32, Ordering}; 7 use std::sync::{Arc, Mutex}; 8 9 /// Allocator for KVM memory slots 10 pub struct MemorySlotAllocator { 11 next_memory_slot: Arc<AtomicU32>, 12 memory_slot_free_list: Arc<Mutex<Vec<u32>>>, 13 } 14 15 impl MemorySlotAllocator { 16 /// Next free memory slot 17 pub fn next_memory_slot(&self) -> u32 { 18 if let Some(slot_id) = self.memory_slot_free_list.lock().unwrap().pop() { 19 return slot_id; 20 } 21 self.next_memory_slot.fetch_add(1, Ordering::SeqCst) 22 } 23 24 /// Release memory slot for reuse 25 pub fn free_memory_slot(&mut self, slot: u32) { 26 self.memory_slot_free_list.lock().unwrap().push(slot) 27 } 28 29 /// Instantiate struct 30 pub fn new( 31 next_memory_slot: Arc<AtomicU32>, 32 memory_slot_free_list: Arc<Mutex<Vec<u32>>>, 33 ) -> Self { 34 Self { 35 next_memory_slot, 36 memory_slot_free_list, 37 } 38 } 39 } 40