1use crate::{arch::xshim::PhysAddr, memory, sync::SpinLock};
40use core::{
41 alloc::{GlobalAlloc, Layout},
42 ptr,
43 sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
44};
45
46const SLAB_SIZES: [usize; 26] = [
64 8, 16, 24, 32, 48, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 640, 768, 896,
65 1024, 1280, 1536, 1792, 2048,
66];
67const NUM_SLABS: usize = SLAB_SIZES.len();
68const MAX_SLAB_SIZE: usize = SLAB_SIZES[NUM_SLABS - 1] - REDZONE_TAIL;
72
73#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74pub enum KernelHeapBackend {
75 Slab,
76 Vmalloc,
77}
78
79#[derive(Clone, Copy, Debug, Eq, PartialEq)]
80pub enum KernelHeapAllocError {
81 InvalidLayout,
82 AlignmentExceedsKernelPage {
84 align: usize,
85 },
86 SlabRefillFailed {
87 effective: usize,
88 class_size: usize,
89 },
90 Vmalloc(memory::vmalloc::VmallocError),
91}
92
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94pub struct KernelHeapFailureSnapshot {
95 pub backend: KernelHeapBackend,
96 pub requested_size: usize,
97 pub align: usize,
98 pub effective_size: usize,
99 pub error: KernelHeapAllocError,
100}
101
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub struct SlabDiagSnapshot {
104 pub pages_allocated: usize,
105 pub pages_reclaimed: usize,
106 pub pages_live: usize,
107}
108
109#[inline]
110pub(crate) fn classify_kernel_heap_backend(layout: Layout) -> KernelHeapBackend {
111 let effective = layout.size().max(layout.align());
112 if effective <= MAX_SLAB_SIZE {
113 KernelHeapBackend::Slab
114 } else {
115 KernelHeapBackend::Vmalloc
116 }
117}
118
119const HEAP_POISON_ENABLED: bool = cfg!(feature = "heap-poison");
140const POISON_BYTE: u8 = 0xDE;
142const SLAB_CANARY: u32 = 0xDEAD_BEEF;
144const REDZONE_TAIL: usize = 8;
148
149#[repr(C)]
167struct SlabPageHeader {
168 next_partial: *mut SlabPageHeader,
170 free_head: *mut u8,
172 free_count: u32,
174 total_blocks: u32,
176}
177
178unsafe impl Send for SlabPageHeader {}
180unsafe impl Sync for SlabPageHeader {}
181
182const SLAB_HEADER_SIZE: usize = core::mem::size_of::<SlabPageHeader>();
184
185const _: () = assert!(
187 SLAB_HEADER_SIZE == 24,
188 "SlabPageHeader size changed : update docs"
189);
190const _: () = assert!(
191 (4096 - SLAB_HEADER_SIZE) / SLAB_SIZES[NUM_SLABS - 1] >= 1,
192 "SlabPageHeader too large: largest slab class gets 0 blocks per page"
193);
194
195struct SlabState {
207 partial_pages: [*mut SlabPageHeader; NUM_SLABS],
208}
209
210unsafe impl Send for SlabState {}
212unsafe impl Sync for SlabState {}
213
214impl SlabState {
215 const fn new() -> Self {
216 SlabState {
217 partial_pages: [ptr::null_mut(); NUM_SLABS],
218 }
219 }
220
221 #[inline]
226 fn class_index_for_layout(layout: Layout) -> usize {
227 for (i, &s) in SLAB_SIZES.iter().enumerate() {
228 if layout.size() + REDZONE_TAIL <= s && layout.align() <= slab_class_alignment(i) {
231 return i;
232 }
233 }
234 unreachable!("class_index_for_layout called for unsupported slab layout")
235 }
236
237 unsafe fn refill(&mut self, ci: usize, token: &crate::sync::IrqDisabledToken) {
242 debug_assert!(
243 !crate::arch::interrupts_enabled(),
244 "refill: IRQs must be disabled (IrqDisabledToken contract)"
245 );
246 let slab_size = SLAB_SIZES[ci];
247 let slab_align = slab_class_alignment(ci);
248 let blocks_offset = (SLAB_HEADER_SIZE + slab_align - 1) & !(slab_align - 1);
249 let num_blocks = (4096 - blocks_offset) / slab_size;
250 debug_assert!(
251 num_blocks >= 1,
252 "refill: slab_size {} yields 0 blocks",
253 slab_size
254 );
255
256 let frame = match memory::allocate_frame(token) {
257 Ok(f) => f,
258 Err(_) => return, };
260 SLAB_PAGES_ALLOCATED.fetch_add(1, AtomicOrdering::Relaxed);
261
262 let page_virt = super::phys_to_virt(frame.start_address.as_u64()) as *mut u8;
263
264 let header = page_virt as *mut SlabPageHeader;
266 (*header).next_partial = ptr::null_mut();
267 (*header).free_head = ptr::null_mut();
268 (*header).free_count = 0;
269 (*header).total_blocks = num_blocks as u32;
270
271 let blocks_start = page_virt.add(blocks_offset);
274 for i in (0..num_blocks).rev() {
275 let block = blocks_start.add(i * slab_size);
276 debug_assert_eq!(
277 (block as usize) & (slab_align - 1),
278 0,
279 "slab block alignment invariant broken for class {}",
280 slab_size
281 );
282 *(block as *mut *mut u8) = (*header).free_head;
283 if HEAP_POISON_ENABLED {
284 let end = slab_size.saturating_sub(4);
285 for off in 8..end {
286 *block.add(off) = POISON_BYTE;
287 }
288 if slab_size >= 12 {
289 let cp = block.add(slab_size - 4) as *mut u32;
290 *cp = SLAB_CANARY;
291 }
292 }
293 (*header).free_head = block;
294 (*header).free_count += 1;
295 }
296
297 (*header).next_partial = self.partial_pages[ci];
299 self.partial_pages[ci] = header;
300 }
301
302 unsafe fn alloc_block(&mut self, ci: usize, token: &crate::sync::IrqDisabledToken) -> *mut u8 {
307 if self.partial_pages[ci].is_null() {
308 self.refill(ci, token);
309 }
310 let header = self.partial_pages[ci];
311 if header.is_null() {
312 return ptr::null_mut();
313 }
314
315 let block = (*header).free_head;
316 debug_assert!(
317 !block.is_null(),
318 "alloc_block: partial page has null free_head"
319 );
320
321 (*header).free_head = *(block as *const *mut u8);
322 (*header).free_count -= 1;
323
324 if (*header).free_count == 0 {
326 self.partial_pages[ci] = (*header).next_partial;
327 (*header).next_partial = ptr::null_mut();
328 }
329
330 if HEAP_POISON_ENABLED {
331 let slab_size = SLAB_SIZES[ci];
332 let end = slab_size.saturating_sub(4);
333 let mut bad_off: Option<usize> = None;
334 for off in 8..end {
335 if *block.add(off) != POISON_BYTE {
336 bad_off = Some(off);
337 break;
338 }
339 }
340 if let Some(off) = bad_off {
341 let b0 = *block.add(off);
342 let b1 = if off + 1 < slab_size {
343 *block.add(off + 1)
344 } else {
345 0
346 };
347 let b2 = if off + 2 < slab_size {
348 *block.add(off + 2)
349 } else {
350 0
351 };
352 let b3 = if off + 3 < slab_size {
353 *block.add(off + 3)
354 } else {
355 0
356 };
357 let task = crate::process::current_task_clone();
358 let task_name = task.as_ref().map(|t| t.name.as_str()).unwrap_or("<none>");
359 crate::serial_println!(
360 "\x1b[1;31m[HEAP] USE-AFTER-FREE: slab[{}] block={:#x} off={} bytes=[{:02x} {:02x} {:02x} {:02x}] task={}\x1b[0m",
361 slab_size,
362 block as u64,
363 off,
364 b0,
365 b1,
366 b2,
367 b3,
368 task_name
369 );
370 let mut rbp: u64;
372 unsafe {
373 core::arch::asm!("mov {}, rbp", out(reg) rbp, options(nomem, nostack, preserves_flags));
374 }
375 for depth in 0..8 {
376 if rbp == 0 {
377 break;
378 }
379 let ret = unsafe { core::ptr::read_volatile((rbp + 8) as *const u64) };
380 let next = unsafe { core::ptr::read_volatile(rbp as *const u64) };
381 crate::serial_println!("[HEAP] UAF-BT[{}] ret={:#x}", depth, ret);
382 if next <= rbp {
383 break;
384 }
385 rbp = next;
386 }
387 }
388 if slab_size >= 12 {
389 let canary = *(block.add(slab_size - 4) as *const u32);
390 if canary != SLAB_CANARY {
391 crate::serial_println!(
392 "\x1b[1;31m[HEAP] CANARY OVERFLOW: slab[{}] block={:#x} expected={:#x} got={:#x}\x1b[0m",
393 slab_size,
394 block as u64,
395 SLAB_CANARY,
396 canary
397 );
398 }
399 }
400 }
401
402 block
403 }
404
405 unsafe fn dealloc_block(
410 &mut self,
411 ptr: *mut u8,
412 ci: usize,
413 token: &crate::sync::IrqDisabledToken,
414 ) {
415 let slab_size = SLAB_SIZES[ci];
416
417 if HEAP_POISON_ENABLED {
418 if slab_size >= 12 {
419 let cp = ptr.add(slab_size - 4) as *mut u32;
420 assert_eq!(
421 *cp, SLAB_CANARY,
422 "slab buffer overflow: class={} block={:p}",
423 slab_size, ptr,
424 );
425 *cp = SLAB_CANARY;
426 }
427 let end = slab_size.saturating_sub(4);
428 for off in 8..end {
429 *ptr.add(off) = POISON_BYTE;
430 }
431 }
432
433 let page_base = (ptr as usize) & !0xFFF;
435 let header = page_base as *mut SlabPageHeader;
436
437 let was_full = (*header).free_count == 0;
438
439 *(ptr as *mut *mut u8) = (*header).free_head;
441 (*header).free_head = ptr;
442 (*header).free_count += 1;
443
444 if was_full {
445 (*header).next_partial = self.partial_pages[ci];
447 self.partial_pages[ci] = header;
448 }
449
450 if (*header).free_count == (*header).total_blocks {
452 self.remove_from_partial(header, ci);
453 let phys = super::virt_to_phys(page_base as u64);
454 core::ptr::write_bytes(header as *mut u8, 0, SLAB_HEADER_SIZE);
456 let frame = memory::frame::PhysFrame {
457 start_address: PhysAddr::new(phys),
458 };
459 memory::free_frame(token, frame);
460 SLAB_PAGES_RECLAIMED.fetch_add(1, AtomicOrdering::Relaxed);
461 }
462 }
463
464 unsafe fn remove_from_partial(&mut self, page: *mut SlabPageHeader, ci: usize) {
468 if self.partial_pages[ci] == page {
469 self.partial_pages[ci] = (*page).next_partial;
470 (*page).next_partial = ptr::null_mut();
471 return;
472 }
473 let mut cur = self.partial_pages[ci];
474 while !cur.is_null() {
475 let next = (*cur).next_partial;
476 if next == page {
477 (*cur).next_partial = (*page).next_partial;
478 (*page).next_partial = ptr::null_mut();
479 return;
480 }
481 cur = next;
482 }
483 debug_assert!(
484 false,
485 "remove_from_partial: page {:p} not found in class {} list",
486 page, ci
487 );
488 }
489}
490
491static SLAB_ALLOC: SpinLock<SlabState> = SpinLock::new(SlabState::new());
492static LAST_HEAP_FAILURE: SpinLock<Option<KernelHeapFailureSnapshot>> = SpinLock::new(None);
493
494static SLAB_PAGES_ALLOCATED: AtomicUsize = AtomicUsize::new(0);
496static SLAB_PAGES_RECLAIMED: AtomicUsize = AtomicUsize::new(0);
498
499pub fn debug_slab_lock_addr() -> usize {
501 &SLAB_ALLOC as *const _ as usize
502}
503
504pub fn debug_register_slab_trace() {
506 crate::sync::debug_set_trace_slab_addr(debug_slab_lock_addr());
507}
508
509pub struct LockedHeap;
514
515unsafe impl GlobalAlloc for LockedHeap {
516 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
518 try_alloc_kernel_heap(layout).unwrap_or(ptr::null_mut())
519 }
520
521 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
523 match classify_kernel_heap_backend(layout) {
524 KernelHeapBackend::Slab => {
525 let ci = SlabState::class_index_for_layout(layout);
527 let _cpu = crate::arch::percpu::current_cpu_index();
528 let _irq_enabled = crate::arch::interrupts_enabled();
529 #[cfg(debug_assertions)]
530 if !_irq_enabled {
531 let effective = layout.size().max(layout.align());
532 use core::sync::atomic::{AtomicUsize, Ordering};
533 static HEAP_D_COUNT: AtomicUsize = AtomicUsize::new(0);
534 let n = HEAP_D_COUNT.fetch_add(1, Ordering::Relaxed);
535 if n % 100 == 0 {
536 crate::e9_println!(
537 "HEAP-D cpu={} irq=0 size={} ci={} n={}",
538 _cpu,
539 effective,
540 ci,
541 n
542 );
543 }
544 }
545 #[cfg(debug_assertions)]
550 {
551 let addr = ptr as u64;
552 if addr >= crate::memory::vmalloc::VMALLOC_VIRT_START
553 && addr < crate::memory::vmalloc::VMALLOC_VIRT_END
554 {
555 crate::serial_println!(
556 "[heap][bug] slab dealloc: ptr {:#x} is in vmalloc range : layout mismatch",
557 addr
558 );
559 debug_assert!(
560 false,
561 "slab dealloc with vmalloc pointer : alloc/dealloc layout mismatch"
562 );
563 }
564 }
565 let mut slab = SLAB_ALLOC.lock();
566 slab.with_mut_and_token(|s, token| s.dealloc_block(ptr, ci, token));
567 }
568 KernelHeapBackend::Vmalloc => {
569 let addr = ptr as u64;
571 if addr >= crate::memory::vmalloc::VMALLOC_VIRT_START
572 && addr < crate::memory::vmalloc::VMALLOC_VIRT_END
573 {
574 let ok = crate::sync::with_irqs_disabled(|token| {
575 crate::memory::free_kernel_virtual(ptr, token)
576 });
577 if !ok {
578 crate::serial_println!(
579 "[heap][leak] vmalloc free: no live mapping at {:#x} (wrong base or double-free?)",
580 addr
581 );
582 }
583 } else {
584 crate::serial_println!(
587 "[heap][leak] vmalloc dealloc: ptr {:#x} outside vmalloc arena [{:#x}..{:#x}]",
588 addr,
589 crate::memory::vmalloc::VMALLOC_VIRT_START,
590 crate::memory::vmalloc::VMALLOC_VIRT_END,
591 );
592 #[cfg(debug_assertions)]
593 debug_assert!(
594 false,
595 "vmalloc dealloc with out-of-range pointer : memory leaked"
596 );
597 }
598 }
599 }
600 }
601}
602
603fn record_heap_failure(
604 layout: Layout,
605 effective: usize,
606 backend: KernelHeapBackend,
607 error: KernelHeapAllocError,
608) -> KernelHeapAllocError {
609 *LAST_HEAP_FAILURE.lock() = Some(KernelHeapFailureSnapshot {
610 backend,
611 requested_size: layout.size(),
612 align: layout.align(),
613 effective_size: effective,
614 error,
615 });
616 error
617}
618
619pub fn last_heap_failure_snapshot() -> Option<KernelHeapFailureSnapshot> {
620 *LAST_HEAP_FAILURE.lock()
621}
622
623pub fn slab_diag_snapshot() -> SlabDiagSnapshot {
624 let allocated = SLAB_PAGES_ALLOCATED.load(AtomicOrdering::Relaxed);
625 let reclaimed = SLAB_PAGES_RECLAIMED.load(AtomicOrdering::Relaxed);
626 SlabDiagSnapshot {
627 pages_allocated: allocated,
628 pages_reclaimed: reclaimed,
629 pages_live: allocated.saturating_sub(reclaimed),
630 }
631}
632
633pub const SLAB_NUM_CLASSES: usize = NUM_SLABS;
635
636#[inline]
640pub fn slab_class_size(ci: usize) -> usize {
641 SLAB_SIZES[ci]
642}
643
644#[inline]
648pub fn slab_class_alignment(ci: usize) -> usize {
649 1usize << SLAB_SIZES[ci].trailing_zeros()
650}
651
652#[inline]
656pub fn slab_blocks_per_page(ci: usize) -> usize {
657 let align = slab_class_alignment(ci);
658 let blocks_offset = (SLAB_HEADER_SIZE + align - 1) & !(align - 1);
659 (4096 - blocks_offset) / SLAB_SIZES[ci]
660}
661
662pub fn slab_page_in_partial_list(ci: usize, page_base: u64) -> Option<bool> {
668 let mut guard = SLAB_ALLOC.try_lock()?;
669 Some(guard.with_mut_and_token(|s, _| unsafe {
672 let mut cur = s.partial_pages[ci];
673 while !cur.is_null() {
674 if cur as u64 == page_base {
675 return true;
676 }
677 cur = (*cur).next_partial;
678 }
679 false
680 }))
681}
682
683#[inline]
689pub unsafe fn try_alloc_kernel_heap(layout: Layout) -> Result<*mut u8, KernelHeapAllocError> {
690 let effective = layout.size().max(layout.align());
692 if !layout.align().is_power_of_two() {
695 return Err(record_heap_failure(
696 layout,
697 effective,
698 classify_kernel_heap_backend(layout),
699 KernelHeapAllocError::InvalidLayout,
700 ));
701 }
702 if effective > MAX_SLAB_SIZE && layout.align() > 4096 {
704 return Err(record_heap_failure(
705 layout,
706 effective,
707 KernelHeapBackend::Vmalloc,
708 KernelHeapAllocError::AlignmentExceedsKernelPage {
709 align: layout.align(),
710 },
711 ));
712 }
713 let boot_reg = crate::silo::debug_boot_reg_active();
714 if boot_reg {
715 crate::serial_println!(
716 "[trace][heap] alloc enter effective={} size={} align={}",
717 effective,
718 layout.size(),
719 layout.align()
720 );
721 }
722
723 let result = match classify_kernel_heap_backend(layout) {
724 KernelHeapBackend::Slab => {
725 let ci = SlabState::class_index_for_layout(layout);
727 let _cpu = crate::arch::percpu::current_cpu_index();
729 let _irq_enabled = crate::arch::interrupts_enabled();
730 #[cfg(debug_assertions)]
731 if !_irq_enabled {
732 use core::sync::atomic::{AtomicUsize, Ordering};
733 static HEAP_A_COUNT: AtomicUsize = AtomicUsize::new(0);
734 let n = HEAP_A_COUNT.fetch_add(1, Ordering::Relaxed);
735 if n % 100 == 0 {
736 crate::e9_println!(
737 "HEAP-A cpu={} irq=0 size={} ci={} n={}",
738 _cpu,
739 effective,
740 ci,
741 n
742 );
743 }
744 }
745 if boot_reg {
746 crate::serial_println!(
747 "[trace][heap] alloc slab ci={} slab_size={} lock={:#x}",
748 ci,
749 SLAB_SIZES[ci],
750 &SLAB_ALLOC as *const _ as usize
751 );
752 }
753 let mut slab = SLAB_ALLOC.lock();
754 if boot_reg {
755 crate::serial_println!("[trace][heap] alloc slab lock acquired");
756 }
757 let ptr = slab.with_mut_and_token(|s, token| s.alloc_block(ci, token));
758 if ptr.is_null() {
759 return Err(record_heap_failure(
760 layout,
761 effective,
762 KernelHeapBackend::Slab,
763 KernelHeapAllocError::SlabRefillFailed {
764 effective,
765 class_size: SLAB_SIZES[ci],
766 },
767 ));
768 }
769 ptr
770 }
771 KernelHeapBackend::Vmalloc => {
772 if boot_reg {
774 crate::serial_println!("[trace][heap] alloc vmalloc size={}", effective);
775 }
776
777 crate::sync::with_irqs_disabled(|token| {
778 crate::memory::allocate_kernel_virtual(effective, token).map_err(|error| {
779 record_heap_failure(
780 layout,
781 effective,
782 KernelHeapBackend::Vmalloc,
783 KernelHeapAllocError::Vmalloc(error),
784 )
785 })
786 })?
787 }
788 };
789
790 Ok(result)
791}
792
793#[global_allocator]
794static HEAP_ALLOCATOR: LockedHeap = LockedHeap;
795
796#[inline]
804pub unsafe fn alloc_kernel_heap(layout: Layout) -> *mut u8 {
805 try_alloc_kernel_heap(layout).unwrap_or(ptr::null_mut())
806}
807
808#[inline]
810pub unsafe fn dealloc_kernel_heap(ptr: *mut u8, layout: Layout) {
811 HEAP_ALLOCATOR.dealloc(ptr, layout);
812}
813
814fn log_common_oom_header(layout: Layout, effective: usize) {
815 let cpu = crate::arch::percpu::current_cpu_index();
816 let irq_enabled = crate::arch::interrupts_enabled();
817 let tid = crate::process::current_task_id()
818 .map(|t| t.as_u64())
819 .unwrap_or(0);
820 let current_task = crate::process::current_task_clone();
821 let task_name = current_task
822 .as_ref()
823 .map(|t| t.name.as_str())
824 .unwrap_or("<none>");
825
826 crate::serial_println!(
827 "[heap][oom] cpu={} irq={} tid={} task={} size={} align={} effective={}",
828 cpu,
829 irq_enabled,
830 tid,
831 task_name,
832 layout.size(),
833 layout.align(),
834 effective
835 );
836}
837
838fn log_buddy_snapshot() -> Option<(usize, usize, usize)> {
839 let snapshot = if let Some(guard) = crate::memory::buddy::get_allocator().try_lock() {
843 guard.as_ref().map(|alloc| {
844 let (total_pages, allocated_pages) = alloc.page_totals();
845 let free_pages = total_pages.saturating_sub(allocated_pages);
846 let fail_counts = crate::memory::buddy::buddy_alloc_fail_counts_snapshot();
847 (total_pages, allocated_pages, free_pages, fail_counts)
848 })
849 } else {
850 crate::serial_println!("[heap][oom] buddy: allocator locked");
851 return None;
852 };
853 let Some((total_pages, allocated_pages, free_pages, fail_counts)) = snapshot else {
856 crate::serial_println!("[heap][oom] buddy: allocator uninitialized");
857 return None;
858 };
859
860 crate::serial_println!(
861 "[heap][oom] buddy: total={} alloc={} free={}",
862 total_pages,
863 allocated_pages,
864 free_pages
865 );
866
867 let mut fail_line = alloc::string::String::from("[heap][oom] buddy_fail_by_order:");
868 for (i, &count) in fail_counts.iter().enumerate() {
869 use core::fmt::Write;
870 let _ = write!(fail_line, " o{}={} ", i, count);
871 }
872 crate::serial_println!("{}", fail_line);
873 Some((total_pages, allocated_pages, free_pages))
874}
875
876fn log_heap_failure_policy(layout: Layout) {
877 match last_heap_failure_snapshot() {
878 Some(snapshot) => {
879 crate::serial_println!(
880 "[heap][oom] last_failure backend={:?} requested={} align={} effective={} error={:?}",
881 snapshot.backend,
882 snapshot.requested_size,
883 snapshot.align,
884 snapshot.effective_size,
885 snapshot.error
886 );
887 if snapshot.requested_size != layout.size() || snapshot.align != layout.align() {
888 crate::serial_println!(
889 "[heap][oom] note=last_heap_failure does not exactly match current layout; using best-effort context"
890 );
891 }
892 }
893 None => crate::serial_println!("[heap][oom] last_heap_failure unavailable"),
894 }
895}
896
897#[alloc_error_handler]
899fn alloc_error_handler(layout: Layout) -> ! {
900 let effective = layout.size().max(layout.align());
901 let pages_needed = (effective.saturating_add(4095)) / 4096;
902 let order = if pages_needed == 0 {
903 0
904 } else {
905 pages_needed.next_power_of_two().trailing_zeros() as u8
906 };
907 log_common_oom_header(layout, effective);
908
909 if effective <= MAX_SLAB_SIZE {
910 crate::serial_println!(
911 "[heap][oom] backend=slab effective={} class_max={} refill_order=0",
912 effective,
913 MAX_SLAB_SIZE
914 );
915 log_heap_failure_policy(layout);
916 if let Some((total_pages, _, free_pages)) = log_buddy_snapshot() {
917 crate::serial_println!(
918 "[heap][oom] slab-refill pages={} buddy_order={}",
919 pages_needed,
920 order
921 );
922 if free_pages > (total_pages / 4) {
923 crate::serial_println!(
924 "[heap][oom] diagnosis=slab order-0 refill failed despite remaining free pages \
925 ({} free pages): allocator pressure, zone exhaustion, or transient allocator state",
926 free_pages,
927 );
928 }
929 }
930 } else {
931 crate::serial_println!(
932 "[heap][oom] backend=vmalloc request_pages={} legacy_buddy_order_hint={}",
933 pages_needed,
934 order
935 );
936 log_heap_failure_policy(layout);
937 if let Some(snap) = last_heap_failure_snapshot() {
938 if let KernelHeapAllocError::AlignmentExceedsKernelPage { align } = snap.error {
939 crate::serial_println!(
940 "[heap][oom] diagnosis=layout alignment {} B exceeds 4 KiB page alignment guaranteed by vmalloc heap path",
941 align
942 );
943 }
944 }
945 match crate::memory::vmalloc::last_failure_snapshot() {
946 Some(snapshot) => {
947 crate::serial_println!(
948 "[heap][oom] vmalloc_last_failure size={} pages={} error={:?}",
949 snapshot.size,
950 snapshot.pages,
951 snapshot.error
952 );
953 match snapshot.error {
954 crate::memory::vmalloc::VmallocError::SizeExceedsPolicy {
955 requested,
956 max_allowed,
957 } => {
958 crate::serial_println!(
959 "[heap][oom] diagnosis=vmalloc policy limit exceeded requested={} max_allowed={}",
960 requested,
961 max_allowed
962 );
963 }
964 crate::memory::vmalloc::VmallocError::VirtualRangeExhausted => {
965 crate::serial_println!(
966 "[heap][oom] diagnosis=kernel virtual allocation arena exhausted or fragmented"
967 );
968 }
969 crate::memory::vmalloc::VmallocError::PhysicalMemoryExhausted => {
970 crate::serial_println!(
971 "[heap][oom] diagnosis=vmalloc could not acquire enough physical pages"
972 );
973 }
974 crate::memory::vmalloc::VmallocError::MetadataAllocationFailed => {
975 crate::serial_println!(
976 "[heap][oom] diagnosis=vmalloc metadata allocation failed"
977 );
978 }
979 crate::memory::vmalloc::VmallocError::KernelMapFailed => {
980 crate::serial_println!(
981 "[heap][oom] diagnosis=kernel page-table mapping failed during vmalloc"
982 );
983 }
984 crate::memory::vmalloc::VmallocError::ZeroSize => {
985 crate::serial_println!("[heap][oom] diagnosis=zero-sized vmalloc request");
986 }
987 }
988 }
989 None => {
990 crate::serial_println!("[heap][oom] vmalloc_last_failure unavailable");
991 }
992 }
993 let _ = log_buddy_snapshot();
994 }
995 crate::serial_println!(
996 "[heap][oom] policy=fatal_global_alloc_path use try_alloc_kernel_heap()/allocate_kernel_virtual() on recoverable paths"
997 );
998 panic!("fatal kernel heap allocation failure: {:?}", layout)
999}
1000
1001pub fn dump_diagnostics() {
1009 crate::serial_println!("[heap][diag] === Heap Diagnostics ===");
1010
1011 let buddy_locked;
1017 let buddy_stats = if let Some(guard) = crate::memory::buddy::get_allocator().try_lock() {
1018 buddy_locked = false;
1019 guard.as_ref().map(|alloc| {
1020 let (total_pages, allocated_pages) = alloc.page_totals();
1021 let mut zones =
1022 [crate::memory::buddy::ZoneStats::empty(); crate::memory::zone::ZoneType::COUNT];
1023 let zone_count = alloc.zone_snapshot(&mut zones);
1024 let mut free_heads = [[(0usize, 0usize); crate::memory::zone::MAX_ORDER + 1];
1025 crate::memory::zone::ZoneType::COUNT];
1026 let mut frag = [[0usize; crate::memory::zone::MAX_ORDER + 1];
1027 crate::memory::zone::ZoneType::COUNT];
1028 for zi in 0..zone_count {
1029 let zone = alloc.get_zone(zi);
1030 for order in 0..=crate::memory::zone::MAX_ORDER {
1031 free_heads[zi][order] = (
1032 zone.free_list_count_for(
1033 order as u8,
1034 crate::memory::zone::Migratetype::Unmovable,
1035 ),
1036 zone.free_list_count_for(
1037 order as u8,
1038 crate::memory::zone::Migratetype::Movable,
1039 ),
1040 );
1041 }
1042 for order in 1..=crate::memory::zone::MAX_ORDER {
1043 frag[zi][order] = zone.fragmentation_score(order as u8, zones[zi].cached_pages);
1044 }
1045 }
1046 (
1047 total_pages,
1048 allocated_pages,
1049 zones,
1050 zone_count,
1051 free_heads,
1052 frag,
1053 )
1054 })
1055 } else {
1056 buddy_locked = true;
1057 None
1058 };
1059 if buddy_locked {
1062 crate::serial_println!("[heap][diag] buddy: allocator locked (retry later)");
1063 } else if let Some((total_pages, allocated_pages, zones, zone_count, free_heads, frag)) =
1064 buddy_stats
1065 {
1066 crate::serial_println!(
1067 "[heap][diag] buddy: total={} pages, allocated={} pages, free={} pages",
1068 total_pages,
1069 allocated_pages,
1070 total_pages.saturating_sub(allocated_pages)
1071 );
1072
1073 for info in zones.iter().take(zone_count) {
1074 crate::serial_println!(
1075 "[heap][diag] zone={:?} state={:?} managed={} present={} reserved={} free={} cached={} cu/cm={}/{} avail={} segments={}/{} pageblocks=u{}/m{} u_free={} m_free={} watermarks={}/{}/{} reserve={} largest_order={:?}",
1076 info.zone_type,
1077 info.pressure(),
1078 info.managed_pages,
1079 info.present_pages,
1080 info.reserved_pages,
1081 info.free_pages,
1082 info.cached_pages,
1083 info.cached_unmovable_pages,
1084 info.cached_movable_pages,
1085 info.available_after_reserve_pages(),
1086 info.segment_count,
1087 info.segment_capacity,
1088 info.unmovable_pageblocks,
1089 info.movable_pageblocks,
1090 info.unmovable_free_pages,
1091 info.movable_free_pages,
1092 info.watermark_min,
1093 info.watermark_low,
1094 info.watermark_high,
1095 info.lowmem_reserve_pages,
1096 info.largest_free_order
1097 );
1098 }
1099
1100 for zi in 0..zone_count {
1102 let info = zones[zi];
1103 let mut line = alloc::string::String::from("[heap][diag] ");
1104 use core::fmt::Write;
1105 let _ = write!(line, "zone={:?} free_heads:", info.zone_type);
1106 for order in 0..=crate::memory::zone::MAX_ORDER {
1107 let (unmovable, movable) = free_heads[zi][order];
1108 if unmovable > 0 || movable > 0 {
1109 let _ = write!(line, " o{}=u{}/m{} ", order, unmovable, movable);
1110 }
1111 }
1112 crate::serial_println!("{}", line);
1113
1114 let mut frag_line = alloc::string::String::from("[heap][diag] ");
1115 let _ = write!(frag_line, "zone={:?} frag:", info.zone_type);
1116 for order in 1..=crate::memory::zone::MAX_ORDER {
1117 let _ = write!(frag_line, " o{}={}%", order, frag[zi][order]);
1118 }
1119 crate::serial_println!("{}", frag_line);
1120 }
1121 }
1122
1123 let fail_counts = crate::memory::buddy::buddy_alloc_fail_counts_snapshot();
1125 let mut has_fails = false;
1126 for (i, &count) in fail_counts.iter().enumerate() {
1127 if count > 0 {
1128 has_fails = true;
1129 }
1130 crate::serial_println!("[heap][diag] buddy_fail[{}]: {}", i, count);
1131 }
1132 if has_fails {
1133 crate::serial_println!(
1134 "[heap][diag] => non-zero buddy_fail counts indicate fragmentation pressure"
1135 );
1136 }
1137
1138 {
1140 let alloc = SLAB_PAGES_ALLOCATED.load(AtomicOrdering::Relaxed);
1141 let reclaim = SLAB_PAGES_RECLAIMED.load(AtomicOrdering::Relaxed);
1142 crate::serial_println!(
1143 "[heap][diag] slab: pages_allocated={} pages_reclaimed={} pages_live={}",
1144 alloc,
1145 reclaim,
1146 alloc.saturating_sub(reclaim)
1147 );
1148 }
1149 if let Some(mut guard) = SLAB_ALLOC.try_lock() {
1150 guard.with_mut_and_token(|s, _| unsafe {
1152 for ci in 0..NUM_SLABS {
1153 let mut head = s.partial_pages[ci];
1154 if head.is_null() {
1155 continue;
1156 }
1157 let mut page_count = 0usize;
1158 let mut free_blocks = 0u32;
1159 while !head.is_null() {
1160 page_count += 1;
1161 free_blocks = free_blocks.saturating_add((*head).free_count);
1162 head = (*head).next_partial;
1163 }
1164 crate::serial_println!(
1165 "[heap][diag] slab[{}]: partial_pages={} free_blocks={}",
1166 SLAB_SIZES[ci],
1167 page_count,
1168 free_blocks
1169 );
1170 }
1171 });
1172 } else {
1173 crate::serial_println!("[heap][diag] slab: locked (retry later)");
1174 }
1175
1176 {
1178 let d = crate::memory::phys_contiguous_diag();
1179 crate::serial_println!(
1180 "[heap][diag] phys_contiguous: pages_allocated={} pages_freed={} pages_live={} alloc_failures={}",
1181 d.pages_allocated,
1182 d.pages_freed,
1183 d.pages_live,
1184 d.alloc_fail_count
1185 );
1186 }
1187
1188 if let Some(snapshot) = last_heap_failure_snapshot() {
1189 crate::serial_println!(
1190 "[heap][diag] last_heap_failure: backend={:?} requested={} align={} effective={} error={:?}",
1191 snapshot.backend,
1192 snapshot.requested_size,
1193 snapshot.align,
1194 snapshot.effective_size,
1195 snapshot.error
1196 );
1197 }
1198
1199 crate::memory::vmalloc::dump_diagnostics();
1200
1201 crate::serial_println!("[heap][diag] === End Diagnostics ===");
1202}