//! # Allocate crate //! //! Provides the Global allocator and methods //! to create special purpose allocators. use alloc::alloc::{GlobalAlloc,Layout}; use crate::sync::NullLock; use crate::sync::interface::Mutex; use core::fmt; use core::fmt::{Debug,Formatter}; use crate::vprintln; /// # Initialize Queue /// - Name: Symbol name /// - Size: Number of elements /// - Default: Default value /// - Type: Data Type macro_rules! init_queue { ($name:tt,$size:tt,$default:tt,$type:ty) => { init_queue!{@gen [$name,$size,$default,$type,concat!("# ", stringify!($type), " Queue Allocator")]} }; (@gen [$name:tt,$size:tt,$default:tt,$type:ty,$doc:expr]) => { #[doc = $doc] #[link_section = ".data.alloc"] pub static $name: QueueAllocator<'static, $type, {$size+2}> = QueueAllocator::<$type, {$size+2}>{inner: NullLock::new([QueueItem{data: $default, next: None}; {$size+2}])}; }; } #[derive(Copy,Clone)] /// # Queue Item /// /// Encapsulates a data element and a pointer to /// the next `Queue` item pub struct QueueItem<'a, T: Sized> { /// # Data /// /// The encapsulated data data: T, /// # Pointer to the next item /// /// Stores either `None` or points /// to the next item. next: Option<*mut QueueItem<'a, T>>, } impl QueueItem<'_,T> { /// # Get the inner data /// /// Returns a borrow of the underlying data. pub fn inner(&mut self) -> &mut T { &mut self.data } /// # Get pointer to inner data pub fn ptr(&mut self) -> *mut u8 { self.inner() as *mut T as *mut u8 } } /// # Sharing Thread Safety for QueueItem unsafe impl Send for QueueItem<'_,T> {} impl Debug for QueueItem<'_,T> { /// # Debug formatter for `QueueItem` /// /// Output the encapsulated data fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { #[cfg(feature="verbose")] return write!(f, "{:?} {:x} {:?}", self.data, self as *const QueueItem<'_,T> as usize, self.next); #[cfg(not(feature="verbose"))] return write!(f, "{:?}", self.data); } } /// # Queue Allocator /// /// Structure to store a pool of allocated data structures. pub struct QueueAllocator<'a, T: Sized, const COUNT: usize> { /// # Synchronized Pool of items /// /// Stores synchronization wrapper around the data pool pub inner: NullLock<[QueueItem<'a, T>;COUNT]>, } /// # Sharing Thread Safety for QueueAllocator unsafe impl Send for QueueAllocator<'_,T,COUNT> {} impl<'a, T: Sized,const COUNT: usize> QueueAllocator<'a, T, COUNT> { /// # Initialization of Fixed-Size Pool /// /// Establishes the header and footer of the queue /// as the first and second elements respectively. /// All of the internal elements point to the next /// one and the final element points to `None` pub fn init(&self) { vprintln!("QA: Initializing Queue Allocator!"); self.inner.lock(|queue| { vprintln!("QA: Clearing internal references..."); for idx in 2..COUNT { if idx != COUNT-1 { queue[idx].next = Some(&mut queue[idx+1] as *mut QueueItem<'a, T>); } else { queue[idx].next = None; } } vprintln!("QA: Initializing head and tail..."); queue[0].next = Some(&mut queue[2] as *mut QueueItem<'a, T>); queue[1].next = Some(&mut queue[COUNT-1] as *mut QueueItem<'a, T>); }); vprintln!("QA: Initialized Queue Allocator!"); } /// # Allocate Data /// /// If there is a data chunk available, /// return it, otherwise return `None` #[allow(dead_code)] pub fn alloc(&self) -> Option<&mut QueueItem<'a,T>> { vprintln!("QA: Allocating chunk!"); return self.inner.lock(|pool| { if let Some(entry) = pool[0].next { vprintln!("QA: Found chunk!"); pool[0].next = unsafe { (*entry).next }; unsafe { (*entry).next = None; } match pool[0].next { None => { pool[1].next = None } _ => {} } vprintln!("QA: \x1b[92mAllocated {:x}\x1b[0m", unsafe{(*entry).ptr() as usize}); return Some(unsafe{&mut *entry as &mut QueueItem<'a,T>}); } else { vprintln!("QA: No chunks available!"); return None; } }); } /// # Free /// /// Add the item to the end of the queue. /// If there were no items, set it as the head. #[allow(dead_code)] pub fn free(&self, freed_item: &mut QueueItem<'a,T>) { vprintln!("QA: Deallocating chunk!"); self.inner.lock(|pool| { freed_item.next = None; match pool[1].next { None => { pool[0].next = Some(freed_item as *mut QueueItem<'a,T>); } Some(entry) => { unsafe { (*entry).next = Some(freed_item as *mut QueueItem<'a,T>); } } } pool[1].next = Some(freed_item as *mut QueueItem<'a,T>); vprintln!("QA: \x1b[91mDeallocated {:x}\x1b[0m", freed_item.ptr() as usize); }); } } impl Debug for QueueAllocator<'_,T,COUNT> { /// # Debug Formatted Output /// /// Output each data point in the array with /// its debug formatter. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.inner.lock(|queue| { #[cfg(feature="verbose")] return write!(f, "{:?}", queue); #[cfg(not(feature="verbose"))] return write!(f, "{:?}", queue); }) } } /// # u256 struct /// /// 256 bit size field #[derive(Copy,Clone)] pub struct U256(u128,u128); impl U256 { pub const fn new() -> Self { U256(0,0) } } /// # u512 struct /// /// 512 bit size field #[derive(Copy,Clone)] pub struct U512(U256,U256); impl U512 { pub const fn new() -> Self { U512(U256::new(), U256::new()) } } /// # u1024 struct /// /// 1024 bit size field #[derive(Copy,Clone)] pub struct U1024(U512,U512); impl U1024 { pub const fn new() -> Self { U1024(U512::new(), U512::new()) } } /// # u2048 struct /// /// 2048 bit size field #[derive(Copy,Clone)] pub struct U2048(U1024,U1024); impl U2048 { pub const fn new() -> Self { U2048(U1024::new(), U1024::new()) } } /// # u4096 struct /// /// 4096 bit size field #[derive(Copy,Clone)] pub struct U4096(U2048,U2048); impl U4096 { pub const fn new() -> Self { U4096(U2048::new(), U2048::new()) } } /// # Grand Allocator /// /// The structure that uses different sized pools and allocates memory chunks pub struct GrandAllocator { } /// # The number of elements of each size const GRAND_ALLOC_SIZE: usize = 64; init_queue!(U8_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u8); init_queue!(U16_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u16); init_queue!(U32_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u32); init_queue!(U64_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u64); init_queue!(U128_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u128); init_queue!(U256_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U256::new()}, U256); init_queue!(U512_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U512::new()}, U512); init_queue!(U1024_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U1024::new()}, U1024); init_queue!(U2048_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U2048::new()}, U2048); init_queue!(U4096_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U4096::new()}, U4096); impl GrandAllocator { pub fn init(&self) -> Result<(), &'static str> { vprintln!("GA: \x1b[93mInit U8 Pool\x1b[0m"); U8_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U16 Pool\x1b[0m"); U16_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U32 Pool\x1b[0m"); U32_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U64 Pool\x1b[0m"); U64_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U128 Pool\x1b[0m"); U128_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U256 Pool\x1b[0m"); U256_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U512 Pool\x1b[0m"); U512_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U1024 Pool\x1b[0m"); U1024_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U2048 Pool\x1b[0m"); U2048_GRAND_ALLOC.init(); vprintln!("GA: \x1b[93mInit U4096 Pool\x1b[0m"); U4096_GRAND_ALLOC.init(); vprintln!("GA: \x1b[94mPools Initialized!\x1b[0m"); Ok(()) } } unsafe impl GlobalAlloc for GrandAllocator { /// # Allocator /// /// Allocate the fixed size chunks unsafe fn alloc(&self, layout: Layout) -> *mut u8 { vprintln!("GA: Allocating chunk of size {}!", layout.size()); match layout.size() { 1 => { match U8_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 2 => { match U16_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 3..=4 => { match U32_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 5..=8 => { match U64_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 9..=16 => { match U128_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 17..=32 => { match U256_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 33..=64 => { match U512_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 65..=128 => { match U1024_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 129..=256 => { match U2048_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } 257..=512 => { match U4096_GRAND_ALLOC.alloc() { None => { panic!("No cells to allocate!"); } Some(elem) => { return (*elem).ptr(); } } } _ => { panic!("No allocators for size {}!", layout.size()); } } } /// # Deallocate /// /// Deallocate the fixed size chunks by searching for them unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { vprintln!("GA: Deallocating chunk of size {}!", layout.size()); match layout.size() { 1 => { U8_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U8_GRAND_ALLOC.free(&mut pool[index+2]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); } 2 => { U16_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U16_GRAND_ALLOC.free(&mut pool[index+2]); }); } 3..=4 => { U32_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U32_GRAND_ALLOC.free(&mut pool[index+2]); }); } 5..=8 => { U64_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U64_GRAND_ALLOC.free(&mut pool[index+2]); }); } 9..=16 => { U128_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U128_GRAND_ALLOC.free(&mut pool[index+2]); }); } 17..=32 => { U256_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U256_GRAND_ALLOC.free(&mut pool[index+2]); }); } 33..=64 => { U512_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U512_GRAND_ALLOC.free(&mut pool[index+2]); }); } 65..=128 => { U1024_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U1024_GRAND_ALLOC.free(&mut pool[index+2]); }); } 129..=256 => { U2048_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U2048_GRAND_ALLOC.free(&mut pool[index+2]); }); } 257..=512 => { U4096_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[3].ptr() as usize) - (pool[2].ptr() as usize); let diff: usize = (ptr as usize) - (pool[2].ptr() as usize); let index: usize = diff/spacing; assert!(index < GRAND_ALLOC_SIZE, "{} is out of the allocation bounds ({})", index, GRAND_ALLOC_SIZE); assert_eq!(diff % spacing, 0, "{} is not aligned with the spacings and so it must not have been allocated by the Grand Allocator", diff % spacing); U4096_GRAND_ALLOC.free(&mut pool[index+2]); }); } _ => { panic!("No deallocators for size {}!", layout.size()); } } } } /// # Grand Allocator /// /// The allocator of allocators. It hands out fixed sized memory chunks. #[global_allocator] pub static ALLOCATOR: GrandAllocator = GrandAllocator{}; /// # Global Allocator /// /// Returns a borrow for the Global Allocator pub fn alloc() -> &'static crate::mem::alloc::GrandAllocator { vprintln!("AL: Getting global allocator!"); &crate::mem::alloc::ALLOCATOR }