Skip to main content

strat9_kernel/memory/
heap.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23// Heap allocator: slab sub-allocator + VM-backed large-allocation path.
24//
25// Small allocations (effective size <= 2048 B) come from per-size-class slab
26// free lists.  Each slab class draws whole pages from the buddy allocator and
27// carves them into fixed-size blocks.  Freed blocks return to the slab free
28// list, so the buddy's page counter stabilises after warm-up instead of
29// growing on every tiny allocation.
30//
31// Large allocations (> 2048 B) go through the kernel vmalloc backend:
32// virtually contiguous, physically fragmented, and independent from
33// high-order physically contiguous buddy blocks.
34//
35// Lock ordering : SLAB_ALLOC (outer) may call the frame-allocation helpers.
36// Those helpers can hit a CPU-local cache (no global buddy lock) or fall back
37// to the global buddy lock as needed.
38
39use crate::{arch::xshim::PhysAddr, memory, sync::SpinLock};
40use core::{
41    alloc::{GlobalAlloc, Layout},
42    ptr,
43    sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
44};
45
46// ---------------------------------------------------------------------------
47// Slab size classes
48// ---------------------------------------------------------------------------
49
50/// Slab block sizes chosen to bound internal fragmentation to ~25% worst-case
51/// (average ~12%) instead of 50% with pure power-of-two classes.
52///
53/// The progression follows a roughly 1.25× step above 64 bytes.  Below 64
54/// bytes the absolute waste of a 2× jump is small enough (max 32 bytes) to
55/// keep power-of-two boundaries, avoiding an explosion of size classes.
56///
57/// | Class range | Step      | Max waste |
58/// |-------------|-----------|-----------|
59/// | 8 to  64 B  | x2 / 1,5× | ≤ 32 B    |
60/// |64 to 256 B  | ~1.25×    | ≤ 64 B    |
61/// |256 to 2048 B| 1.25×     | ≤ 512 B   |
62
63const 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();
68/// Allocations with effective size above this threshold bypass the slab.
69/// Maximum payload size that can be served from the slab allocator.
70/// Must account for REDZONE_TAIL: the actual slab class must be >= payload + redzone.
71const 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    /// [`GlobalAlloc`] large path uses vmalloc, which only guarantees 4 KiB alignment.
83    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
119// =============================================================================
120// CRITICAL: slab corruption detection
121//
122// Build with `--features heap-poison` when debugging heap-corruption crashes
123// (off by default: it re-reads/rewrites whole blocks on every alloc/free).
124// When enabled:
125//   - Every block carved by refill() is filled with POISON_BYTE in bytes [8..N-4]
126//     and stamped with SLAB_CANARY in the last 4 bytes.
127//   - dealloc_block() restores the canary and re-poisons before linking.
128//     The live allocation's canary is checked before either operation.
129//   - alloc_block() verifies poison and canary before handing the block out;
130//     a mismatch is logged immediately via serial_println! (non-allocating).
131//
132// This detects:
133//   - Use-after-free: a write to a freed slab block overwrites poison bytes.
134//   - Buffer overflow: a write past the end overwrites the canary or the next
135//     block's free-list pointer.
136//
137// Cost: one memset + canary write per alloc/dealloc for slab classes.
138// =============================================================================
139const HEAP_POISON_ENABLED: bool = cfg!(feature = "heap-poison");
140/// Byte pattern written to the body of freed slab blocks.
141const POISON_BYTE: u8 = 0xDE;
142/// Canary word placed at the last 4 bytes of each slab block.
143const SLAB_CANARY: u32 = 0xDEAD_BEEF;
144/// Bytes reserved at the end of every slab block for the canary + padding.
145/// The user-visible allocation size is `slab_size - REDZONE_TAIL`, ensuring
146/// writes to the full user area cannot overwrite the canary.
147const REDZONE_TAIL: usize = 8;
148
149// ---------------------------------------------------------------------------
150// Slab page header : embedded at byte 0 of every buddy page used by a class.
151// Blocks start at offset SLAB_HEADER_SIZE within the page.
152// ---------------------------------------------------------------------------
153
154/// Header at the base of each 4 KiB page dedicated to a slab class.
155///
156/// Page layout:
157/// ```text
158/// [0 .. SLAB_HEADER_SIZE)   SlabPageHeader  (24 bytes)
159/// [SLAB_HEADER_SIZE .. 4096) slab blocks, each SLAB_SIZES[ci] bytes
160/// ```
161///
162/// A page lives in `partial_pages[ci]` while `0 < free_count < total_blocks`.
163/// It is removed when all blocks are allocated (`free_count == 0`), and is
164/// reclaimed to the buddy allocator when it becomes fully empty again
165/// (`free_count == total_blocks`).
166#[repr(C)]
167struct SlabPageHeader {
168    /// Next page in the partial list for this class (null = end of list).
169    next_partial: *mut SlabPageHeader,
170    /// Head of the intra-page free-block chain (null = page is full).
171    free_head: *mut u8,
172    /// Free blocks currently in this page.
173    free_count: u32,
174    /// Total blocks this page can hold (constant per class after refill).
175    total_blocks: u32,
176}
177
178// SAFETY: only accessed under SLAB_ALLOC spinlock.
179unsafe impl Send for SlabPageHeader {}
180unsafe impl Sync for SlabPageHeader {}
181
182/// Byte offset at which slab blocks begin within each slab page.
183const SLAB_HEADER_SIZE: usize = core::mem::size_of::<SlabPageHeader>();
184
185// Compile-time invariants.
186const _: () = 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
195// ---------------------------------------------------------------------------
196// SlabState
197// ---------------------------------------------------------------------------
198
199/// Per-size-class partial-page lists.
200///
201/// `partial_pages[ci]` is the head of a singly-linked list of `SlabPageHeader`
202/// nodes for class `ci`.  A page enters the list on `refill` and on the first
203/// `dealloc` after going full.  It leaves the list when all its blocks are
204/// allocated (it silently becomes "full") or when it becomes completely empty
205/// (it is then returned to the buddy allocator).
206struct SlabState {
207    partial_pages: [*mut SlabPageHeader; NUM_SLABS],
208}
209
210// SAFETY: protected exclusively through `SLAB_ALLOC: SpinLock<SlabState>`.
211unsafe 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    /// Return the slab class index for `layout`.
222    ///
223    /// The chosen class must be large enough for the payload and guarantee the
224    /// requested alignment for every block carved from that class.
225    #[inline]
226    fn class_index_for_layout(layout: Layout) -> usize {
227        for (i, &s) in SLAB_SIZES.iter().enumerate() {
228            // P0 fix: require REDZONE_TAIL bytes beyond the user payload so the
229            // canary (at offset s-4) is always outside the user's writable area.
230            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    /// Allocate one buddy page, write a `SlabPageHeader` at its base, carve
238    /// the remaining space into blocks, and prepend the page to `partial_pages[ci]`.
239    // SAFETY: caller holds the slab lock with IRQs disabled; the page came
240    // from the buddy allocator and is HHDM-mapped for a full 4 KiB.
241    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, // OOM : alloc_block will see null partial and return null
259        };
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        // Initialise page header at byte 0.
265        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        // Carve blocks starting at an alignment-respecting offset, highest index first so
272        // the lowest-address block ends up at the head (cosmetic only).
273        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        // Prepend to partial list.
298        (*header).next_partial = self.partial_pages[ci];
299        self.partial_pages[ci] = header;
300    }
301
302    /// Pop one block from the first partial page for class `ci`.
303    /// Calls `refill` when the partial list is empty.  Returns null on OOM.
304    // SAFETY: caller holds the slab lock; headers and free lists are only
305    // mutated under it.
306    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        // Remove page from partial list when it is now full (free_count == 0).
325        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                // Best-effort frame-pointer walk of the allocating stack.
371                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    /// Return `ptr` to its slab page and reclaim the page to the buddy
406    /// allocator if it becomes fully empty.
407    // SAFETY: caller holds the slab lock; `ptr` came from this allocator and
408    // its page header is intact.
409    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        // Locate the page header: round ptr down to 4 KiB boundary.
434        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        // Push block onto the page's intra-page free list.
440        *(ptr as *mut *mut u8) = (*header).free_head;
441        (*header).free_head = ptr;
442        (*header).free_count += 1;
443
444        if was_full {
445            // Page went full -> partial: re-insert at list head.
446            (*header).next_partial = self.partial_pages[ci];
447            self.partial_pages[ci] = header;
448        }
449
450        // Reclaim fully-empty pages to the buddy allocator.
451        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            // Zero the header before freeing to catch accidental reuse.
455            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    /// Unlink `page` from `partial_pages[ci]`.  O(n) in partial-list length.
465    // SAFETY: caller holds the slab lock; `page` is a valid SlabPageHeader
466    // linked in this class's partial list.
467    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
494/// Total buddy pages ever handed to the slab allocator.
495static SLAB_PAGES_ALLOCATED: AtomicUsize = AtomicUsize::new(0);
496/// Total buddy pages ever returned from the slab allocator (fully-empty reclaim).
497static SLAB_PAGES_RECLAIMED: AtomicUsize = AtomicUsize::new(0);
498
499/// Returns the slab lock address for deadlock tracing.
500pub fn debug_slab_lock_addr() -> usize {
501    &SLAB_ALLOC as *const _ as usize
502}
503
504/// Register slab lock for E9 trace (call from init).
505pub fn debug_register_slab_trace() {
506    crate::sync::debug_set_trace_slab_addr(debug_slab_lock_addr());
507}
508
509// ---------------------------------------------------------------------------
510// GlobalAlloc implementation
511// ---------------------------------------------------------------------------
512
513pub struct LockedHeap;
514
515unsafe impl GlobalAlloc for LockedHeap {
516    /// Performs the alloc operation.
517    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
518        try_alloc_kernel_heap(layout).unwrap_or(ptr::null_mut())
519    }
520
521    /// Performs the dealloc operation.
522    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
523        match classify_kernel_heap_backend(layout) {
524            KernelHeapBackend::Slab => {
525                // --- slab path: return block to free list ---
526                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                // Catch layout mismatches where a vmalloc pointer is freed with
546                // a small layout (classify_kernel_heap_backend routes to Slab).
547                // This means the caller passed a different layout to dealloc than
548                // was used for alloc : a GlobalAlloc contract violation.
549                #[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                // vmalloc path: free via the vmalloc arena
570                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                    // Pointer is outside the vmalloc arena with a large-allocation
585                    // layout : nothing is freed (GlobalAlloc contract violation).
586                    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
633/// Number of slab size classes.
634pub const SLAB_NUM_CLASSES: usize = NUM_SLABS;
635
636/// Block size in bytes for slab class `ci`.
637///
638/// Panics in debug if `ci >= SLAB_NUM_CLASSES`.
639#[inline]
640pub fn slab_class_size(ci: usize) -> usize {
641    SLAB_SIZES[ci]
642}
643
644/// Guaranteed alignment in bytes for slab class `ci`.
645///
646/// This is the largest power-of-two divisor of the class size.
647#[inline]
648pub fn slab_class_alignment(ci: usize) -> usize {
649    1usize << SLAB_SIZES[ci].trailing_zeros()
650}
651
652/// Number of blocks that fit in one buddy page for slab class `ci`.
653///
654/// Accounts for the `SlabPageHeader` at the base of each page.
655#[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
662/// Returns whether the slab page at `page_base` is currently present in the
663/// partial-page list for class `ci`.
664///
665/// Returns `None` if the slab allocator lock is contended. Intended for
666/// shell/debug validation, not for allocator hot paths.
667pub fn slab_page_in_partial_list(ci: usize, page_base: u64) -> Option<bool> {
668    let mut guard = SLAB_ALLOC.try_lock()?;
669    // SAFETY: we hold the slab lock; walking the partial list through raw
670    // pointers is safe because the list is only mutated under that lock.
671    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/// Fallible heap entry point with explicit backend-aware errors.
684///
685/// Kernel code that can recover from allocation failure should prefer this API
686/// over `Box`/`Vec`/`GlobalAlloc`, which eventually route to
687/// [`alloc_error_handler`] and remain fatal by language contract.
688#[inline]
689pub unsafe fn try_alloc_kernel_heap(layout: Layout) -> Result<*mut u8, KernelHeapAllocError> {
690    // Effective size must satisfy both the size and alignment requirements.
691    let effective = layout.size().max(layout.align());
692    // `Layout` constructors guarantee a non-zero alignment; keep the power-of-two
693    // check as a defensive guard for any malformed caller input.
694    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    // Large heap path uses vmalloc, which only aligns to 4 KiB pages.
703    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            // --- slab path ---
726            let ci = SlabState::class_index_for_layout(layout);
727            // Race/corruption diagnostic: log alloc when IRQs disabled (rate-limited).
728            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            // --- vmalloc path (large allocation) ---
773            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/// Compatibility facade over the current global kernel heap policy.
797///
798/// Callers that need an explicit heap allocation entry point, rather than
799/// relying on `Box`/`Vec`/`GlobalAlloc`, should use this helper. The selected
800/// backend remains the current heap policy:
801/// - small allocations -> slab
802/// - large allocations -> vmalloc
803#[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/// Free memory previously returned by [`alloc_kernel_heap`].
809#[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    // Phase 1: read the allocator stats and release the buddy lock BEFORE any
840    // heap allocation (`String::from` / `write!` / `serial_println!`), so no
841    // allocation happens while the guard is live.
842    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    // Guard dropped here.
854
855    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/// Allocates error handler.
898#[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
1001/// Dump heap and buddy allocator diagnostics to the serial console.
1002///
1003/// Safe to call from the shell or debug tooling. Prints:
1004/// - Total/allocated/free pages
1005/// - Per-order buddy free list head counts
1006/// - Buddy allocation failure counts by order (fragmentation indicator)
1007/// - Slab free list head pointers
1008pub fn dump_diagnostics() {
1009    crate::serial_println!("[heap][diag] === Heap Diagnostics ===");
1010
1011    // Buddy allocator stats.
1012    //
1013    // Snapshot everything needed into stack arrays while the try_lock guard is
1014    // held, then drop it BEFORE formatting: no `alloc::`/`String` allocation
1015    // may happen under the buddy guard.
1016    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    // Guard (if any) dropped here.
1060
1061    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        // Per-zone free list heads by migratetype.
1101        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    // Buddy failure counts
1124    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    // Slab stats
1139    {
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        // SAFETY: we hold the slab lock; raw pointer traversal is safe.
1151        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    // Contiguous-physical allocation telemetry
1177    {
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}