1#![allow(dead_code)]
17
18use core::alloc::{GlobalAlloc, Layout};
19use core::ptr::{null_mut, NonNull};
20use core::sync::atomic::{AtomicBool, Ordering};
21use rlsf::Tlsf;
22
23type TheTlsf = Tlsf<'static, u32, u16, 25, 16>;
28
29struct TlsfHeap {
31 tlsf: TheTlsf,
32 total: usize,
33 used: usize,
34}
35
36impl TlsfHeap {
37 const fn empty() -> Self {
39 Self {
40 tlsf: Tlsf::new(),
41 total: 0,
42 used: 0,
43 }
44 }
45
46 unsafe fn init(&mut self, start: usize, size: usize) {
51 self.total = size;
52 self.used = 0;
53 let slice = core::ptr::slice_from_raw_parts_mut(start as *mut u8, size);
54 if let Some(nn) = NonNull::new(slice) {
55 self.tlsf.insert_free_block_ptr(nn);
56 }
57 }
58
59 unsafe fn alloc(&mut self, layout: Layout) -> *mut u8 {
60 if self.total > 0 {
63 let free = self.total.saturating_sub(self.used);
64 if free.saturating_sub(layout.size()) < OS_HEAP_RESERVE
65 && !crate::kernel::scheduler::is_current_process_critical()
66 {
67 crate::warn!(
68 "[MEM] [ALLOC FAIL (OS RESERVE)] size={} free={} reserve={}",
69 layout.size(),
70 free,
71 OS_HEAP_RESERVE
72 );
73 return null_mut();
74 }
75 }
76 match self.tlsf.allocate(layout) {
77 Some(p) => {
78 self.used = self.used.saturating_add(layout.size());
79 MEM_LEDGER.on_alloc(
81 crate::kernel::scheduler::core_id(),
82 layout.size(),
83 self.total.saturating_sub(self.used),
84 );
85 p.as_ptr()
86 }
87 None => {
88 crate::error!(
89 "[MEM] [ALLOC FAIL] size={} align={} used={} total={}",
90 layout.size(),
91 layout.align(),
92 self.used,
93 self.total
94 );
95 null_mut()
96 }
97 }
98 }
99
100 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
101 self.tlsf.deallocate(ptr, layout.align());
103 self.used = self.used.saturating_sub(layout.size());
104 MEM_LEDGER.on_dealloc(
105 crate::kernel::scheduler::core_id(),
106 layout.size(),
107 self.total.saturating_sub(self.used),
108 );
109 }
110
111 fn free_space(&self) -> usize {
112 self.total.saturating_sub(self.used)
113 }
114}
115
116#[global_allocator]
118static ALLOCATOR: Locked<TlsfHeap> = Locked::new(TlsfHeap::empty());
119
120pub const KERNEL_HEAP_SIZE: usize = 768 * 1024 * 1024;
139
140pub const OS_HEAP_RESERVE: usize = 32 * 1024 * 1024;
143
144pub static MEM_LEDGER: crate::kernel::mem_quota::Ledger = crate::kernel::mem_quota::Ledger::new();
148
149static mut TOTAL_HEAP_SIZE: usize = 0;
151
152pub fn heap_total() -> usize {
154 unsafe { TOTAL_HEAP_SIZE }
156}
157
158pub fn init(start: usize, size: usize) {
160 unsafe {
161 TOTAL_HEAP_SIZE = size;
162 ALLOCATOR.lock().init(start, size);
163 }
164}
165
166pub fn get_heap_stats() -> (usize, usize) {
170 let total = unsafe { TOTAL_HEAP_SIZE };
171 let free = ALLOCATOR.lock().free_space();
172 (total.saturating_sub(free), total)
173}
174
175pub fn check_heap_integrity() -> bool {
180 false
181}
182
183pub fn force_release_lock(cid: i16) {
186 unsafe {
187 ALLOCATOR.force_release_if_core(cid);
188 }
189}
190
191pub static ALLOC_COUNT: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
193
194unsafe impl GlobalAlloc for Locked<TlsfHeap> {
195 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
196 ALLOC_COUNT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
197 self.lock().alloc(layout)
198 }
199
200 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
201 if let Some(nn) = NonNull::new(ptr) {
202 self.lock().dealloc(nn, layout);
203 }
204 }
205}
206
207pub struct Locked<A> {
214 inner: spin::Mutex<A>,
215 holder: core::sync::atomic::AtomicI16,
217}
218
219impl<A> Locked<A> {
220 pub const fn new(inner: A) -> Self {
222 Self {
223 inner: spin::Mutex::new(inner),
224 holder: core::sync::atomic::AtomicI16::new(-1),
225 }
226 }
227
228 pub fn lock(&self) -> LockedGuard<'_, A> {
242 let guard = self.inner.lock();
243 self.holder.store(
244 crate::kernel::scheduler::core_id() as i16,
245 Ordering::Relaxed,
246 );
247 LockedGuard {
248 guard: Some(guard),
249 holder: &self.holder,
250 }
251 }
252
253 pub unsafe fn force_release_if_core(&self, cid: i16) {
260 if self.holder.load(Ordering::Relaxed) == cid {
261 self.holder.store(-1, Ordering::Relaxed);
262 self.inner.force_unlock();
263 }
264 }
265}
266
267pub struct LockedGuard<'a, A> {
268 guard: Option<spin::MutexGuard<'a, A>>,
269 holder: &'a core::sync::atomic::AtomicI16,
270}
271
272impl<'a, A> Drop for LockedGuard<'a, A> {
273 fn drop(&mut self) {
274 self.holder.store(-1, Ordering::Relaxed);
275 self.guard.take(); }
277}
278
279impl<'a, A> core::ops::Deref for LockedGuard<'a, A> {
280 type Target = A;
281 fn deref(&self) -> &A {
282 match self.guard.as_ref() {
283 Some(g) => g,
284 None => loop {
285 core::hint::spin_loop();
286 },
287 }
288 }
289}
290
291impl<'a, A> core::ops::DerefMut for LockedGuard<'a, A> {
292 fn deref_mut(&mut self) -> &mut A {
293 match self.guard.as_mut() {
294 Some(g) => g,
295 None => loop {
296 core::hint::spin_loop();
297 },
298 }
299 }
300}
301
302mod spin {
307 use super::*;
308
309 pub struct Mutex<T> {
310 lock: AtomicBool,
311 data: core::cell::UnsafeCell<T>,
312 }
313
314 unsafe impl<T: Send> Sync for Mutex<T> {}
315 unsafe impl<T: Send> Send for Mutex<T> {}
316
317 pub struct MutexGuard<'a, T> {
318 mutex: &'a Mutex<T>,
319 interrupt_state: bool,
320 }
321
322 impl<T> Mutex<T> {
323 pub const fn new(value: T) -> Self {
324 Self {
325 lock: AtomicBool::new(false),
326 data: core::cell::UnsafeCell::new(value),
327 }
328 }
329
330 pub fn lock(&self) -> MutexGuard<'_, T> {
331 let irq_enabled = is_interrupt_enabled();
332 if irq_enabled {
333 disable_interrupts();
334 }
335
336 while self
337 .lock
338 .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
339 .is_err()
340 {
341 core::hint::spin_loop();
342 }
343
344 MutexGuard {
345 mutex: self,
346 interrupt_state: irq_enabled,
347 }
348 }
349
350 pub unsafe fn force_unlock(&self) {
356 self.lock.store(false, Ordering::Release);
357 }
358 }
359
360 impl<'a, T> core::ops::Deref for MutexGuard<'a, T> {
361 type Target = T;
362 fn deref(&self) -> &Self::Target {
363 unsafe { &*self.mutex.data.get() }
364 }
365 }
366
367 impl<'a, T> core::ops::DerefMut for MutexGuard<'a, T> {
368 fn deref_mut(&mut self) -> &mut Self::Target {
369 unsafe { &mut *self.mutex.data.get() }
370 }
371 }
372
373 impl<'a, T> Drop for MutexGuard<'a, T> {
374 fn drop(&mut self) {
375 self.mutex.lock.store(false, Ordering::Release);
376 if self.interrupt_state {
377 enable_interrupts();
378 }
379 }
380 }
381
382 pub(super) fn is_interrupt_enabled() -> bool {
383 let daif: u64;
384 unsafe {
385 core::arch::asm!("mrs {}, daif", out(reg) daif);
386 }
387 (daif & (1 << 7)) == 0
388 }
389
390 pub(super) fn disable_interrupts() {
391 unsafe {
392 core::arch::asm!("msr daifset, #2", options(nomem, nostack));
393 }
394 }
395
396 pub(super) fn enable_interrupts() {
397 unsafe {
398 core::arch::asm!("msr daifclr, #2", options(nomem, nostack));
399 }
400 }
401}