//! Native product shutdown adapter. Completion of earlier experiments is not //! authority to power off a product. All live product owners must first have //! published their real teardown and accounting receipts. //! //! The current native D3 path is read-only. This adapter can issue an actual //! negotiated VirtIO FLUSH barrier after that owner closes, but cannot turn it //! into evidence of data/metadata/journal writes that the product never made. use super::super::*; use turkos_kernel::runtime::{platform, psci_call}; use turkos_kernel::{virtio_mmio, virtio_ring}; const UNKNOWN: u64 = u64::MAX; const OBSERVED_RUNTIME: u64 = 1; const OBSERVED_LIFECYCLE: u64 = 1 << 1; const OBSERVED_PSCI: u64 = 1 << 2; const OBSERVED_BLOCK: u64 = 1 << 3; const OBSERVED_LEASE: u64 = 1 << 4; const OBSERVED_FLUSH: u64 = 1 << 5; const OBSERVED_RESET: u64 = 1 << 6; const OBSERVED_RECONCILED: u64 = 1 << 7; const OBSERVED_OFF_RETURN: u64 = 1 << 8; const PSCI_VERSION: u64 = 0x8400_0000; const PSCI_FEATURES: u64 = 0x8400_000a; const SYSTEM_OFF: u64 = 0x8400_0008; fn counter() -> u64 { let value: u64; unsafe { asm!("mrs {value}, CNTPCT_EL0", value = out(reg) value, options(nomem, nostack, preserves_flags)); } value } unsafe fn read32(base: u64, offset: u64) -> u32 { unsafe { core::ptr::read_volatile((base + offset) as *const u32) } } unsafe fn write32(base: u64, offset: u64, value: u32) { unsafe { core::ptr::write_volatile((base + offset) as *mut u32, value) } } unsafe fn write64(base: u64, offset: u64, value: u64) { unsafe { write32(base, offset, value as u32); write32(base, offset + 4, (value >> 32) as u32); } } fn psci(conduit: psci_call::Conduit, function: u64, argument: u64) -> u64 { let result: u64; // The conduit is discovered from the bounded boot DTB, never guessed from // QEMU defaults. Only EL1 on the boot CPU can reach this adapter. unsafe { match conduit { psci_call::Conduit::Hvc => asm!("hvc #0", inout("x0") function => result, inout("x1") argument => _, in("x2") 0u64, in("x3") 0u64, clobber_abi("C"), options(nostack)), psci_call::Conduit::Smc => asm!("smc #0", inout("x0") function => result, inout("x1") argument => _, in("x2") 0u64, in("x3") 0u64, clobber_abi("C"), options(nostack)), } } result } fn require_closed_owners() -> Result<(), &'static str> { // A completed phase bit alone does not prove that its device/CPU owners // are closed. Each owner has a separate receipt, initially unavailable. super::require_shutdown_prerequisites()?; super::d3_shell::require_closed()?; super::d4_net_ipc::require_drained()?; if !super::d5_smp::stopped() { return Err("native-d7-secondary-stop-receipt-missing"); } super::d6_accounting::require_reconciled() } fn block_base(boot: &BootData, tables: &mmu::Tables) -> Result { if boot.dtb_address == 0 || boot.dtb_size == 0 { return Err("native-d7-dtb-missing"); } let blob = unsafe { core::slice::from_raw_parts(boot.dtb_address as *const u8, boot.dtb_size) }; let nodes = dtb::discover_virtio_mmio(blob).map_err(|_| "native-d7-block-discovery")?; let mut block = None; for node in nodes.as_slice() { let last = node .base .checked_add(0x107) .ok_or("native-d7-block-mmio-overflow")?; for address in [node.base, last] { let descriptor = os_k700_translation(tables, address)?; if descriptor & 1 == 0 || (descriptor >> 2) & 7 != 1 { return Err("native-d7-block-mmio-not-device"); } } if unsafe { read32(node.base, 0) } != virtio_mmio::MAGIC { return Err("native-d7-block-magic"); } if unsafe { read32(node.base, 8) } != 2 { continue; } if unsafe { read32(node.base, 4) } != 2 || block.replace(node.base).is_some() { return Err("native-d7-block-ambiguous-or-legacy"); } } block.ok_or("native-d7-block-missing") } /// Issue exactly one real FLUSH request. No completion count is supplied by a /// caller: the used-ring identity, request type, length and status are read /// from the device-owned DMA pages after an acquire barrier. fn flush_queue( base: u64, lease: &mut virtio_ring::DmaLease, boot: &BootData, frequency: u64, out: &mut [u64; 32], ) -> Result<(), &'static str> { let frames = lease.frames().map_err(|_| "native-d7-dma-frames")?; let [desc, avail, used, _] = frames; virtio_ring::split_ring_pages( desc, avail, used, 4, boot.hardware.ram_base, boot.hardware.ram_size, ) .map_err(|_| "native-d7-ring-geometry")?; for (index, frame) in frames.iter().enumerate() { out[11 + index] = *frame; unsafe { core::ptr::write_bytes(*frame as *mut u8, 0, 4096) }; } unsafe { // The caller already required an unowned, reset device. Never reset a // live service merely to obtain a shutdown-looking measurement. write32(base, 0x70, 3); write32(base, 0x14, 0); let low = read32(base, 0x10); write32(base, 0x14, 1); let high = read32(base, 0x10); if low & virtio_mmio::BLK_F_FLUSH == 0 || high & virtio_mmio::MODERN_F_VERSION_1 == 0 || high & virtio_mmio::MODERN_F_IOMMU_PLATFORM != 0 { return Err("native-d7-flush-feature-required"); } // Preserve RO if offered. No OUT descriptor is ever submitted. let accepted_low = low & (virtio_mmio::BLK_F_FLUSH | virtio_mmio::BLK_F_RO); out[7] = u64::from(accepted_low); out[8] = u64::from(virtio_mmio::MODERN_F_VERSION_1); write32(base, 0x24, 0); write32(base, 0x20, accepted_low); write32(base, 0x24, 1); write32(base, 0x20, virtio_mmio::MODERN_F_VERSION_1); write32(base, 0x70, 0x0b); if read32(base, 0x70) != 0x0b { return Err("native-d7-features-readback"); } write32(base, 0x30, 0); if read32(base, 0x34) < 4 || read32(base, 0x44) != 0 { return Err("native-d7-queue-owned-or-small"); } write32(base, 0x38, 4); write64(base, 0x80, desc); write64(base, 0x90, avail); write64(base, 0xa0, used); asm!("dmb oshst", options(nostack, preserves_flags)); // Mark ownership live before making it visible to the device. lease.mark_ready().map_err(|_| "native-d7-lease-ready")?; write32(base, 0x44, 1); if read32(base, 0x44) != 1 { return Err("native-d7-queue-ready-readback"); } write32(base, 0x70, 0x0f); if read32(base, 0x70) != 0x0f { return Err("native-d7-driver-ready-readback"); } } let header = lease .request_subregion(0, 16) .map_err(|_| "native-d7-flush-header")?; let status = lease .request_subregion(16, 1) .map_err(|_| "native-d7-flush-status")?; let chain = [ virtio_ring::Descriptor { addr_le: header.to_le(), len_le: 16u32.to_le(), flags_le: virtio_ring::DESC_F_NEXT.to_le(), next_le: 1u16.to_le(), }, virtio_ring::Descriptor { addr_le: status.to_le(), len_le: 1u32.to_le(), flags_le: virtio_ring::DESC_F_WRITE.to_le(), next_le: 0, }, ]; out[20] = counter(); out[22] = virtio_ring::deadline_after( out[20], frequency .checked_mul(2) .ok_or("native-d7-deadline-overflow")?, ) .map_err(|_| "native-d7-deadline")?; unsafe { for (index, descriptor) in chain.into_iter().enumerate() { core::ptr::write_volatile( (desc as *mut virtio_ring::Descriptor).add(index), descriptor, ); } core::ptr::write_volatile( header as *mut virtio_ring::BlockReadHeader, virtio_ring::BlockReadHeader { type_le: 4u32.to_le(), reserved_le: 0, sector_le: 0, }, ); core::ptr::write_volatile(status as *mut u8, 0xff); core::ptr::write_volatile((avail + 4) as *mut u16, 0); asm!("dmb oshst", options(nostack, preserves_flags)); core::ptr::write_volatile((avail + 2) as *mut u16, 1u16.to_le()); asm!("dmb oshst", options(nostack, preserves_flags)); write32(base, 0x50, 0); } let observed = loop { let index = unsafe { u16::from_le(core::ptr::read_volatile((used + 2) as *const u16)) }; if index != 0 || virtio_ring::deadline_expired(counter(), out[22]) { break index; } core::hint::spin_loop(); }; unsafe { asm!("dmb oshld", options(nostack, preserves_flags)) }; out[21] = counter(); out[15] = u64::from(unsafe { u16::from_le(core::ptr::read_volatile((avail + 2) as *const u16)) }); out[16] = u64::from(observed); out[17] = u64::from(unsafe { u32::from_le(core::ptr::read_volatile((used + 4) as *const u32)) }); out[18] = u64::from(unsafe { u32::from_le(core::ptr::read_volatile((used + 8) as *const u32)) }); out[19] = u64::from(unsafe { core::ptr::read_volatile(status as *const u8) }); let actual_header = unsafe { core::ptr::read_volatile(header as *const virtio_ring::BlockReadHeader) }; if observed == 0 { out[31] = 110; return Err("native-d7-flush-timeout"); } if out[15] != 1 || observed != 1 || out[17] != 0 || out[18] != 1 || out[19] != 0 || u32::from_le(actual_header.type_le) != 4 || actual_header.reserved_le != 0 || actual_header.sector_le != 0 { out[31] = 5; return Err("native-d7-flush-completion-invalid"); } out[0] |= OBSERVED_FLUSH; out[31] = 0; Ok(()) } fn flush_and_release( runtime: &mut OsK660Runtime, tables: &mmu::Tables, boot: &BootData, out: &mut [u64; 32], ) -> Result<(), &'static str> { let base = block_base(boot, tables)?; out[5] = base; out[6] = unsafe { u64::from(read32(base, 0x100)) | u64::from(read32(base, 0x104)) << 32 }; out[9] = u64::from(unsafe { read32(base, 0x70) }); out[10] = u64::from(unsafe { read32(base, 0x44) }); out[0] |= OBSERVED_BLOCK; if out[9] != 0 || out[10] != 0 || out[6] == 0 { return Err("native-d7-block-owner-not-closed"); } let frequency: u64; unsafe { asm!("mrs {value}, CNTFRQ_EL0", value = out(reg) frequency, options(nomem, nostack, preserves_flags)); } if frequency == 0 { return Err("native-d7-counter-frequency-zero"); } let allocator = &mut runtime .memory_mut() .map_err(|_| "native-d7-memory-owner")? .allocator; out[2] = allocator.remaining_pages(); let mut lease = virtio_ring::DmaLease::allocate(allocator, boot.hardware.ram_base, boot.hardware.ram_size) .map_err(|_| "native-d7-dma-allocate")?; out[3] = allocator.remaining_pages(); out[0] |= OBSERVED_LEASE; if lease .frames() .map_err(|_| "native-d7-dma-frames")? .into_iter() .any(|frame| !tables.normal_shareable_identity(frame)) { // No queue was exposed and no frame was dereferenced. In particular, // do not attempt to scrub an address that failed the mapping check. lease .release(allocator) .map_err(|_| "native-d7-unused-dma-release")?; out[4] = allocator.remaining_pages(); return Err("native-d7-dma-not-normal-identity"); } let result = flush_queue(base, &mut lease, boot, frequency, out); // A timeout or EIO is not clean shutdown. Even those paths must first // prove reset before scrubbing or releasing a possibly live DMA frame. unsafe { write32(base, 0x70, 0); asm!("dsb osh", options(nostack, preserves_flags)); out[23] = u64::from(read32(base, 0x70)); out[24] = u64::from(read32(base, 0x44)); } if out[23] != 0 || out[24] != 0 { // Deliberately retain allocated frames. Reuse while a device may // still DMA would hide both a leak and a memory safety failure. return Err("native-d7-reset-failed-dma-retained"); } lease.mark_reset().map_err(|_| "native-d7-dma-mark-reset")?; for frame in lease.frames().map_err(|_| "native-d7-dma-frames")? { unsafe { core::ptr::write_bytes(frame as *mut u8, 0, 4096) }; } unsafe { asm!("dsb oshst", options(nostack, preserves_flags)) }; lease .release(allocator) .map_err(|_| "native-d7-dma-release")?; out[4] = allocator.remaining_pages(); out[0] |= OBSERVED_RESET; if out[3].checked_add(4) != Some(out[2]) || out[4] != out[2] { return Err("native-d7-dma-accounting-mismatch"); } result?; out[0] |= OBSERVED_RECONCILED; Ok(()) } pub(super) fn run( runtime: &mut super::super::OsK660Runtime, tables: &super::super::mmu::Tables, boot: &super::super::BootData, out: &mut [u64; 32], ) -> Result<(), &'static str> { *out = [UNKNOWN; 32]; out[0] = 0; let daif: u64; let mpidr: u64; unsafe { asm!("mrs {v}, DAIF", v = out(reg) daif, options(nomem, nostack, preserves_flags)); asm!("mrs {v}, MPIDR_EL1", v = out(reg) mpidr, options(nomem, nostack, preserves_flags)); } out[30] = daif; out[2] = runtime .memory() .ok_or("native-d7-memory-owner-missing")? .allocator .remaining_pages(); out[0] |= OBSERVED_RUNTIME; if daif & 0x80 == 0 || mpidr & psci_call::AFFINITY_MASK != 0 { return Err("native-d7-requires-masked-boot-cpu"); } // No MMIO writes, new DMA allocations or firmware calls precede this // check. Missing D3/D4/D5/D6 state remains an error, never a default zero. require_closed_owners()?; out[0] |= OBSERVED_LIFECYCLE; out[1] = super::boot_id()?; if out[1] == 0 { return Err("native-d7-boot-id-zero"); } if boot.dtb_address == 0 || boot.dtb_size == 0 || boot.dtb_size > platform::MAX_BLOB { return Err("native-d7-dtb-missing-or-unbounded"); } let blob = unsafe { core::slice::from_raw_parts(boot.dtb_address as *const u8, boot.dtb_size) }; // The serialized final boot-CPU path owns this existing BSS workspace. // Reusing it avoids placing a 22 KiB FDT workspace on a 16 KiB stack. let scratch = unsafe { &mut *core::ptr::addr_of_mut!(OS_K700_WORKSPACE) }; let conduit = psci_call::discover_conduit(blob, scratch).map_err(|_| "native-d7-psci-dtb")?; out[25] = conduit as u64; out[26] = psci(conduit, PSCI_VERSION, 0); out[27] = psci(conduit, PSCI_FEATURES, SYSTEM_OFF); out[28] = SYSTEM_OFF; if (out[26] as u32 as i32) < 0 || (out[26] as u32) < 2 || (out[27] as u32 as i32) < 0 { return Err("native-d7-psci-system-off-unsupported"); } out[0] |= OBSERVED_PSCI; flush_and_release(runtime, tables, boot, out)?; require_closed_owners()?; // This publishes only SHUTDOWN_READY. The host verifier must capture it // and explicitly release the gate; it is not a guest-off acceptance bit. super::checkpoint_shutdown(out)?; if super::boot_id()? != out[1] || runtime .memory() .ok_or("native-d7-memory-owner-missing")? .allocator .remaining_pages() != out[4] { return Err("native-d7-state-changed-at-shutdown-gate"); } require_closed_owners()?; unsafe { asm!("dsb sy", options(nostack, preserves_flags)) }; out[29] = psci(conduit, SYSTEM_OFF, 0); out[0] |= OBSERVED_OFF_RETURN; // A successful PSCI SYSTEM_OFF never returns. Host quit, host process exit // or reaching this line cannot be converted into a clean guest receipt. Err("native-d7-psci-system-off-returned") }