Skip to main content

memory/
trait.rs

1use core::ptr::NonNull;
2
3use crate::{CapabilityFlags, Layout};
4
5/// Trait that defines the interface for memory allocators in the Xila system.
6///
7/// Implementors of this trait can be used to manage memory allocation and deallocation
8/// operations with specific capabilities. The trait provides the foundation for
9/// custom memory allocation strategies.
10///
11/// # Safety
12///
13/// All methods in this trait are unsafe because they deal with raw memory and can
14/// cause undefined behavior if used incorrectly, such as:
15/// - Deallocating memory that wasn't allocated with the same allocator
16/// - Using memory after it has been deallocated
17/// - Deallocating the same memory multiple times
18pub trait ManagerTrait: Send + Sync {
19    /// Allocates memory with the specified capabilities and layout.
20    ///
21    /// # Parameters
22    /// * `Capabilities` - Specific requirements for the allocation
23    /// * `Layout` - Size and alignment requirements for the allocation
24    ///
25    /// # Returns
26    /// A pointer to the allocated memory, where the protection is set to [`crate::Protection::READ`], or a null pointer if allocation failed.
27    ///
28    /// # Safety
29    /// This function is unsafe because the caller must ensure that:
30    /// - The returned memory is properly initialized before use
31    /// - The memory is properly deallocated when no longer needed
32    unsafe fn allocate(&self, capabilities: CapabilityFlags, layout: Layout)
33    -> Option<NonNull<u8>>;
34
35    /// Deallocates memory previously allocated by this allocator.
36    ///
37    /// # Parameters
38    /// * `Pointer` - Pointer to the memory to deallocate
39    /// * `Layout` - The layout that was used to allocate the memory
40    ///
41    /// # Safety
42    /// This function is unsafe because the caller must ensure that:
43    /// - The pointer was allocated by this allocator
44    /// - The layout matches the one used for allocation
45    /// - The memory is not used after deallocation
46    /// - The memory is not deallocated multiple times
47    unsafe fn deallocate(&self, pointer: NonNull<u8>, layout: Layout);
48
49    /// Changes the size or alignment of a previously allocated memory block.
50    ///
51    /// On success, the contents are preserved up to the smaller of the two sizes.
52    /// On failure, the original allocation remains valid.
53    ///
54    /// The allocator may move the block according to its ordinary placement policy,
55    /// subject to the original capability requirements.
56    ///
57    /// # Safety
58    ///
59    /// - `old_pointer` must refer to a live allocation from this manager with `old_layout`
60    ///   and the original `capabilities`.
61    /// - On success, access the allocation through the returned pointer and `new_layout`.
62    unsafe fn reallocate(
63        &self,
64        capabilities: CapabilityFlags,
65        old_pointer: NonNull<u8>,
66        old_layout: Layout,
67        new_layout: Layout,
68    ) -> Option<NonNull<u8>> {
69        if new_layout.size() == 0 {
70            return None;
71        }
72        let new_pointer = unsafe { self.allocate(capabilities, new_layout) }?;
73
74        // Copy the old data to the new memory
75
76        let old_size = old_layout.size();
77        let new_size = new_layout.size();
78        if old_size > 0 && new_size > 0 {
79            let old_ptr = old_pointer.as_ptr();
80            let new_ptr = new_pointer.as_ptr();
81            let copy_size = core::cmp::min(old_size, new_size);
82
83            // Check if memory regions overlap
84            let old_end = old_ptr.wrapping_add(old_size);
85            let new_end = new_ptr.wrapping_add(new_size);
86            let overlaps = (old_ptr < new_end) && (new_ptr < old_end);
87
88            if overlaps {
89                // Use copy for overlapping regions (handles overlap correctly)
90                unsafe { core::ptr::copy(old_ptr, new_ptr, copy_size) };
91            } else {
92                // Use copy_nonoverlapping for non-overlapping regions (faster)
93                unsafe { core::ptr::copy_nonoverlapping(old_ptr, new_ptr, copy_size) };
94            }
95        }
96        // Deallocate the old memory
97        unsafe { self.deallocate(old_pointer, old_layout) };
98
99        Some(new_pointer)
100    }
101
102    /// Returns the amount of memory currently used in this allocator.
103    ///
104    /// # Returns
105    /// The number of bytes currently allocated.
106    fn get_used(&self) -> usize;
107
108    /// Returns the amount of memory currently available in this allocator.
109    ///
110    /// # Returns
111    /// The number of bytes available for allocation.
112    fn get_free(&self) -> usize;
113
114    /// Returns the total size of the memory managed by this allocator.
115    ///
116    /// # Returns
117    /// The total number of bytes managed by the allocator.
118    fn get_total_size(&self) -> usize {
119        self.get_used() + self.get_free()
120    }
121
122    /// Flushes the instruction cache for a specific memory region.
123    ///
124    /// This method ensures that any cached instructions in the specified memory
125    /// region are synchronized with main memory. This is particularly important
126    /// on architectures with separate instruction and data caches when code
127    /// has been modified at runtime.
128    ///
129    /// # Parameters
130    /// * `Address` - Pointer to the start of the memory region to flush
131    /// * `Size` - Size in bytes of the memory region to flush
132    ///
133    /// # Note
134    /// The default implementation does nothing and can be overridden by specific
135    /// allocators that need to handle instruction cache management.
136    fn flush_instruction_cache(&self, _address: NonNull<u8>, _size: usize) {
137        // Default implementation does nothing, can be overridden by specific allocators
138    }
139
140    /// Flushes the data cache to ensure memory coherency.
141    ///
142    /// This method ensures that any cached data is written back to main memory
143    /// and that the cache is synchronized. This is important for maintaining
144    /// memory coherency, especially in multi-core systems or when dealing with
145    /// memory-mapped I/O operations.
146    ///
147    /// # Note
148    /// The default implementation does nothing and can be overridden by specific
149    /// allocators that need to handle data cache management.
150    fn flush_data_cache(&self) {
151        // Default implementation does nothing, can be overridden by specific allocators
152    }
153
154    /// Returns the page size used by this memory allocator.
155    ///
156    /// The page size is the smallest unit of memory that can be allocated
157    /// by the underlying memory management system. This information is useful
158    /// for optimizing memory allocation patterns and understanding alignment
159    /// requirements.
160    ///
161    /// # Returns
162    /// The page size in bytes used by this allocator.
163    ///
164    /// # Note
165    /// The default implementation returns 4096 bytes (4 KiB), which is a common
166    /// page size on many architectures. Specific allocators can override this
167    /// to return the actual page size of their underlying memory management system.
168    fn get_page_size(&self) -> usize {
169        // Default implementation returns a common page size, can be overridden by specific allocators
170        4096 // 4 KiB is a common page size
171    }
172}