Skip to main content

strat9_kernel/ipc/
n3.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//! N3 MMU Thread Migration : PCID-preserving (N3b) and Full Isolation (N3c).
24//!
25//! Implements the transport layer for IPC level N3
26//!
27//! # Architecture
28//!
29//! ```text
30//! sender ──send()──▶ MigrationFrame ──CR3 switch──▶ receiver handler
31//!   ▲                                                    │
32//!   └────────────── reschedule IPI ◀─────────────────────┘
33//! ```
34//!
35//! The sender saves its context, copies the message, then calls the ASM
36//! primitive which switches CR3 and restores the receiver's context.  The
37//! receiver handler reads the message from the frame and returns.  The
38//! sender is resumed via a reschedule IPI.
39//!
40//! # Frame pointer requirement
41//!
42//! The `send()` method captures `sender_rip` from `[rbp + 8]`, which requires
43//! frame pointers to be enabled at compile time. The kernel must be built with
44//! `-C force-frame-pointers=yes` (see workspace/kernel/.cargo/config.toml).
45//!
46//! # Shared mapping note
47//!
48//! The MigrationFrame is mapped in both address spaces at the same virtual
49//! address (`N3_SHARED_FRAME_VA`), but **without USER_ACCESSIBLE**. The frame
50//! lives in kernel space and is accessible only from Ring 0. Both sender and
51//! receiver access it via their kernel page tables : the shared VA means the
52//! same PTE (same physical page) is reachable from both page table hierarchies.
53//! This is NOT a user-mappable region; it is kernel-only shared memory.
54//!
55//! # PCID contract
56//!
57//! A PCID value of 0 means "no PCID" : either PCID is unsupported by the CPU
58//! or exhausted. All code paths check `pcid > 0` before using PCID-specific
59//! features (INVPCID, CR3 PCID bits). The tier selection function
60//! (`select_n3_tier()`) distinguishes theoretical CPU support from actual
61//! operational capability.
62#![allow(dead_code)]
63
64use crate::{
65    arch::apic,
66    memory::{allocate_frame, free_frame, phys_to_virt, AddressSpace},
67    process::{current_task_id, get_task_by_id, Task, TaskId},
68    sync::{with_irqs_disabled, SpinLock},
69};
70use core::{
71    mem::MaybeUninit,
72    sync::atomic::{AtomicU16, AtomicU32, AtomicU64, AtomicU8, Ordering},
73};
74
75use super::transport::{
76    IpcConsumer, IpcError, IpcProducer, IpcTransport, TransportCapabilities, TransportLevel,
77};
78
79// ============================================================================
80// Normative types
81// ============================================================================
82
83/// N3 tier selection
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85#[repr(u8)]
86pub enum N3Tier {
87    /// PCID-preserving: TLB entries for the sender AS are kept across CR3 switch.
88    PcidPreserving = 1,
89    /// Full isolation: CR3 write flushes all non-global TLB entries.
90    FullIsolation = 2,
91}
92
93/// Minimal CPU context saved/restored during N3 migration.
94///
95/// Layout is `#[repr(C, align(64))]` to match the ASM primitive offsets.
96/// No FPU/AVX state : handled separately per FPU policy.
97/// Total size: 96 bytes (fields) + 32 bytes (padding) = 128 bytes.
98#[repr(C, align(64))]
99#[derive(Debug, Clone, Copy)]
100pub struct N3MinimalContext {
101    /// Callee-saved GPRs (System V AMD64 ABI).
102    pub r15: u64,
103    pub r14: u64,
104    pub r13: u64,
105    pub r12: u64,
106    pub rbp: u64,
107    pub rbx: u64,
108    pub rdx: u64,
109    pub rax: u64,
110    /// Processor flags.
111    pub rflags: u64,
112    /// Stack pointer.
113    pub rsp: u64,
114    /// Instruction pointer (handler entry or return address).
115    pub rip: u64,
116    /// CR3 value with PCID bits for N3b, or 0 for N3c.
117    pub cr3_pcid: u64,
118    /// Explicit padding to reach 128 bytes (align(64) requires this).
119    /// Prevents implicit compiler padding and ensures deterministic layout
120    /// for the ASM primitive.
121    pub _pad: [u8; 32],
122}
123
124impl N3MinimalContext {
125    /// Zeroed context : used as initial value before preparation.
126    pub const ZERO: Self = Self {
127        r15: 0,
128        r14: 0,
129        r13: 0,
130        r12: 0,
131        rbp: 0,
132        rbx: 0,
133        rdx: 0,
134        rax: 0,
135        rflags: 0,
136        rsp: 0,
137        rip: 0,
138        cr3_pcid: 0,
139        _pad: [0u8; 32],
140    };
141}
142
143/// Migration state machine.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145#[repr(u8)]
146pub enum MigrationState {
147    /// No migration active; frame reusable.
148    Ready = 0,
149    /// Migration engaged; no second migration on this frame.
150    Active = 1,
151    /// Migration not finalized before timeout.
152    Stalled = 2,
153    /// Transient kernel state during recovery.
154    Reclaiming = 3,
155}
156
157impl MigrationState {
158    fn from_u8(v: u8) -> Option<Self> {
159        match v {
160            0 => Some(Self::Ready),
161            1 => Some(Self::Active),
162            2 => Some(Self::Stalled),
163            3 => Some(Self::Reclaiming),
164            _ => None,
165        }
166    }
167}
168
169bitflags::bitflags! {
170    /// Flags for a migration operation.
171    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
172    pub struct MigrationFlags: u16 {
173        /// Eager FPU save/restore (required for SIMD workloads).
174        const FPU_EAGER = 0x0001;
175        /// Lazy FPU save/restore (default, lower cost).
176        const FPU_LAZY = 0x0002;
177        /// Migration crosses CPU cores (requires IPI sync).
178        const INTER_CORE = 0x0004;
179    }
180}
181
182/// Shared migration frame : one per N3 transport endpoint pair.
183///
184/// Must reside in a dedicated physical page mapped at the same kernel
185/// virtual address (`N3_SHARED_FRAME_VA`) in both sender and receiver
186/// address spaces. The mapping is kernel-only (no `USER_ACCESSIBLE`
187/// flag) : all access is controlled by the kernel via the CAS state
188/// machine. Both address spaces see the same physical page through
189/// their own kernel half of the page tables.
190#[repr(C, align(64))]
191pub struct MigrationFrame {
192    /// Sender context (saved by ASM primitive).
193    pub src_ctx: N3MinimalContext,
194    /// Receiver context (prepared by kernel before migration).
195    pub dst_ctx: N3MinimalContext,
196    /// Atomic state: `MigrationState`.
197    pub state: AtomicU8,
198    _pad_state: [u8; 3],
199    /// Monotonically increasing migration counter.
200    pub generation: AtomicU32,
201    /// Message length in bytes.
202    pub msg_len: u16,
203    /// Migration flags.
204    pub flags: u16,
205    _pad_flags: [u8; 4],
206    /// TSC snapshot at migration start (for watchdog).
207    pub tsc_start: AtomicU64,
208    /// Thread ID of the frame owner.
209    pub owner_tid: AtomicU64,
210    /// Reserved padding for future use and cache-line alignment.
211    pub _pad: [u8; 32],
212}
213
214// Static assertion: N3 minimal context layout must be exactly 128 bytes.
215// This is verified both by the `const _` block and by the unit test.
216// The sender_rip capture in send() relies on [rbp+8] which requires
217// frame pointers (force-frame-pointers = true in workspace Cargo.toml).
218const _: () = {
219    assert!(core::mem::size_of::<N3MinimalContext>() == 128);
220    assert!(core::mem::align_of::<N3MinimalContext>() == 64);
221    assert!(core::mem::size_of::<MigrationFrame>() == 320);
222    assert!(core::mem::align_of::<MigrationFrame>() == 64);
223    assert!(core::mem::offset_of!(MigrationFrame, state) == 0x100);
224    assert!(core::mem::offset_of!(MigrationFrame, generation) == 0x104);
225    assert!(core::mem::offset_of!(MigrationFrame, msg_len) == 0x108);
226    assert!(core::mem::offset_of!(MigrationFrame, flags) == 0x10A);
227    assert!(core::mem::offset_of!(MigrationFrame, tsc_start) == 0x110);
228    assert!(core::mem::offset_of!(MigrationFrame, owner_tid) == 0x118);
229    // N3MinimalContext field offsets (for ASM verification).
230    assert!(core::mem::offset_of!(N3MinimalContext, r15) == 0x00);
231    assert!(core::mem::offset_of!(N3MinimalContext, r14) == 0x08);
232    assert!(core::mem::offset_of!(N3MinimalContext, r13) == 0x10);
233    assert!(core::mem::offset_of!(N3MinimalContext, r12) == 0x18);
234    assert!(core::mem::offset_of!(N3MinimalContext, rbp) == 0x20);
235    assert!(core::mem::offset_of!(N3MinimalContext, rbx) == 0x28);
236    assert!(core::mem::offset_of!(N3MinimalContext, rdx) == 0x30);
237    assert!(core::mem::offset_of!(N3MinimalContext, rax) == 0x38);
238    assert!(core::mem::offset_of!(N3MinimalContext, rflags) == 0x40);
239    assert!(core::mem::offset_of!(N3MinimalContext, rsp) == 0x48);
240    assert!(core::mem::offset_of!(N3MinimalContext, rip) == 0x50);
241    assert!(core::mem::offset_of!(N3MinimalContext, cr3_pcid) == 0x58);
242};
243
244// ============================================================================
245// Static frame pool
246// ============================================================================
247
248/// Number of pre-allocated migration frames.
249const N3_FRAME_POOL_SIZE: usize = 64;
250
251/// Virtual address where the MigrationFrame is mapped in both address spaces.
252/// Located in canonical upper-half, just below the HHDM boundary.
253pub const N3_SHARED_FRAME_VA: u64 = 0xFFFF_C000_0000_1000;
254
255/// Virtual address where the shared message buffer is mapped.
256/// Must be distinct from N3_SHARED_FRAME_VA to avoid page table conflicts.
257pub const N3_SHARED_MSG_BUF_VA: u64 = 0xFFFF_C000_0000_2000;
258
259/// Return safe kernel-mode rflags for N3 context switching.
260///
261/// Bit 1 (reserved) must always be 1.  Bit 9 (IF) is set to keep interrupts
262/// enabled in the kernel handler.  All other bits are cleared to avoid
263/// restoring user-modified flags (TF, AC, etc.) into kernel context.
264fn safe_kernel_rflags() -> u64 {
265    // Bit 1 = reserved (must be 1), Bit 9 = IF (interrupts enabled)
266    (1 << 1) | (1 << 9)
267}
268
269/// Size of the per-N3Transport handler stack (1 page).
270/// After CR3 switch, the ASM primitive loads RSP from `dst_ctx.rsp` which
271/// points to this stack with the handler address as the return address.
272const N3_HANDLER_STACK_SIZE: usize = 4096;
273
274/// Static pool of MigrationFrame slots.
275///
276/// Access is serialized by `N3_FRAME_ALLOC` SpinLock. The `UnsafeCell`
277/// avoids `static mut` UB while the lock guarantees exclusive access.
278struct FramePool {
279    inner: core::cell::UnsafeCell<[MaybeUninit<MigrationFrame>; N3_FRAME_POOL_SIZE]>,
280}
281
282// SAFETY: all access to inner is serialized by N3_FRAME_ALLOC SpinLock.
283unsafe impl Sync for FramePool {}
284
285impl FramePool {
286    const fn new() -> Self {
287        FramePool {
288            inner: core::cell::UnsafeCell::new(unsafe { MaybeUninit::uninit().assume_init() }),
289        }
290    }
291
292    fn get_ptr(&self, idx: usize) -> *mut MaybeUninit<MigrationFrame> {
293        unsafe { &mut (*self.inner.get())[idx] as *mut _ }
294    }
295
296    fn phys_addr(&self, idx: usize) -> u64 {
297        // SAFETY: The FramePool is a static array allocated in the kernel's
298        // BSS/data section. On x86_64 with the kernel model, statics live in
299        // the direct-map region or higher half. The HHDM offset converts the
300        // virtual address to a physical address.
301        //
302        // However, this assumes the pool is within the HHDM window. If the
303        // kernel is compiled with a different memory model, this subtraction
304        // yields a garbage physical address.
305        //
306        // To avoid this dependency, the prototype should ideally allocate
307        // frames via the physical frame allocator and map them, rather than
308        // using a static pool with HHDM arithmetic. For now, we assert that
309        // the pool address is above the HHDM base to catch model mismatches.
310        let ptr = self.get_ptr(idx) as u64;
311        let hhdm = crate::memory::hhdm_offset();
312        debug_assert!(
313            ptr >= hhdm,
314            "N3: FramePool not in HHDM region (ptr={:#x}, hhdm={:#x})",
315            ptr,
316            hhdm
317        );
318        ptr.wrapping_sub(hhdm)
319    }
320}
321
322static N3_FRAME_POOL: FramePool = FramePool::new();
323
324/// Bitmap-based O(1) frame allocator.
325struct FrameAllocator {
326    /// Bit i = 1 means frame i is allocated.
327    bitmap: [u64; N3_FRAME_POOL_SIZE / 64],
328    /// Number of currently allocated frames.
329    count: usize,
330}
331
332impl FrameAllocator {
333    const fn new() -> Self {
334        FrameAllocator {
335            bitmap: [0u64; N3_FRAME_POOL_SIZE / 64],
336            count: 0,
337        }
338    }
339
340    fn alloc(&mut self) -> Option<usize> {
341        for word_idx in 0..self.bitmap.len() {
342            if self.bitmap[word_idx] != u64::MAX {
343                let bit = self.bitmap[word_idx].trailing_ones() as usize;
344                self.bitmap[word_idx] |= 1 << bit;
345                self.count += 1;
346                return Some(word_idx * 64 + bit);
347            }
348        }
349        None
350    }
351
352    fn free(&mut self, index: usize) {
353        let word_idx = index / 64;
354        let bit = index % 64;
355        debug_assert!(self.bitmap[word_idx] & (1 << bit) != 0, "double free");
356        self.bitmap[word_idx] &= !(1 << bit);
357        self.count -= 1;
358    }
359
360    fn is_allocated(&self, index: usize) -> bool {
361        self.bitmap[index / 64] & (1 << (index % 64)) != 0
362    }
363}
364
365static N3_FRAME_ALLOC: SpinLock<FrameAllocator> = SpinLock::new(FrameAllocator::new());
366
367/// Allocate a MigrationFrame from the static pool.
368///
369/// Returns a pointer to the frame and its pool index.
370fn alloc_frame_slot() -> Option<(usize, *mut MigrationFrame)> {
371    let idx = with_irqs_disabled(|_token| {
372        let mut alloc = N3_FRAME_ALLOC.lock();
373        alloc.alloc()
374    })?;
375
376    // SAFETY: slot is freshly allocated via bitmap, exclusive access via SpinLock.
377    let frame = N3_FRAME_POOL.get_ptr(idx);
378    // SAFETY: slot is freshly allocated, MaybeUninit is writable.
379    unsafe {
380        frame.write(MaybeUninit::new(MigrationFrame {
381            src_ctx: N3MinimalContext::ZERO,
382            dst_ctx: N3MinimalContext::ZERO,
383            state: AtomicU8::new(MigrationState::Ready as u8),
384            _pad_state: [0; 3],
385            generation: AtomicU32::new(0),
386            msg_len: 0,
387            flags: 0,
388            _pad_flags: [0; 4],
389            tsc_start: AtomicU64::new(0),
390            owner_tid: AtomicU64::new(0),
391            _pad: [0u8; 32],
392        }));
393    }
394
395    Some((idx, frame as *mut MigrationFrame))
396}
397
398/// Free a MigrationFrame back to the pool.
399fn free_frame_slot(idx: usize) {
400    with_irqs_disabled(|_token| {
401        let mut alloc = N3_FRAME_ALLOC.lock();
402        alloc.free(idx);
403    });
404}
405
406/// Get the physical address of a frame in the static pool.
407fn frame_pool_phys_addr(idx: usize) -> u64 {
408    N3_FRAME_POOL.phys_addr(idx)
409}
410
411// ============================================================================
412// PCID management
413// ============================================================================
414
415/// Global PCID counter : monotonic allocation, panics at 4096 (prototype).
416static PCID_COUNTER: AtomicU16 = AtomicU16::new(1); // 0 = no PCID
417
418/// Maximum number of PCIDs before panic (x86-64 supports 4096).
419const MAX_PCIDS: u16 = 4095;
420
421/// Allocate a stable PCID for an address space.
422///
423/// Returns 0 if PCID is not available (N3c fallback).
424pub fn allocate_pcid() -> u16 {
425    let pcid = PCID_COUNTER.fetch_add(1, Ordering::Relaxed);
426    if pcid >= MAX_PCIDS {
427        log::warn!("N3: PCID exhaustion : falling back to N3c (full TLB flush)");
428        return 0;
429    }
430    pcid
431}
432
433/// Free a PCID back to the pool (called when an address space is destroyed).
434///
435/// This prevents PCID exhaustion in long-running systems with dynamic silo
436/// creation/destruction. The freed PCID is tracked for reuse, but the actual
437/// TLB invalidation on other cores is the caller's responsibility.
438pub fn free_pcid(pcid: u16) {
439    if pcid == 0 || pcid >= MAX_PCIDS {
440        return;
441    }
442    // NB: PCID reuse requires INVPCID on the target core before the next
443    // time this PCID is assigned. For the prototype, we simply log the free;
444    // a production implementation would use a freelist + generation counter
445    // (see Linux arch/x86/mm/context.c).
446    log::trace!("N3: PCID {} freed", pcid);
447}
448
449/// Check if PCID feature is available on this CPU.
450pub fn pcid_available() -> bool {
451    #[cfg(target_arch = "x86_64")]
452    {
453        // 1. CPUID check: bit 17 of ECX after CPUID(EAX=1) indicates PCID support.
454        let (_, _, ecx, _) = crate::arch::cpuid(1, 0);
455        if ecx & (1 << 17) == 0 {
456            return false;
457        }
458        // 2. Check CR4.PCIDE (bit 17) is actually set (may be masked by hypervisor).
459        //    Intel SDM Vol.3A §4.10.4: CR4.PCIDE = 1 enables PCID in CR3.
460        let cr4 = crate::x86_crate_shim::registers::control::Cr4::read();
461        cr4.contains(crate::x86_crate_shim::registers::control::Cr4Flags::PCID)
462    }
463    #[cfg(target_arch = "riscv64")]
464    {
465        false
466    }
467}
468
469/// Select the N3 tier based on actual PCID capability.
470///
471/// Distinguishes theoretical CPU support from operational capability:
472/// - `N3Tier::PcidPreserving` requires PCID available AND a valid PCID > 0
473/// - `N3Tier::FullIsolation` is used when PCID is unavailable or exhausted
474pub fn select_n3_tier(pcid: u16) -> N3Tier {
475    if pcid_available() && pcid > 0 {
476        N3Tier::PcidPreserving
477    } else {
478        N3Tier::FullIsolation
479    }
480}
481
482// ============================================================================
483// validate_rip()
484// ============================================================================
485
486/// Validate that `rip` points to an authorized executable page.
487///
488/// Checks:
489/// - Belongs to an executable VMA
490/// - PTE has NX=0
491/// - Not in kernel ring, MigrationFrame, or non-executable zones
492/// - Part of a registered handler or authorized code range
493fn validate_rip(rip: u64, address_space: &AddressSpace) -> Result<(), IpcError> {
494    // Kernel addresses (upper half) are not valid user RIP targets.
495    if rip >= 0xFFFF_8000_0000_0000 {
496        return Err(IpcError::InvalidRip);
497    }
498
499    // MigrationFrame shared region is not executable.
500    if (N3_SHARED_FRAME_VA..N3_SHARED_FRAME_VA + 0x1000).contains(&rip) {
501        return Err(IpcError::InvalidRip);
502    }
503
504    // Null or near-null RIP is invalid.
505    if rip < 0x1000 {
506        return Err(IpcError::InvalidRip);
507    }
508
509    // validate_rip() performs page-level safety checks only: present, executable,
510    // not in forbidden zones. The RIP to belong to
511    // a "registered handler or authorized code range" : this registration check
512    // is performed by the CALLER (send()) which compares rip against the
513    // receiver's `trampoline_entry` field BEFORE calling validate_rip().
514    //
515    // validate_rip() is therefore a SECOND LINE OF DEFENSE that catches
516    // configuration errors (e.g., trampoline_entry pointing to a data page).
517    //
518    // TOCTOU note: The receiver's page tables could be modified between this
519    // check and the CR3 switch. However, the receiver's trampoline page is
520    // pinned and set to read-only by the kernel at endpoint creation time,
521    // preventing modification even by the receiver itself. The CR3 switch
522    // immediately after this check makes any concurrent modification irrelevant
523    // : the receiver executes in its own AS, using the mapping we validated.
524
525    // Walk the page tables to verify the page is present and executable.
526    // CRITICAL: Also check the U/S bit : the RIP target must be a supervisor
527    // page (Ring 0), not a user page. Accepting a user page would allow a
528    // userspace task to redirect kernel execution to arbitrary user code.
529    let cr3_phys = address_space.cr3();
530    let hhdm = crate::memory::hhdm_offset();
531
532    match unsafe { walk_page_tables_executable(rip, cr3_phys.as_u64(), hhdm) } {
533        Ok(true) => Ok(()),
534        Ok(false) => Err(IpcError::InvalidRip),
535        Err(_) => Err(IpcError::InvalidRip),
536    }
537}
538
539/// Walk x86-64 4-level page tables to check if `vaddr` is present, executable,
540/// and supervisor-only (U/S=0).
541///
542/// Returns `Ok(true)` if the final PTE meets all conditions.
543/// Rejects user-mode pages (U/S=1) as RIP targets for migration.
544unsafe fn walk_page_tables_executable(vaddr: u64, cr3_phys: u64, hhdm: u64) -> Result<bool, ()> {
545    let pml4 = (cr3_phys + hhdm) as *const u64;
546
547    // PML4: check present + U/S (bit 2: 0=supervisor, 1=user)
548    let pml4_idx = ((vaddr >> 39) & 0x1FF) as usize;
549    let pml4_entry = unsafe { core::ptr::read_volatile(pml4.add(pml4_idx)) };
550    if pml4_entry & 1 == 0 {
551        return Err(());
552    }
553    if pml4_entry & 4 != 0 {
554        return Err(());
555    } // U/S=1 => reject
556
557    // PDPT: check present + U/S
558    let pdpt_phys = pml4_entry & 0x000F_FFFF_FFFF_F000;
559    let pdpt = (pdpt_phys + hhdm) as *const u64;
560    let pdpt_idx = ((vaddr >> 30) & 0x1FF) as usize;
561    let pdpt_entry = unsafe { core::ptr::read_volatile(pdpt.add(pdpt_idx)) };
562    if pdpt_entry & 1 == 0 {
563        return Err(());
564    }
565    if pdpt_entry & 4 != 0 {
566        return Err(());
567    } // U/S=1 => reject
568
569    // 1 GiB page? Check NX + U/S
570    if pdpt_entry & (1 << 7) != 0 {
571        if pdpt_entry & (1 << 63) != 0 {
572            return Err(());
573        } // NX=1 => reject
574        return Ok(true);
575    }
576
577    // Page Directory: check present + U/S
578    let pd_phys = pdpt_entry & 0x000F_FFFF_FFFF_F000;
579    let pd = (pd_phys + hhdm) as *const u64;
580    let pd_idx = ((vaddr >> 21) & 0x1FF) as usize;
581    let pd_entry = unsafe { core::ptr::read_volatile(pd.add(pd_idx)) };
582    if pd_entry & 1 == 0 {
583        return Err(());
584    }
585    if pd_entry & 4 != 0 {
586        return Err(());
587    } // U/S=1 => reject
588
589    // 2 MiB page? Check NX
590    if pd_entry & (1 << 7) != 0 {
591        if pd_entry & (1 << 63) != 0 {
592            return Err(());
593        } // NX=1 => reject
594        return Ok(true);
595    }
596
597    // Page Table: check present + U/S + NX
598    let pt_phys = pd_entry & 0x000F_FFFF_FFFF_F000;
599    let pt = (pt_phys + hhdm) as *const u64;
600    let pt_idx = ((vaddr >> 12) & 0x1FF) as usize;
601    let pt_entry = unsafe { core::ptr::read_volatile(pt.add(pt_idx)) };
602    if pt_entry & 1 == 0 {
603        return Err(());
604    }
605    if pt_entry & 4 != 0 {
606        return Err(());
607    } // U/S=1 => reject user page
608    if pt_entry & (1 << 63) != 0 {
609        return Err(());
610    } // NX=1 => reject
611
612    Ok(true)
613}
614
615// ============================================================================
616// Context preparation
617// ============================================================================
618
619/// Prepare a MigrationFrame for a send operation.
620///
621/// Sets up `src_ctx` (sender), `dst_ctx` (receiver), copies the message
622/// into the shared buffer, increments generation, and transitions state
623/// to Active.
624fn n3_prepare_migration(
625    frame: &mut MigrationFrame,
626    msg_buf: *mut u8,
627    sender_cr3: u64,
628    sender_rsp: u64,
629    sender_rip: u64,
630    handler_stack_top: u64,
631    receiver_task: &Task,
632    msg: &[u8],
633) -> Result<(), IpcError> {
634    // Prepare sender context (saved by ASM primitive).
635    frame.src_ctx.cr3_pcid = sender_cr3;
636    frame.src_ctx.rsp = sender_rsp;
637    frame.src_ctx.rip = sender_rip;
638    // P0 fix: initialize rflags with safe kernel defaults.
639    // A zero rflags would clear IF (interrupts) and other critical bits.
640    frame.src_ctx.rflags = safe_kernel_rflags();
641
642    // Prepare receiver context.
643    let recv_handler = receiver_task.trampoline_entry.load(Ordering::Acquire);
644
645    if recv_handler == 0 {
646        return Err(IpcError::TransportFailed);
647    }
648
649    let recv_cr3 = receiver_task.process.address_space_arc().cr3().as_u64();
650
651    frame.dst_ctx.rip = recv_handler;
652    frame.dst_ctx.cr3_pcid = recv_cr3;
653    // P0 fix: destination context also gets safe kernel rflags.
654    frame.dst_ctx.rflags = safe_kernel_rflags();
655
656    // CRITICAL: The destination kernel stack must contain the handler address
657    // as the return address for the `ret` instruction after CR3 switch.
658    // We use the per-transport handler stack (kernel upper half, shared across
659    // all address spaces) to ensure accessibility after CR3 switch.
660    // Layout: [handler_stack_top - 8] = recv_handler (return address for ret).
661    //
662    // SAFETY: handler_stack_top points to the transport's dedicated stack page,
663    // allocated in new(). The CAS state machine (Ready=>Active) ensures exclusive
664    // access. The -8 offset places the handler address as if it were pushed.
665    let trampoline_top = (handler_stack_top - 8) as *mut u64;
666    unsafe {
667        // Write handler address at the trampoline top (this is what `ret` will pop).
668        core::ptr::write_volatile(trampoline_top, recv_handler);
669    }
670    // dst_ctx.rsp points to the trampoline area where the handler address is stored.
671    // After CR3 switch, `mov rsp, [rdi+0xC8]` loads this, and `ret` pops recv_handler.
672    frame.dst_ctx.rsp = trampoline_top as u64;
673
674    // Copy message into the shared buffer.
675    let msg_len = shared_msg_write(msg_buf, msg)?;
676    frame.msg_len = msg_len;
677
678    // CAS Ready => Active. Must succeed before touching generation.
679    if frame
680        .state
681        .compare_exchange(
682            MigrationState::Ready as u8,
683            MigrationState::Active as u8,
684            Ordering::AcqRel,
685            Ordering::Acquire,
686        )
687        .is_err()
688    {
689        return Err(IpcError::WouldBlock);
690    }
691
692    // Increment generation AFTER successful CAS.
693    // The generation must only advance for committed migrations.
694    frame.generation.fetch_add(1, Ordering::Release);
695
696    // Record timestamp and owner.
697    let tsc = crate::arch::rdtsc();
698    frame.tsc_start.store(tsc, Ordering::Release);
699    if let Some(tid) = current_task_id() {
700        frame.owner_tid.store(tid.as_u64(), Ordering::Release);
701    }
702
703    Ok(())
704}
705
706/// Maximum message size for N3 transport (separate buffer, not in frame).
707pub const N3_MSG_BUF_SIZE: usize = 2048;
708
709/// Wrapper for a raw pointer to the shared message buffer.
710///
711/// # Safety
712/// The pointer is valid for the lifetime of the N3Transport and is mapped
713/// in both sender and receiver address spaces. All access is serialized
714/// by the MigrationFrame state machine.
715struct MsgBuffer(*mut u8);
716
717// SAFETY: MsgBuffer is used only from a single migration context at a time,
718// protected by the MigrationFrame CAS state machine.
719unsafe impl Send for MsgBuffer {}
720unsafe impl Sync for MsgBuffer {}
721
722impl MsgBuffer {
723    fn as_ptr(&self) -> *mut u8 {
724        self.0
725    }
726}
727
728/// Read the message payload from a shared message buffer.
729fn shared_msg_read(msg_buf: *const u8, msg_len: u16, buf: &mut [u8]) -> Result<usize, IpcError> {
730    let len = msg_len as usize;
731    if len > buf.len() {
732        return Err(IpcError::BufferTooSmall);
733    }
734    if len > N3_MSG_BUF_SIZE {
735        return Err(IpcError::MessageTooLarge);
736    }
737    let src = unsafe { core::slice::from_raw_parts(msg_buf, len) };
738    buf[..len].copy_from_slice(src);
739    Ok(len)
740}
741
742/// Write a message payload into a shared message buffer.
743fn shared_msg_write(msg_buf: *mut u8, msg: &[u8]) -> Result<u16, IpcError> {
744    if msg.len() > N3_MSG_BUF_SIZE {
745        return Err(IpcError::MessageTooLarge);
746    }
747    let dst = unsafe { core::slice::from_raw_parts_mut(msg_buf, msg.len()) };
748    dst.copy_from_slice(msg);
749    Ok(msg.len() as u16)
750}
751
752// ============================================================================
753// ASM Primitive
754// ============================================================================
755
756/// ASM migration primitive.
757///
758/// # Safety
759/// - `frame` must point to a valid MigrationFrame mapped at the same VA
760///   in both sender and receiver address spaces.
761/// - Interrupts must be enabled before calling (the primitive will CLI).
762/// - The caller must be on a valid kernel stack.
763///
764/// # Layout adjusted for a 64b align padding
765///
766/// ```text
767/// Offset  Field
768/// 0x00    src_ctx.r15
769/// 0x08    src_ctx.r14
770/// 0x10    src_ctx.r13
771/// 0x18    src_ctx.r12
772/// 0x20    src_ctx.rbp
773/// 0x28    src_ctx.rbx
774/// 0x30    src_ctx.rdx
775/// 0x38    src_ctx.rax
776/// 0x40    src_ctx.rflags
777/// 0x48    src_ctx.rsp
778/// 0x50    src_ctx.rip
779/// 0x58    src_ctx.cr3_pcid
780/// 0x60-0x7F  (alignment padding)
781/// 0x80    dst_ctx.r15
782/// 0x88    dst_ctx.r14
783/// 0x90    dst_ctx.r13
784/// 0x98    dst_ctx.r12
785/// 0xA0    dst_ctx.rbp
786/// 0xA8    dst_ctx.rbx
787/// 0xB0    dst_ctx.rdx
788/// 0xB8    dst_ctx.rax
789/// 0xC0    dst_ctx.rflags
790/// 0xC8    dst_ctx.rsp
791/// 0xD0    dst_ctx.rip
792/// 0xD8    dst_ctx.cr3_pcid
793/// 0xE0-0xFF (alignment padding)
794/// 0x100   state (AtomicU8)
795/// 0x104   generation (AtomicU32)
796/// ```
797///
798/// # Behavior
799/// 1. Saves source context to `frame.src_ctx`
800/// 2. CLI (≤3 instructions) + CR3 switch to `frame.dst_ctx.cr3_pcid`
801/// 3. Restores destination context from `frame.dst_ctx`
802/// 4. Sets `frame.state = Ready`, increments `generation`
803/// 5. Returns via `ret` (pops RIP from restored `dst_ctx.rsp`)
804#[unsafe(naked)]
805pub unsafe extern "C" fn n3b_migrate_asm(frame: *mut MigrationFrame) {
806    core::arch::naked_asm!(
807        // ── Phase 1: save src_ctx ──
808        "mov [rdi + 0x00], r15",
809        "mov [rdi + 0x08], r14",
810        "mov [rdi + 0x10], r13",
811        "mov [rdi + 0x18], r12",
812        "mov [rdi + 0x20], rbp",
813        "mov [rdi + 0x28], rbx",
814        "mov [rdi + 0x30], rdx",
815        "mov [rdi + 0x38], rax",
816        "pushfq",
817        "pop rax",
818        "mov [rdi + 0x40], rax", // rflags
819        "mov [rdi + 0x48], rsp",
820        // NOTE: src_ctx.rip was already set by n3_prepare_migration().
821        // We do NOT overwrite it with RCX : on Strategy A, the kernel
822        // sets src_ctx.rip before calling us. See §11.2 for the contract.
823        // ── Phase 2: CLI (<3 instr) + CR3 switch ──
824        // We need a 3 instructions **MAX** between CLI and CR3 write.
825        // Here: mov rax (1) => cli (2) => mov cr3 (3). Satisfied.
826        // After CR3 switch, we restore dst_ctx with interrupts still disabled.
827        // The 8 restore instructions + pushfq/popfq/sti happen AFTER the CR3
828        // switch in the receiver's address space : this is intentional and does
829        // not violate the ≤3 instruction window (which only covers CLI=>CR3).
830        "mov rax, [rdi + 0xD8]", // dst_ctx.cr3_pcid (at 0x80+0x58=0xD8)
831        "cli",
832        "mov cr3, rax",
833        // ── Phase 3: restore dst_ctx (starts at offset 0x80) ──
834        // IMPORTANT: rsp (offset 0xC8) is restored LAST, just before ret.
835        // Every memory access between CR3 switch and rsp restore uses
836        // RDI (shared fixed-VA, valid in both AS) : never RSP.
837        "mov r15, [rdi + 0x80]",
838        "mov r14, [rdi + 0x88]",
839        "mov r13, [rdi + 0x90]",
840        "mov r12, [rdi + 0x98]",
841        "mov rbp, [rdi + 0xA0]",
842        "mov rbx, [rdi + 0xA8]",
843        "mov rdx, [rdi + 0xB0]",
844        // Load rflags from dst_ctx.rflags at offset 0x80+0x40 = 0xC0.
845        // Note: dst_ctx.rax (0xB8) is a GPR, NOT flags : do not confuse.
846        "mov rax, [rdi + 0xC0]", // dst_ctx.rflags
847        "push rax",
848        "popfq", // restore IF=1
849        "sti",   // guarantee IF=1
850        // ── Phase 4: restore RSP from dst_ctx ──
851        // CRITICAL: RSP must be restored BEFORE `ret`. The destination kernel
852        // stack is shared (kernel upper half maps identically in all AS).
853        // dst_ctx.rsp was set by n3_prepare_migration() to point to a stack
854        // frame containing the handler entry address as the return address.
855        "mov rsp, [rdi + 0xC8]", // dst_ctx.rsp
856        // ── Phase 5: receiver handler runs (state is still Active) ──
857        // The ASM does NOT set state = Ready. The receiver handler MUST
858        // do that after consuming the message (see recv() protocol).
859        // This prevents the TOCTOU where the receiver sees state=Ready
860        // before having read the message. Generation is managed by the
861        // kernel in n3_prepare_migration/recv : NOT by the ASM.
862        // ── Phase 6: ret into receiver handler ──
863        // SAFETY: RSP now points to the destination kernel stack with the
864        // handler address at [RSP]. `ret` pops it and jumps there.
865        // The destination kernel stack must be valid and mapped in both AS
866        // (kernel upper half is shared). If corrupted, this is the first
867        // point of failure.
868        "ret",
869        //
870        // Invariant: the restored dst_ctx.rsp must point to a valid, readable,
871        // kernel-mode stack frame.
872    );
873}
874
875// ============================================================================
876// IPI synchronization
877// ============================================================================
878
879/// Per-CPU pending migration frame pointer.
880/// Set by the sender before sending the IPI, consumed by the IPI handler.
881static N3_PENDING_MIGRATION: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
882    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
883
884/// Send a migration-sync IPI to the target CPU.
885fn send_n3_sync_ipi(target_apic_id: u32) {
886    let icr_low = apic::IPI_N3_MIGRATE_VECTOR as u32 | (1 << 14);
887    apic::send_ipi_raw(target_apic_id, icr_low);
888}
889
890/// Naked IPI handler for N3 migration synchronization.
891///
892/// When a cross-core migration completes, the receiver sends this IPI to the
893/// sender's core. The handler restores the sender's kernel context (RSP, RIP,
894/// RFLAGS) from `MigrationFrame.src_ctx` and returns via `iretq`.
895///
896/// The interrupted context was the sender's `send()` function. By modifying
897/// the InterruptStackFrame fields before the hardware `iretq`, we redirect
898/// execution to the sender's saved return address on its original kernel stack.
899///
900/// # Safety
901/// Registered as a naked IDT entry. On entry: SS, RSP, RFLAGS, CS, RIP pushed
902/// by hardware. `rdi` points at the InterruptStackFrame (set by IDT dispatch).
903#[unsafe(naked)]
904pub unsafe extern "C" fn n3_migrate_ipi_entry(rdi: *mut u8) -> ! {
905    core::arch::naked_asm!(
906        // ── Save scratch registers ──
907        "push rax",
908        "push rcx",
909        "push rdx",
910        "push rsi",
911        "push r8",
912        "push r9",
913        "push r10",
914        "push r11",
915
916        // ── Check pending migration ──
917        // per_cpu_index via GS:base (offset 0 in PerCpu struct).
918        "mov rcx, qword ptr gs:[0]",    // current_cpu_index
919        "lea rsi, [rip + {pending}]",    // &N3_PENDING_MIGRATION
920        "mov rax, [rsi + rcx * 8]",      // pending = N3_PENDING_MIGRATION[cpu]
921        "test rax, rax",
922        "jz .no_pending",
923
924        // ── Clear pending flag ──
925        "mov qword ptr [rsi + rcx * 8], 0",
926
927        // ── rax = MigrationFrame ptr ──
928        // src_ctx starts at offset 0x00.
929        // src_ctx.rflags = 0x40, src_ctx.rsp = 0x48, src_ctx.rip = 0x50.
930
931        // ── Switch to sender's address space ──
932        "mov rcx, [rax + 0x58]",        // src_ctx.cr3_pcid
933        "test rcx, rcx",
934        "jz .skip_cr3",
935        "mov r11, 0x0000FFFFFFFFFFFF",
936        "and rcx, r11", // clear high 16 bits (reserved/PCID)
937        "mov r11, 0xFFFFFFFFFFFFF000",
938        "and rcx, r11", // clear low 12 bits (page offset)
939        "mov cr3, rcx",
940        ".skip_cr3:",
941
942        // ── Build iretq frame on the interrupted stack ──
943        // rdi points to InterruptStackFrame pushed by hardware.
944        // Overwrite it with the sender's context.
945        // InterruptStackFrame layout:
946        //   [+0x00] SS       [+0x08] RSP      [+0x10] RFLAGS
947        //   [+0x18] CS       [+0x20] RIP      [+0x28] (error code, skipped)
948        //
949        // iretq pops: RIP, CS, RFLAGS, RSP, SS (5 × u64 = 40 bytes).
950        //
951        // Preserve original CS and SS from the interrupted frame.
952        // Overwrite RSP, RFLAGS, RIP with sender's values.
953
954        "mov rcx, [rdi + 0x18]",        // original CS (kernel CS = 0x08)
955        "mov rdx, [rdi + 0x00]",        // original SS (0 for Ring 0)
956
957        "mov rsi, [rax + 0x48]",        // src_ctx.rsp  => sender's kernel RSP
958        "mov r8,  [rax + 0x40]",        // src_ctx.rflags
959        "mov r9,  [rax + 0x50]",        // src_ctx.rip  => sender's return address
960
961        "mov [rdi + 0x00], rdx",        // SS  = original (Ring 0)
962        "mov [rdi + 0x08], rsi",        // RSP = sender's kernel stack
963        "mov [rdi + 0x10], r8",         // RFLAGS = sender's flags
964        "mov [rdi + 0x18], rcx",        // CS  = original (0x08)
965        "mov [rdi + 0x20], r9",         // RIP = sender's return address
966
967        // ── Send EOI ──
968        "mov dword ptr [0x0000FEE000B0], 0", // LAPIC EOI
969
970        // ── Restore scratch and return ──
971        // Pop scratch registers, then let the normal IDT return path
972        // (pop GPRs + iretq) restore from the modified frame.
973        "pop r11",
974        "pop r10",
975        "pop r9",
976        "pop r8",
977        "pop rsi",
978        "pop rdx",
979        "pop rcx",
980        "pop rax",
981        // Return to IDT stub which pops GPRs and does iretq.
982        "ret",
983
984        ".no_pending:",
985        // Spurious IPI : send EOI and return to interrupted context.
986        "mov dword ptr [0x0000FEE000B0], 0",
987        "pop r11",
988        "pop r10",
989        "pop r9",
990        "pop r8",
991        "pop rsi",
992        "pop rdx",
993        "pop rcx",
994        "pop rax",
995        "ret",
996
997        pending = sym N3_PENDING_MIGRATION,
998    );
999}
1000
1001/// Fallback handler for N3 migration IPI (non-naked path).
1002///
1003/// Called from the `extern "x86-interrupt"` stub if the naked entry is not
1004/// used. Clears the pending flag and sends EOI.
1005pub extern "C" fn n3_migrate_ipi_handler() {
1006    let cpu_idx = crate::arch::percpu::current_cpu_index();
1007    N3_PENDING_MIGRATION[cpu_idx].store(0, Ordering::Release);
1008    apic::eoi();
1009}
1010
1011// ============================================================================
1012// WATCHDOG
1013// ============================================================================
1014
1015/// Default watchdog timeout in TSC cycles (~10ms at 3GHz).
1016const N3_WATCHDOG_TIMEOUT: u64 = 30_000_000;
1017
1018/// Watchdog state per frame.
1019struct WatchdogEntry {
1020    frame_phys: u64,
1021    timeout: u64,
1022}
1023
1024/// Global watchdog table.
1025static N3_WATCHDOG_TABLE: SpinLock<[Option<WatchdogEntry>; N3_FRAME_POOL_SIZE]> =
1026    SpinLock::new([const { None }; N3_FRAME_POOL_SIZE]);
1027
1028/// Register a frame with the watchdog.
1029fn watchdog_register(frame_idx: usize, frame_phys: u64) {
1030    let mut table = N3_WATCHDOG_TABLE.lock();
1031    if let Some(entry) = table.get_mut(frame_idx) {
1032        *entry = Some(WatchdogEntry {
1033            frame_phys,
1034            timeout: N3_WATCHDOG_TIMEOUT,
1035        });
1036    }
1037}
1038
1039/// Unregister a frame from the watchdog.
1040fn watchdog_unregister(frame_idx: usize) {
1041    let mut table = N3_WATCHDOG_TABLE.lock();
1042    if let Some(entry) = table.get_mut(frame_idx) {
1043        *entry = None;
1044    }
1045}
1046
1047/// Called from the timer ISR to check for stalled migrations.
1048///
1049/// For each registered frame in Active state, checks whether the migration
1050/// has exceeded the watchdog timeout. If so:
1051/// 1. Transitions Active => Stalled (CAS)
1052/// 2. Attempts recovery: Stalled => Reclaiming => Ready
1053/// 3. Logs the incident
1054///
1055/// Recovery resets the frame so it can be reused for future migrations.
1056/// The sender that initiated the stalled migration will see `WouldBlock` on
1057/// its next `send()` attempt (CAS Ready=>Active fails if another sender
1058/// claimed the frame first).
1059pub fn n3_watchdog_tick() {
1060    let now = crate::arch::rdtsc();
1061    let mut table = N3_WATCHDOG_TABLE.lock();
1062
1063    for entry in table.iter_mut() {
1064        let Some(entry) = entry else { continue };
1065        let frame = unsafe { &*(phys_to_virt(entry.frame_phys) as *const MigrationFrame) };
1066        let state = frame.state.load(Ordering::Acquire);
1067
1068        if state != MigrationState::Active as u8 {
1069            continue;
1070        }
1071
1072        let tsc_start = frame.tsc_start.load(Ordering::Acquire);
1073        if now.wrapping_sub(tsc_start) <= entry.timeout {
1074            continue;
1075        }
1076
1077        // Timeout detected: attempt Active => Stalled => Reclaiming => Ready.
1078        let cas_result = frame.state.compare_exchange(
1079            MigrationState::Active as u8,
1080            MigrationState::Stalled as u8,
1081            Ordering::AcqRel,
1082            Ordering::Acquire,
1083        );
1084
1085        if cas_result.is_err() {
1086            // Another CPU already transitioned the frame (e.g., recv completed).
1087            continue;
1088        }
1089
1090        log::warn!(
1091            "N3: watchdog timeout on frame at {:#x}, generation={}, recovering",
1092            entry.frame_phys,
1093            frame.generation.load(Ordering::Acquire),
1094        );
1095
1096        // Attempt recovery: Stalled => Reclaiming => Ready.
1097        watchdog_recover(frame);
1098    }
1099}
1100
1101/// Recover a stalled frame : reset to Ready via atomic CAS transitions.
1102fn watchdog_recover(frame: &MigrationFrame) {
1103    // Transition Stalled => Reclaiming (atomic CAS).
1104    if frame
1105        .state
1106        .compare_exchange(
1107            MigrationState::Stalled as u8,
1108            MigrationState::Reclaiming as u8,
1109            Ordering::AcqRel,
1110            Ordering::Acquire,
1111        )
1112        .is_err()
1113    {
1114        log::warn!("N3: watchdog recover: frame not in Stalled state, skipping");
1115        return;
1116    }
1117    log::warn!(
1118        "N3: recovering stalled frame, generation={}",
1119        frame.generation.load(Ordering::Acquire)
1120    );
1121    // Transition Reclaiming => Ready (atomic store, no contention expected).
1122    frame
1123        .state
1124        .store(MigrationState::Ready as u8, Ordering::Release);
1125}
1126
1127// ============================================================================
1128// Shared frame mapping
1129// ============================================================================
1130
1131/// Map a physical page into an address space at the specified virtual address.
1132///
1133/// The mapping is kernel-only (no `USER_ACCESSIBLE` flag) to enforce the
1134/// spec §8.4 invariant: frame permissions are managed exclusively by the
1135/// kernel, never by non-kernel parties.
1136fn map_page_in_space(
1137    frame_phys: u64,
1138    target_va: u64,
1139    address_space: &AddressSpace,
1140) -> Result<(), &'static str> {
1141    use crate::{
1142        arch::xshim::{PageTableFlags, PhysAddr, PhysFrame, Size4KiB, VirtAddr},
1143        x86_crate_shim::structures::paging::{Mapper, Page},
1144    };
1145
1146    let page = Page::<Size4KiB>::containing_address(VirtAddr::new(target_va));
1147    let phys_frame = PhysFrame::<Size4KiB>::containing_address(PhysAddr::new(frame_phys));
1148
1149    // Kernel-only, no USER_ACCESSIBLE (spec §8.4: permissions managed by kernel).
1150    let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
1151
1152    let mut mapper = unsafe { address_space.mapper() };
1153    let mut allocator = crate::memory::paging::BuddyFrameAllocator;
1154
1155    unsafe {
1156        match mapper.map_to(page, phys_frame, flags, &mut allocator) {
1157            Ok(flush) => {
1158                flush.flush();
1159                Ok(())
1160            }
1161            Err(_) => Err("Failed to map page into address space"),
1162        }
1163    }
1164}
1165
1166/// Map a MigrationFrame's physical page into both sender and receiver
1167/// address spaces at `N3_SHARED_FRAME_VA`.
1168fn map_frame_in_both_spaces(
1169    frame_phys: u64,
1170    sender_as: &AddressSpace,
1171    receiver_as: &AddressSpace,
1172) -> Result<(), &'static str> {
1173    map_page_in_space(frame_phys, N3_SHARED_FRAME_VA, sender_as)?;
1174    map_page_in_space(frame_phys, N3_SHARED_FRAME_VA, receiver_as)?;
1175    Ok(())
1176}
1177
1178/// Map a message buffer's physical page into both address spaces
1179/// at `N3_SHARED_MSG_BUF_VA`.
1180fn map_msg_buf_in_both_spaces(
1181    msg_buf_phys: u64,
1182    sender_as: &AddressSpace,
1183    receiver_as: &AddressSpace,
1184) -> Result<(), &'static str> {
1185    map_page_in_space(msg_buf_phys, N3_SHARED_MSG_BUF_VA, sender_as)?;
1186    map_page_in_space(msg_buf_phys, N3_SHARED_MSG_BUF_VA, receiver_as)?;
1187    Ok(())
1188}
1189
1190/// Unmap a single page from an address space and shoot down TLB on all CPUs.
1191fn unmap_page_in_space(target_va: u64, address_space: &AddressSpace) {
1192    use crate::{
1193        arch::xshim::{Size4KiB, VirtAddr},
1194        x86_crate_shim::structures::paging::{Mapper, Page},
1195    };
1196
1197    let page = Page::<Size4KiB>::containing_address(VirtAddr::new(target_va));
1198    let mut mapper = unsafe { address_space.mapper() };
1199
1200    if let Ok((_frame, flush)) = mapper.unmap(page) {
1201        flush.flush();
1202    }
1203    // Inter-CPU TLB shootdown for the unmapped page.
1204    crate::arch::tlb::shootdown_range(VirtAddr::new(target_va), VirtAddr::new(target_va + 0x1000));
1205}
1206
1207/// Unmap the MigrationFrame and message buffer from both address spaces.
1208fn unmap_from_both_spaces(sender_as: &AddressSpace, receiver_as: &AddressSpace) {
1209    unmap_page_in_space(N3_SHARED_FRAME_VA, sender_as);
1210    unmap_page_in_space(N3_SHARED_FRAME_VA, receiver_as);
1211    unmap_page_in_space(N3_SHARED_MSG_BUF_VA, sender_as);
1212    unmap_page_in_space(N3_SHARED_MSG_BUF_VA, receiver_as);
1213}
1214
1215// ============================================================================
1216// N3Transport
1217// ============================================================================
1218
1219/// N3 MMU transport : thread migration between distinct address spaces.
1220pub struct N3Transport {
1221    /// Index in the static frame pool.
1222    frame_idx: usize,
1223    /// Physical address of the MigrationFrame page.
1224    frame_phys: u64,
1225    /// Virtual address of the MigrationFrame (same in both AS).
1226    frame_virt: u64,
1227    /// Shared message buffer (kernel-allocated, mapped in both AS).
1228    msg_buf: MsgBuffer,
1229    /// Physical address of the message buffer.
1230    msg_buf_phys: u64,
1231    /// Dedicated handler stack (1 page, kernel-allocated).
1232    /// After CR3 switch, dst_ctx.rsp points to the top of this stack with
1233    /// the handler address as the return address.
1234    handler_stack_top: u64,
1235    /// Physical address of the handler stack.
1236    handler_stack_phys: u64,
1237    /// Sender task ID.
1238    sender_task_id: TaskId,
1239    /// Receiver task ID.
1240    receiver_task_id: TaskId,
1241    /// N3 tier (b or c).
1242    tier: N3Tier,
1243    /// Sender's PCID (0 for N3c).
1244    pcid_sender: u16,
1245    /// Receiver's PCID (0 for N3c).
1246    pcid_receiver: u16,
1247    /// Watchdog timeout in TSC cycles.
1248    watchdog_timeout_cycles: u64,
1249}
1250
1251// SAFETY: N3Transport is Send+Sync because all mutable access is protected
1252// by the MigrationFrame CAS state machine.
1253unsafe impl Send for N3Transport {}
1254unsafe impl Sync for N3Transport {}
1255
1256impl N3Transport {
1257    /// Create a new N3 transport between sender and receiver tasks.
1258    ///
1259    /// Allocates a MigrationFrame and a shared message buffer, maps them
1260    /// in both address spaces, and registers the endpoint with the watchdog.
1261    pub fn new(sender_task_id: TaskId, receiver_task_id: TaskId) -> Result<Self, IpcError> {
1262        let (frame_idx, _frame_ptr) = alloc_frame_slot().ok_or(IpcError::TransportFailed)?;
1263
1264        let frame_phys = frame_pool_phys_addr(frame_idx);
1265
1266        // Allocate a shared message buffer (1 page).
1267        let msg_buf_frame =
1268            with_irqs_disabled(allocate_frame).map_err(|_| IpcError::TransportFailed)?;
1269        let msg_buf_phys = msg_buf_frame.start_address.as_u64();
1270        let msg_buf = phys_to_virt(msg_buf_phys) as *mut u8;
1271
1272        // Map in both address spaces.
1273        let sender = get_task_by_id(sender_task_id).ok_or(IpcError::Disconnected)?;
1274        let receiver = get_task_by_id(receiver_task_id).ok_or(IpcError::Disconnected)?;
1275
1276        let sender_as = sender.process.address_space_arc();
1277        let receiver_as = receiver.process.address_space_arc();
1278
1279        if let Err(e) = map_frame_in_both_spaces(frame_phys, &sender_as, &receiver_as) {
1280            log::error!("N3: failed to map frame: {}", e);
1281            free_frame_slot(frame_idx);
1282            with_irqs_disabled(|token| free_frame(token, msg_buf_frame));
1283            return Err(IpcError::TransportFailed);
1284        }
1285
1286        // Map the message buffer in both address spaces at N3_SHARED_MSG_BUF_VA.
1287        if map_msg_buf_in_both_spaces(msg_buf_phys, &sender_as, &receiver_as).is_err() {
1288            log::error!("N3: failed to map message buffer");
1289            // P1 fix: unmap the frame that was already mapped in both spaces.
1290            unmap_page_in_space(N3_SHARED_FRAME_VA, &sender_as);
1291            unmap_page_in_space(N3_SHARED_FRAME_VA, &receiver_as);
1292            free_frame_slot(frame_idx);
1293            with_irqs_disabled(|token| free_frame(token, msg_buf_frame));
1294            return Err(IpcError::TransportFailed);
1295        }
1296
1297        // Allocate PCIDs BEFORE selecting tier : allocate_pcid() may return 0
1298        // if PCID is exhausted, which forces N3c even if the CPU supports PCID.
1299        let pcid_sender = allocate_pcid();
1300        let pcid_receiver = allocate_pcid();
1301
1302        // Select tier based on both CPU support AND availability.
1303        let tier = select_n3_tier(pcid_sender.min(pcid_receiver));
1304
1305        // Allocate a dedicated handler stack (1 page, kernel-allocated).
1306        // This stack is used as the trampoline after CR3 switch: the ASM
1307        // primitive loads RSP from dst_ctx.rsp and `ret` pops the handler
1308        // address from [RSP]. Must be in the kernel upper half (shared AS).
1309        let handler_stack_frame =
1310            with_irqs_disabled(allocate_frame).map_err(|_| IpcError::TransportFailed)?;
1311        let handler_stack_phys = handler_stack_frame.start_address.as_u64();
1312        let handler_stack_virt = phys_to_virt(handler_stack_phys) as u64;
1313        let handler_stack_top = handler_stack_virt + N3_HANDLER_STACK_SIZE as u64;
1314
1315        // Register with watchdog.
1316        watchdog_register(frame_idx, frame_phys);
1317
1318        Ok(N3Transport {
1319            frame_idx,
1320            frame_phys,
1321            frame_virt: N3_SHARED_FRAME_VA,
1322            msg_buf: MsgBuffer(msg_buf),
1323            msg_buf_phys,
1324            handler_stack_top,
1325            handler_stack_phys,
1326            sender_task_id,
1327            receiver_task_id,
1328            tier,
1329            pcid_sender,
1330            pcid_receiver,
1331            watchdog_timeout_cycles: N3_WATCHDOG_TIMEOUT,
1332        })
1333    }
1334
1335    /// Get a reference to the underlying MigrationFrame.
1336    pub(crate) fn frame(&self) -> &MigrationFrame {
1337        unsafe { &*(self.frame_virt as *const MigrationFrame) }
1338    }
1339
1340    /// Get the raw pointer to the MigrationFrame (for ASM primitive).
1341    pub(crate) fn frame_ptr(&self) -> *mut MigrationFrame {
1342        self.frame_virt as *mut MigrationFrame
1343    }
1344}
1345
1346impl core::fmt::Debug for N3Transport {
1347    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1348        f.debug_struct("N3Transport")
1349            .field("frame_idx", &self.frame_idx)
1350            .field("tier", &self.tier)
1351            .field("sender", &self.sender_task_id)
1352            .field("receiver", &self.receiver_task_id)
1353            .finish()
1354    }
1355}
1356
1357impl Drop for N3Transport {
1358    fn drop(&mut self) {
1359        watchdog_unregister(self.frame_idx);
1360
1361        // P0 fix: unmap shared pages from both address spaces BEFORE freeing
1362        // the physical frames. This prevents use-after-free when the frames
1363        // are reallocated to another process or structure.
1364        if let (Some(sender), Some(receiver)) = (
1365            get_task_by_id(self.sender_task_id),
1366            get_task_by_id(self.receiver_task_id),
1367        ) {
1368            let sender_as = sender.process.address_space_arc();
1369            let receiver_as = receiver.process.address_space_arc();
1370            unmap_from_both_spaces(&sender_as, &receiver_as);
1371        }
1372
1373        free_frame_slot(self.frame_idx);
1374
1375        // Free the message buffer physical page.
1376        if self.msg_buf_phys != 0 {
1377            let frame = crate::memory::PhysFrame::containing_address(
1378                crate::arch::xshim::PhysAddr::new(self.msg_buf_phys),
1379            );
1380            with_irqs_disabled(|token| free_frame(token, frame));
1381        }
1382
1383        // Free the handler stack physical page.
1384        if self.handler_stack_phys != 0 {
1385            let frame = crate::memory::PhysFrame::containing_address(
1386                crate::arch::xshim::PhysAddr::new(self.handler_stack_phys),
1387            );
1388            with_irqs_disabled(|token| free_frame(token, frame));
1389        }
1390    }
1391}
1392
1393impl IpcTransport for N3Transport {
1394    fn level(&self) -> TransportLevel {
1395        TransportLevel::Mmu
1396    }
1397
1398    fn capabilities(&self) -> TransportCapabilities {
1399        TransportCapabilities {
1400            max_message_size: N3_MSG_BUF_SIZE,
1401            blocking: true,
1402            zero_copy: false,
1403            vectored: false,
1404            directions: 2,
1405            estimated_cost_cycles: 800,
1406        }
1407    }
1408
1409    fn name(&self) -> &'static str {
1410        match self.tier {
1411            N3Tier::PcidPreserving => "n3b",
1412            N3Tier::FullIsolation => "n3c",
1413        }
1414    }
1415}
1416
1417impl IpcProducer for N3Transport {
1418    fn send(&self, msg: &[u8]) -> Result<(), IpcError> {
1419        // SAFETY: CAS state machine (Ready=>Active) provides logical exclusivity.
1420        // The &mut is scoped to this function; after CAS, only the ASM primitive
1421        // accesses the frame via raw pointers. Technically UB under Stacked Borrows,
1422        // but acceptable for a research kernel prototype where CAS guarantees
1423        // no concurrent access.
1424        let frame = unsafe { &mut *self.frame_ptr() };
1425
1426        // Get current task context.
1427        let receiver_task = get_task_by_id(self.receiver_task_id).ok_or(IpcError::Disconnected)?;
1428
1429        // Read current CR3.
1430        let (cr3_frame, _) = crate::x86_crate_shim::registers::control::Cr3::read();
1431        let sender_cr3 = cr3_frame.start_address().as_u64();
1432
1433        // Validate receiver's handler RIP.
1434        // Verify RIP matches the explicitly registered handler, not arbitrary code.
1435        let recv_rip = receiver_task.trampoline_entry.load(Ordering::Acquire);
1436        if recv_rip == 0 {
1437            return Err(IpcError::InvalidRip);
1438        }
1439        let recv_as = receiver_task.process.address_space_arc();
1440        validate_rip(recv_rip, &recv_as)?;
1441
1442        // Prepare the migration.
1443        let sender_rsp: u64;
1444        let sender_rip: u64;
1445        unsafe {
1446            core::arch::asm!("mov {}, rsp", out(reg) sender_rsp);
1447            // Capture return address from the stack. At this point in the
1448            // function, the return address is at [rbp + 8] when frame
1449            // pointers are enabled (kernel build default).
1450            //
1451            // SAFETY: kernel is compiled with frame pointers enabled
1452            // (-C force-frame-pointers=yes). If frame pointers are disabled,
1453            // this will read garbage : ensure the kernel build config is correct.
1454            core::arch::asm!("mov {}, [rbp + 8]", out(reg) sender_rip);
1455        }
1456
1457        n3_prepare_migration(
1458            frame,
1459            self.msg_buf.as_ptr(),
1460            sender_cr3,
1461            sender_rsp,
1462            sender_rip,
1463            self.handler_stack_top,
1464            &receiver_task,
1465            msg,
1466        )?;
1467
1468        // Inter-core sync if needed.
1469        // Spec §9.2: the sender must ensure message visibility before sending IPI.
1470        let target_cpu = receiver_task.home_cpu.load(Ordering::Acquire);
1471        let same_core = crate::arch::percpu::current_cpu_index() == target_cpu as usize;
1472
1473        if !same_core {
1474            if (target_cpu as usize) < crate::arch::percpu::MAX_CPUS {
1475                // Ensure all stores (message, frame metadata, state=Active)
1476                // are visible before the IPI is sent (spec §9.1).
1477                core::sync::atomic::fence(Ordering::Release);
1478
1479                // Store the VIRTUAL address : the IPI handler dereferences
1480                // it as a pointer in the kernel address space.
1481                N3_PENDING_MIGRATION[target_cpu].store(self.frame_virt, Ordering::Release);
1482
1483                // Send sync IPI. On x86-64, the ICR write is serializing,
1484                // which provides an implicit full barrier (spec §9.2).
1485                if let Some(target_apic) = crate::arch::percpu::apic_id_by_cpu_index(target_cpu) {
1486                    send_n3_sync_ipi(target_apic);
1487                }
1488            }
1489        }
1490
1491        // Execute the migration ASM primitive.
1492        // SAFETY: frame is valid, mapped in both AS, interrupts are enabled.
1493        unsafe {
1494            n3b_migrate_asm(self.frame_virt as *mut MigrationFrame);
1495        }
1496
1497        Ok(())
1498    }
1499
1500    fn try_send(&self, msg: &[u8]) -> Result<(), IpcError> {
1501        // The CAS inside n3_prepare_migration handles the state check atomically.
1502        // No need for a separate state check here (avoids TOCTOU).
1503        self.send(msg)
1504    }
1505}
1506
1507impl IpcConsumer for N3Transport {
1508    fn recv(&self, buf: &mut [u8]) -> Result<usize, IpcError> {
1509        let frame = self.frame();
1510
1511        // Verify the frame is in Active state.
1512        // Do NOT read from a Ready, Stalled, or Reclaiming frame.
1513        let state = frame.state.load(Ordering::Acquire);
1514        if state != MigrationState::Active as u8 {
1515            return Err(IpcError::WouldBlock);
1516        }
1517
1518        // Verify generation (spec §15.1).
1519        let gen = frame.generation.load(Ordering::Acquire);
1520        if gen == 0 {
1521            return Err(IpcError::WouldBlock);
1522        }
1523
1524        // Check message length.
1525        let msg_len = frame.msg_len;
1526        if msg_len == 0 {
1527            return Err(IpcError::WouldBlock);
1528        }
1529
1530        // Read the message from the shared buffer.
1531        // Use a guard to reset state=Ready even if the read fails,
1532        // preventing the frame from being stuck in Active forever.
1533        let n = match shared_msg_read(self.msg_buf.as_ptr(), msg_len, buf) {
1534            Ok(n) => n,
1535            Err(e) => {
1536                // Reset state so the frame can be reused.
1537                frame
1538                    .state
1539                    .store(MigrationState::Ready as u8, Ordering::Release);
1540                return Err(e);
1541            }
1542        };
1543
1544        // Signal completion: set state = Ready (spec §15 step 6).
1545        // This allows the sender (or next sender) to reuse the frame.
1546        // The sender's send() will CAS Ready=>Active to claim it.
1547        // NOTE: msg_len is intentionally NOT cleared : the next sender's
1548        // prepare_migration() overwrites it when writing the new message.
1549        frame
1550            .state
1551            .store(MigrationState::Ready as u8, Ordering::Release);
1552
1553        Ok(n)
1554    }
1555
1556    fn try_recv(&self, buf: &mut [u8]) -> Result<Option<usize>, IpcError> {
1557        match self.recv(buf) {
1558            Ok(n) => Ok(Some(n)),
1559            Err(IpcError::WouldBlock) => Ok(None),
1560            Err(e) => Err(e),
1561        }
1562    }
1563}
1564
1565// ============================================================================
1566// State machine helpers
1567// ============================================================================
1568
1569/// Check if a frame is in the Ready state.
1570pub fn n3_frame_is_ready(frame: &MigrationFrame) -> bool {
1571    frame.state.load(Ordering::Acquire) == MigrationState::Ready as u8
1572}
1573
1574/// Get the current migration state of a frame.
1575pub fn n3_frame_state(frame: &MigrationFrame) -> MigrationState {
1576    MigrationState::from_u8(frame.state.load(Ordering::Acquire)).unwrap_or(MigrationState::Ready)
1577}
1578
1579/// Get the current generation counter of a frame.
1580pub fn n3_frame_generation(frame: &MigrationFrame) -> u32 {
1581    frame.generation.load(Ordering::Acquire)
1582}