Skip to content

Commit

Permalink
vm-allocator: Add an allocator KVM memory slots
Browse files Browse the repository at this point in the history
Add an allocator for KVM memory slots, a finite resource in the kernel
- these need to be manipulated across different crates with a common
dependency on this crate.

Signed-off-by: Rob Bradford <[email protected]>
  • Loading branch information
rbradford committed Nov 24, 2024
1 parent 3c05626 commit 80b2c98
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions vm-allocator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ pub use crate::gsi::GsiAllocator;
#[cfg(target_arch = "x86_64")]
pub use crate::gsi::GsiApic;
pub use crate::system::SystemAllocator;
mod memory_slot;
pub use memory_slot::MemorySlotAllocator;
39 changes: 39 additions & 0 deletions vm-allocator/src/memory_slot.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright © 2024 Rivos Inc
//
// SPDX-License-Identifier: Apache-2.0
//

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};

/// Allocator for KVM memory slots
pub struct MemorySlotAllocator {
next_memory_slot: Arc<AtomicU32>,
memory_slot_free_list: Arc<Mutex<Vec<u32>>>,
}

impl MemorySlotAllocator {
/// Next free memory slot
pub fn next_memory_slot(&self) -> u32 {
if let Some(slot_id) = self.memory_slot_free_list.lock().unwrap().pop() {
return slot_id;
}
self.next_memory_slot.fetch_add(1, Ordering::SeqCst)
}

/// Release memory slot for reuse
pub fn free_memory_slot(&mut self, slot: u32) {
self.memory_slot_free_list.lock().unwrap().push(slot)
}

/// Instantiate struct
pub fn new(
next_memory_slot: Arc<AtomicU32>,
memory_slot_free_list: Arc<Mutex<Vec<u32>>>,
) -> Self {
Self {
next_memory_slot,
memory_slot_free_list,
}
}
}

0 comments on commit 80b2c98

Please sign in to comment.