diff --git a/Documentation/ABI/testing/sysfs-driver-apple-sep b/Documentation/ABI/testing/sysfs-driver-apple-sep index bf43678393338..530dd62d2763e 100644 --- a/Documentation/ABI/testing/sysfs-driver-apple-sep +++ b/Documentation/ABI/testing/sysfs-driver-apple-sep @@ -544,6 +544,35 @@ Description: lowercase hex digits once pnon reads "read", and "unavailable" before then. +What: /sys/bus/platform/devices/.sep/diag/xars +Date: November 2026 +KernelVersion: 7.3 +Contact: Ryan Murray +Description: + (RO) The enclave's xART control service (endpoint xars). + The driver sends nothing on xars at boot, idle or system + sleep, and registers its out-of-line buffers lazily. On an + orderly reboot, halt or power-off, a blocking reboot notifier + sends the storage-volume unmount notification followed by a + non-forced cached-state flush while xarm continues servicing + enclave-initiated writes, then closes the host xART store. + + ======== ============================================= + pending Bring-up has not ended yet. + ready The endpoint is offered with its known layout + and the xART store is writable; the shutdown + barrier is armed. + readonly The endpoint is offered, but the xART store + is read-only (for example, during initrd + keystore_only attach); the barrier will not + run until writes are enabled. + absent The endpoint was not offered or advertised an + unknown layout; left alone. + flushed The shutdown barrier completed cleanly. + failed The shutdown barrier failed or ended + indeterminate; the kernel log says why. + ======== ============================================= + What: /sys/bus/platform/devices/.sep/diag/sse What: /sys/bus/platform/devices/.sep/diag/hibe What: /sys/bus/platform/devices/.sep/diag/skdl diff --git a/drivers/soc/apple/diag.rs b/drivers/soc/apple/diag.rs index fe14587204ac9..6e7276ef6cc13 100644 --- a/drivers/soc/apple/diag.rs +++ b/drivers/soc/apple/diag.rs @@ -69,6 +69,7 @@ extern "C" { fn sep_diag_set_hwrng(registered: bool); fn sep_diag_set_stac(state: c_int); fn sep_diag_set_pnon(state: c_int, digest: *const u8, len: usize); + fn sep_diag_set_xars(state: c_int); fn sep_diag_set_offer(endpoint: u8, state: c_int); fn sep_diag_sse_event() -> c_uint; fn sep_diag_xarm_failed() -> c_uint; @@ -423,6 +424,27 @@ pub(crate) fn pnon(state: Pnon, digest: Option<&[u8; crate::pnon::DIGEST_LEN]>) unsafe { sep_diag_set_pnon(state as c_int, ptr, len) }; } +/// The xART control endpoint (`xars`), as `SEP_DIAG_XARS_*` in `shim.h` spells it. +#[derive(Clone, Copy)] +pub(crate) enum Xars { + /// Endpoint offered with known layout and xART writable; shutdown barrier armed. + Ready = 1, + /// Endpoint offered with known layout, but xART is read-only. + ReadOnly = 2, + /// Endpoint absent or advertises an unknown layout. + Absent = 3, + /// Shutdown unmount and non-forced flush barrier completed. + Flushed = 4, + /// Shutdown barrier failed or ended indeterminate. + Failed = 5, +} + +/// Reports the `xars` endpoint / shutdown-barrier state. +pub(crate) fn xars(state: Xars) { + // SAFETY: no preconditions; updates one word. + unsafe { sep_diag_set_xars(state as c_int) }; +} + /// An endpoint the driver checks at bring-up and sends nothing to, as /// `SEP_DIAG_OFFER_*` in `shim.h` spells the reported states. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/drivers/soc/apple/diag_shim.c b/drivers/soc/apple/diag_shim.c index 1f905fd2f5c65..4a6493ebff98c 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -113,6 +113,7 @@ static struct { atomic_t stac; atomic_t stac_onlines; atomic_t pnon; + atomic_t xars; atomic_t sse; atomic_t sse_events; atomic_t hibe; @@ -670,6 +671,35 @@ static ssize_t local_policy_digest_show(struct device *dev, } static DEVICE_ATTR_ADMIN_RO(local_policy_digest); +static ssize_t xars_show(struct device *dev, struct device_attribute *attr, + char *buf) +{ + const char *state; + + switch (atomic_read(&sep_diag.xars)) { + case SEP_DIAG_XARS_READY: + state = "ready"; + break; + case SEP_DIAG_XARS_READONLY: + state = "readonly"; + break; + case SEP_DIAG_XARS_ABSENT: + state = "absent"; + break; + case SEP_DIAG_XARS_FLUSHED: + state = "flushed"; + break; + case SEP_DIAG_XARS_FAILED: + state = "failed"; + break; + default: + state = "pending"; + break; + } + return sysfs_emit(buf, "%s\n", state); +} +static DEVICE_ATTR_RO(xars); + static ssize_t sep_diag_offer_emit(char *buf, atomic_t *state) { switch (atomic_read(state)) { @@ -803,6 +833,7 @@ static struct attribute *sep_diag_attrs[] = { &dev_attr_stac_onlines.attr, &dev_attr_pnon.attr, &dev_attr_local_policy_digest.attr, + &dev_attr_xars.attr, &dev_attr_sse.attr, &dev_attr_sse_events.attr, &dev_attr_hibe.attr, @@ -916,6 +947,11 @@ void sep_diag_set_pnon(int state, const u8 *digest, size_t len) atomic_set(&sep_diag.pnon, state); } +void sep_diag_set_xars(int state) +{ + atomic_set(&sep_diag.xars, state); +} + unsigned int sep_diag_xarm_failed(void) { return (unsigned int)atomic_inc_return(&sep_diag.xarm_failures); diff --git a/drivers/soc/apple/pm.rs b/drivers/soc/apple/pm.rs index d479bf866ae4c..f46ba91e0a46f 100644 --- a/drivers/soc/apple/pm.rs +++ b/drivers/soc/apple/pm.rs @@ -33,6 +33,7 @@ extern "C" { sleep: unsafe extern "C" fn() -> c_int, wake: unsafe extern "C" fn(), told: unsafe extern "C" fn() -> bool, + shutdown: unsafe extern "C" fn(), ) -> c_int; fn sep_pm_unregister(); fn sep_pm_keep_domains(dev: *mut c_void) -> c_int; @@ -278,6 +279,12 @@ unsafe extern "C" fn pm_told() -> bool { with_sep(false, |sep| sep.sleep_gate() == SleepGate::Told) } +/// # Safety +/// Called by `pm_shim.c` from the blocking reboot notifier chain, in process context. +unsafe extern "C" fn pm_shutdown() { + with_sep((), |sep| sep.xars_shutdown_barrier()); +} + pub(crate) fn register(sep: Arc) -> Result<()> { let dev: *mut c_void = sep.dev.as_raw().cast(); let ptr = sep.into_foreign(); @@ -296,9 +303,9 @@ pub(crate) fn register(sep: Arc) -> Result<()> { return Err(EBUSY); } - // SAFETY: the shim stores the callback and registers a notifier block - // that lives for the module's lifetime. - let rc = unsafe { sep_pm_register(dev, pm_event, pm_sleep, pm_wake, pm_told) }; + // SAFETY: the shim stores the callbacks and registers notifier blocks + // that live for the module's lifetime. + let rc = unsafe { sep_pm_register(dev, pm_event, pm_sleep, pm_wake, pm_told, pm_shutdown) }; if rc != 0 { let raw = SEP.swap(core::ptr::null_mut(), Ordering::AcqRel); if !raw.is_null() { diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index a7d965603a5ae..75826905ea3c1 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -58,6 +59,7 @@ static void (*sep_pm_event)(bool entering); static int (*sep_pm_sleep)(void); static void (*sep_pm_wake)(void); static bool (*sep_pm_told)(void); +static void (*sep_pm_shutdown)(void); /* In the device's .suspend, the only caller that can leave the request to the sleep. */ static bool sep_pm_suspending; @@ -91,6 +93,29 @@ static struct notifier_block sep_pm_nb = { .notifier_call = sep_pm_notify, }; +static int sep_reboot_notify(struct notifier_block *nb, unsigned long action, + void *data) +{ + void (*shutdown)(void) = READ_ONCE(sep_pm_shutdown); + + if (!shutdown) + return NOTIFY_DONE; + + switch (action) { + case SYS_RESTART: + case SYS_HALT: + case SYS_POWER_OFF: + shutdown(); + return NOTIFY_OK; + default: + return NOTIFY_DONE; + } +} + +static struct notifier_block sep_reboot_nb = { + .notifier_call = sep_reboot_notify, +}; + /* The enclave's own domain is the first one its node lists. */ static int sep_pm_domain(struct device *dev, struct regmap **regmap, u32 *offset) { @@ -520,7 +545,8 @@ const struct dev_pm_ops sep_pm_ops = { }; int sep_pm_register(void *ptr, void (*event)(bool entering), int (*sleep)(void), - void (*wake)(void), bool (*told)(void)) + void (*wake)(void), bool (*told)(void), + void (*shutdown)(void)) { int ret; @@ -528,26 +554,38 @@ int sep_pm_register(void *ptr, void (*event)(bool entering), int (*sleep)(void), WRITE_ONCE(sep_pm_sleep, sleep); WRITE_ONCE(sep_pm_wake, wake); WRITE_ONCE(sep_pm_told, told); + WRITE_ONCE(sep_pm_shutdown, shutdown); ret = register_pm_notifier(&sep_pm_nb); + if (ret) + goto err_clear; + + ret = register_reboot_notifier(&sep_reboot_nb); if (ret) { - WRITE_ONCE(sep_pm_event, NULL); - WRITE_ONCE(sep_pm_sleep, NULL); - WRITE_ONCE(sep_pm_wake, NULL); - WRITE_ONCE(sep_pm_told, NULL); - return ret; + unregister_pm_notifier(&sep_pm_nb); + goto err_clear; } return 0; + +err_clear: + WRITE_ONCE(sep_pm_event, NULL); + WRITE_ONCE(sep_pm_sleep, NULL); + WRITE_ONCE(sep_pm_wake, NULL); + WRITE_ONCE(sep_pm_told, NULL); + WRITE_ONCE(sep_pm_shutdown, NULL); + return ret; } /* Returns only once no notifier call is still running. */ void sep_pm_unregister(void) { + unregister_reboot_notifier(&sep_reboot_nb); unregister_pm_notifier(&sep_pm_nb); WRITE_ONCE(sep_pm_event, NULL); WRITE_ONCE(sep_pm_sleep, NULL); WRITE_ONCE(sep_pm_wake, NULL); WRITE_ONCE(sep_pm_told, NULL); + WRITE_ONCE(sep_pm_shutdown, NULL); } static void sep_pm_release_domains(void *data) diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index d3f47288e18c9..c4672583b36f4 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -53,6 +53,7 @@ mod transfer; mod trusted; mod userbag; mod xarm; +mod xars; mod xart_apfs; mod xart_guard; mod xart_store; @@ -937,6 +938,21 @@ struct SepData { #[pin] pnon_owner: Mutex>, + // The xART control endpoint (see `xars`): lazily registered buffers, + // shutdown barrier state, single in-flight exchange and discovery facts. + #[pin] + ool_xars: Mutex>, + #[pin] + xars_barrier_lock: Mutex, + xars_barrier_state: Atomic, + #[pin] + xars_rx: Mutex, + #[pin] + xars_wq: CondVar, + xars_named: Atomic, + xars_layout: Atomic, + xars_shutdown_writes: Atomic, + // What discovery said about the endpoints the driver checks and sends // nothing to (see `sse`, `hibe`, `skdl`). sse_named: Atomic, @@ -1191,6 +1207,12 @@ impl SepData { )?; // Sized from the endpoint's layout before it is registered. let ool_pnon = Self::alloc_ool(dev, pnon::EP_PNON, pnon::OOL_SIZE_PNON, (0, 0))?; + let ool_xars = Self::alloc_ool( + dev, + xars::EP_XARS, + xars::OOL_SIZE_XARS, + (xars::OOL_SIZE_XARS, xars::OOL_SIZE_XARS), + )?; let dma_ring = dma::Coherent::::zeroed_slice(dev, DMA_RING_SIZE, GFP_KERNEL)?; let keystore_only = attach::requested(); @@ -1374,6 +1396,14 @@ impl SepData { pnon_txn: Atomic::new(false), pnon_signed: Atomic::new(false), pnon_owner <- new_mutex!(None), + ool_xars <- new_mutex!(Some(ool_xars)), + xars_barrier_lock <- new_mutex!(xars::BarrierState::Idle), + xars_barrier_state: Atomic::new(xars::BarrierState::Idle as u32), + xars_rx <- new_mutex!(xars::Exchange::new()), + xars_wq <- new_condvar!("SepData::xars_wq"), + xars_named: Atomic::new(false), + xars_layout: Atomic::new(0), + xars_shutdown_writes: Atomic::new(0), sse_named: Atomic::new(false), sse_layout: Atomic::new(0), hibe_named: Atomic::new(false), @@ -2391,6 +2421,13 @@ impl SepData { } fn register_ool(&self, slot: &Mutex>) -> Result<()> { + self.register_ool_by(slot, None) + } + + /// As [`Self::register_ool`]. With `deadline_ms` (boot time) each control + /// request is sent only while its whole reply timeout still ends by the + /// deadline, so the caller's budget bounds the registration. + fn register_ool_by(&self, slot: &Mutex>, deadline_ms: Option) -> Result<()> { let guard = slot.lock(); if guard.as_ref().is_some_and(|b| b.registered) { return Ok(()); @@ -2415,10 +2452,17 @@ impl SepData { // drop the buffer lock before blocking control requests; the drain path takes it drop(guard); - self.control_request_required(&proto::op_ool_inbound_size(endpoint, declared_in as u32))?; - self.control_request_required(&proto::op_ool_inbound_addr(endpoint, in_iova))?; - self.control_request_required(&proto::op_ool_outbound_size(endpoint, declared_out as u32))?; - self.control_request_required(&proto::op_ool_outbound_addr(endpoint, out_iova))?; + for op in [ + proto::op_ool_inbound_size(endpoint, declared_in as u32), + proto::op_ool_inbound_addr(endpoint, in_iova), + proto::op_ool_outbound_size(endpoint, declared_out as u32), + proto::op_ool_outbound_addr(endpoint, out_iova), + ] { + if deadline_ms.is_some_and(|d| boottime_ms().saturating_add(u64::from(op.timeout_ms())) > d) { + return Err(ETIMEDOUT); + } + self.control_request_required(&op)?; + } { // deref first, or the guard's inherent as_mut wins over Option::as_mut @@ -2574,6 +2618,13 @@ impl SepData { ); } + if done.reply.status == xarm::STATUS_OK + && xarm::is_write(req.opcode) + && self.xars_is_closing() + { + self.xars_shutdown_writes.fetch_add(1, Relaxed); + } + if done.reply_bytes > 0 { if self .ool_write(&self.ool_xarm, 0, &staging[..done.reply_bytes]) @@ -3348,6 +3399,8 @@ impl SepData { Self::queue_stac_online(this.clone()); // The enclave's account of the LocalPolicy that admitted this boot. Self::queue_pnon_digest(this.clone()); + // Record xars availability; OOL is registered lazily at shutdown. + this.xars_attach(); Self::arm_settle(this); } @@ -3411,9 +3464,11 @@ impl SepData { module_parameters::xart_start_sector.value(), ) .ok(); + drop(store); // diag/xart must not keep reading "enabled" (keystore_only=2 // without a guard opened the store writable at probe). diag::xart_state(false, None); + self.xars_attach(); return Err(e); } }; @@ -3424,6 +3479,7 @@ impl SepData { *self.host_store.lock() = Some(host); *self.bio_index.lock() = index; diag::xart_state(writable, guard); + self.xars_attach(); self.keystore_only.store(false, Relaxed); *cached = None; drop(cached); @@ -3504,6 +3560,8 @@ impl SepData { xarm::EP_XARM => self.on_xarm(msg), + xars::EP_XARS => self.on_xars(msg), + proto::EP_SBIO => self.on_sbio(msg), proto::EP_SKS => self.on_sks(msg), @@ -3572,6 +3630,7 @@ impl SepData { self.stac_discovered(&f); self.hdcp_discovered(&f); self.pnon_discovered(&f); + self.xars_discovered(&f); self.sse_discovered(&f); self.hibe_discovered(&f); self.skdl_discovered(&f); @@ -3624,6 +3683,7 @@ impl SepData { self.sbio_wq.notify_all(); self.sks_wq.notify_all(); self.scrd_wq.notify_all(); + self.xars_wq.notify_all(); self.hdcp_wq.notify_all(); pm::unregister(); // Release any capture start still held for a resume that will not be @@ -3647,6 +3707,7 @@ impl SepData { self.scrd_wq.notify_all(); self.stac_wq.notify_all(); self.pnon_wq.notify_all(); + self.xars_wq.notify_all(); if let Some(mut handle) = self.rng.lock().take() { handle.unregister(); } @@ -3679,6 +3740,7 @@ impl SepData { for slot in [ &self.ool_xarm, + &self.ool_xars, &self.ool_sbio, &self.ool_sks, &self.ool_scrd, diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 56ff25a7c5e0c..e5f65d8d6328c 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -27,7 +27,8 @@ void sep_cancel_delayed_work_sync(void *work); /* -- pm_shim.c ---------------------------------------------------------- */ int sep_pm_register(void *dev, void (*event)(bool entering), int (*sleep)(void), - void (*wake)(void), bool (*told)(void)); + void (*wake)(void), bool (*told)(void), + void (*shutdown)(void)); void sep_pm_unregister(void); int sep_pm_keep_domains(void *dev); int sep_pm_wait_gated(void *dev, unsigned int timeout_ms); @@ -210,6 +211,14 @@ int sep_sensor_irq_wait(unsigned int timeout_ms); #define SEP_DIAG_PNON_FAILED 3 #define SEP_DIAG_PNON_DIGEST_LEN 48 +/* Mirrored by diag.rs (Xars). */ +#define SEP_DIAG_XARS_PENDING 0 +#define SEP_DIAG_XARS_READY 1 +#define SEP_DIAG_XARS_READONLY 2 +#define SEP_DIAG_XARS_ABSENT 3 +#define SEP_DIAG_XARS_FLUSHED 4 +#define SEP_DIAG_XARS_FAILED 5 + /* * Mirrored by diag.rs (Trusted). The word keeps the state in its low byte and, * for SEP_DIAG_TRUSTED_REFUSED, the enclave's status in the next one. @@ -258,6 +267,7 @@ void sep_diag_set_os_identity(int source); void sep_diag_set_hwrng(bool registered); void sep_diag_set_stac(int state); void sep_diag_set_pnon(int state, const u8 *digest, size_t len); +void sep_diag_set_xars(int state); void sep_diag_set_offer(u8 endpoint, int state); unsigned int sep_diag_sse_event(void); unsigned int sep_diag_xarm_failed(void); diff --git a/drivers/soc/apple/xars.rs b/drivers/soc/apple/xars.rs new file mode 100644 index 0000000000000..81f5db50e1217 --- /dev/null +++ b/drivers/soc/apple/xars.rs @@ -0,0 +1,1123 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +// Copyright 2026 Ryan Murray + +//! The enclave's xART control endpoint (`xars`). +//! +//! `xarm` (endpoint `0x13`) is the enclave-initiated callback channel through +//! which the SEP asks the host to read, write and delete opaque anti-replay +//! records in the shared gigalocker. `xars` (endpoint `0x10`) is the opposite, +//! host-initiated control channel for the same xART service. +//! +//! On macOS 27, `xars` is silent during boot, idle, display sleep and ordinary +//! system sleep; its out-of-line buffers (two 16 KiB pages each way) are +//! registered lazily on first use. During an orderly shutdown, halt or reboot +//! — before filesystems unmount and before the later control-endpoint shutdown +//! handshake — macOS sends two serialized lifecycle requests while `xarm` and +//! the host store remain live: +//! +//! ```text +//! TX 0x0000_0000_000d_0610 endpoint 0x10, tag, op 0x0d (notify storage unmount), 0 OOL bytes +//! (enclave disables clients via silent xarm 0x1d..=0x1f notifications and drains dirty +//! root/session records through xarm writes, which the host fsyncs and acknowledges) +//! RX 0x0000_0000_0000_0610 endpoint 0x10, same tag, status 0, 0 OOL bytes, args [0, 0, 0] +//! +//! TX 0x0000_0000_010c_0610 endpoint 0x10, tag, op 0x0c (flush cached state), 1 OOL byte [0x00] +//! (any final enclave-initiated xarm writes are serviced and fsynced before the reply) +//! RX 0x0000_0000_0000_0610 endpoint 0x10, same tag, status 0, 0 OOL bytes, args [0, 0, 0] +//! ``` +//! +//! Only after both operations succeed does the host close its xART store. +//! +//! Linux implements this exact shutdown barrier from a blocking reboot +//! notifier (`SYS_RESTART`, `SYS_HALT`, `SYS_POWER_OFF`), before +//! `device_shutdown()`, while the mailbox, DART and NVMe gigalocker handle are +//! still live. Nothing is sent on suspend, hibernation, panic or emergency +//! restart, and nothing is sent when `xars` is absent, advertises an unknown +//! buffer layout, or the xART store is read-only. +//! +//! The command set is intentionally closed to [`ShutdownOp`]: there is no raw +//! selector, no userspace interface, no forced flush, and no destructive +//! operation (such as session-seed erasure, which macOS sends only when +//! deleting an APFS volume group). Any timeout, refusal or malformed reply +//! after a request is submitted is treated as indeterminate: the driver never +//! retries blindly, never sends flush after an indeterminate unmount, keeps +//! `xarm` servicing alive until ordinary teardown, logs the failure and allows +//! shutdown to proceed within a bounded budget. The budget starts when the +//! reboot notifier enters the barrier and bounds every later wait: the store +//! lock for the precondition check, OOL registration, both replies and the +//! final store close. If an `xarm` callback still holds the store (syncing a +//! write) at the deadline, the store is left open and serviced. + +use super::*; +use crate::proto::*; +use kernel::prelude::*; +use kernel::soc::apple::mailbox::Message; + +pub(crate) const EP_XARS: u8 = 0x10; + +/// The name in the endpoint's discovery descriptor (upper half of `msg0`). +pub(crate) const XARS_NAME: u32 = u32::from_be_bytes(*b"xars"); + +/// The buffer layout the endpoint advertises in its discovery configuration +/// word: two 16 KiB enclave pages each way. The driver talks to the endpoint +/// only when it advertises this layout. +pub(crate) const XARS_LAYOUT: u32 = 0x0202_0202; + +/// Each out-of-line buffer: two 16 KiB enclave pages, as the layout says. +pub(crate) const OOL_SIZE_XARS: usize = 0x8000; + +/// Lifecycle operations used in the orderly shutdown barrier. +pub(crate) const OP_FLUSH_CACHED_STATE: u8 = 0x0c; +pub(crate) const OP_NOTIFY_STORAGE_UNMOUNT: u8 = 0x0d; + +pub(crate) const STATUS_OK: u8 = 0x00; + +/// First transaction tag handed out by [`Exchange`]; monotonic across requests +/// within a boot so a late reply to a timed-out call cannot match the next. +pub(crate) const FIRST_TAG: u8 = 0x06; +const TAG_MIN: u8 = 0x01; +const TAG_MAX: u8 = 0xfe; + +/// Per-operation reply bound and total reboot-notifier barrier budget. +pub(crate) const OP_TIMEOUT_MS: u32 = 5_000; +pub(crate) const BARRIER_BUDGET_MS: u32 = 10_000; + +/// Poll interval while the store lock is held by an `xarm` callback. +const STORE_POLL_MS: i64 = 5; + +/// Non-forced flush payload: a single Boolean `false`. Forced flush (`true`) is +/// reserved for destructive erase flows and is never transmitted here. +const FLUSH_NON_FORCED: [u8; 1] = [0x00]; + +/// Closed set of host-initiated `xars` operations this driver can transmit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ShutdownOp { + /// Tell the enclave that xART storage is about to unmount. + NotifyStorageUnmount, + /// Ask the enclave to flush any remaining cached state (`force_flush = false`). + FlushCachedState, +} + +impl ShutdownOp { + pub(crate) const fn opcode(self) -> u8 { + match self { + ShutdownOp::NotifyStorageUnmount => OP_NOTIFY_STORAGE_UNMOUNT, + ShutdownOp::FlushCachedState => OP_FLUSH_CACHED_STATE, + } + } + + pub(crate) const fn body(self) -> &'static [u8] { + match self { + ShutdownOp::NotifyStorageUnmount => &[], + ShutdownOp::FlushCachedState => &FLUSH_NON_FORCED, + } + } + + pub(crate) const fn ool_length(self) -> u16 { + self.body().len() as u16 + } + + pub(crate) const fn name(self) -> &'static CStr { + match self { + ShutdownOp::NotifyStorageUnmount => c"notify_storage_unmount", + ShutdownOp::FlushCachedState => c"flush_cached_state", + } + } +} + +/// Encodes one typed `xars` request in the shared 8-byte xART carrier format. +pub(crate) const fn encode_request(tag: u8, op: ShutdownOp) -> Message { + let len = op.ool_length().to_le_bytes(); + Message { + msg0: u64::from_le_bytes([ + EP_XARS, + tag, + op.opcode(), + len[0], + len[1], + 0, + 0, + 0, + ]), + msg1: 0, + } +} + +// Match the mailbox words recorded on a J616s under macOS 27 shutdown. +static_assert!( + encode_request(FIRST_TAG, ShutdownOp::NotifyStorageUnmount).msg0 == 0x0000_0000_000d_0610 +); +static_assert!( + encode_request(FIRST_TAG, ShutdownOp::FlushCachedState).msg0 == 0x0000_0000_010c_0610 +); + +/// Decoded 8-byte `xars` reply word. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Reply { + pub(crate) tag: u8, + pub(crate) status: u8, + pub(crate) length: u16, + pub(crate) args: [u8; 3], +} + +/// Decodes a mailbox message if it belongs to [`EP_XARS`]. +pub(crate) fn decode_reply(msg: &Message) -> Option { + let b = msg.msg0.to_le_bytes(); + if b[0] != EP_XARS { + return None; + } + Some(Reply { + tag: b[1], + status: b[2], + length: u16::from_le_bytes([b[3], b[4]]), + args: [b[5], b[6], b[7]], + }) +} + +/// Result of one `xars` shutdown operation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Outcome { + /// Tag matched, status 0, zero returned length and zero result arguments. + Accepted, + /// Tag matched, enclave returned a nonzero `service_status`. + Refused(u8), + /// Tag matched, but returned length or result arguments were unexpected. + Malformed, + /// Reply carried a different transaction tag (not an answer to this call). + WrongTag, + /// No matching reply arrived within the operation deadline. + NoReply, +} + +/// Validates a decoded reply against `expected_tag` for a zero-body response. +pub(crate) fn check_reply(expected_tag: u8, reply: &Reply) -> Outcome { + if reply.tag != expected_tag { + return Outcome::WrongTag; + } + if reply.status != STATUS_OK { + return Outcome::Refused(reply.status); + } + if reply.length != 0 || reply.args != [0, 0, 0] { + return Outcome::Malformed; + } + Outcome::Accepted +} + +/// Lifecycle state of the `xars` shutdown barrier. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BarrierState { + /// Normal operation; barrier has not run yet. + Idle = 0, + /// Barrier is in progress; new host mutations are refused while `xarm` stays live. + Closing = 1, + /// Unmount and non-forced flush succeeded and the host xART store was closed. + Completed = 2, + /// An operation failed, timed out or returned a malformed reply. + Indeterminate = 3, + /// Endpoint absent/unknown layout, attach incomplete, or xART read-only. + Unavailable = 4, +} + +impl BarrierState { + pub(crate) const fn from_u32(v: u32) -> BarrierState { + match v { + 0 => BarrierState::Idle, + 1 => BarrierState::Closing, + 2 => BarrierState::Completed, + 3 => BarrierState::Indeterminate, + _ => BarrierState::Unavailable, + } + } +} + +/// Serialised single-in-flight transaction tracker for `xars`. +pub(crate) struct Exchange { + waiting: bool, + tag: u8, + next_tag: u8, + generation: u64, + outcome: Option, +} + +impl Exchange { + pub(crate) const fn new() -> Exchange { + Exchange { + waiting: false, + tag: 0, + next_tag: FIRST_TAG, + generation: 0, + outcome: None, + } + } + + fn alloc_tag(&mut self) -> u8 { + let tag = self.next_tag; + self.next_tag = if tag >= TAG_MAX { TAG_MIN } else { tag + 1 }; + tag + } + + /// Starts a new exchange with a fresh non-zero transaction tag. + pub(crate) fn begin(&mut self) -> (u64, u8) { + let tag = self.alloc_tag(); + self.generation = self.generation.wrapping_add(1); + self.waiting = true; + self.tag = tag; + self.outcome = None; + (self.generation, tag) + } + + /// Returns `(generation, tag)` if an exchange is waiting for its reply. + #[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] + #[allow(dead_code)] + pub(crate) fn current(&self) -> Option<(u64, u8)> { + if self.waiting { + Some((self.generation, self.tag)) + } else { + None + } + } + + /// Delivers a reply to the active exchange. Returns `true` if the reply + /// matched the waiting generation and tag. + pub(crate) fn deliver(&mut self, reply: &Reply) -> bool { + if !self.waiting || self.outcome.is_some() { + return false; + } + let outcome = check_reply(self.tag, reply); + if outcome == Outcome::WrongTag { + return false; + } + self.outcome = Some(outcome); + true + } + + pub(crate) fn take(&mut self) -> Option { + let outcome = self.outcome.take(); + if outcome.is_some() { + self.waiting = false; + } + outcome + } + + pub(crate) fn end(&mut self) { + self.waiting = false; + self.outcome = None; + } +} + +/// Pure transport boundary for [`execute_barrier`], allowing KUnit tests to +/// exercise every shutdown-barrier transition and fault path without hardware. +/// +/// `deadline_ms` is the barrier's absolute deadline on the `now_ms` clock: a +/// method given it must return by then (bar one poll interval). +pub(crate) trait BarrierTransport { + fn now_ms(&self) -> u64; + fn preconditions_met(&self, deadline_ms: u64) -> bool; + fn begin_closing(&mut self); + fn register_ool(&mut self, deadline_ms: u64) -> Result<()>; + fn transact(&mut self, op: ShutdownOp, timeout_ms: u32) -> Result; + /// Detaches the host xART store; `false` (store left open) if it could not + /// be taken by the deadline. + fn close_store(&mut self, deadline_ms: u64) -> bool; +} + +/// Final disposition returned by [`execute_barrier`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BarrierResult { + /// Already ran earlier in this boot; nothing sent. + AlreadyRan(BarrierState), + /// Preconditions not met; nothing sent. + Unavailable, + /// Unmount + non-forced flush succeeded and the host store was closed. + Completed, + /// OOL registration failed before any `xars` request was submitted. + OolFailed, + /// A submitted `xars` request did not succeed cleanly; store left open. + Indeterminate { + op: ShutdownOp, + outcome: Outcome, + }, + /// Submitting a `xars` request failed at the transport layer; store left open. + SendFailed { + op: ShutdownOp, + }, + /// Total barrier budget expired before a request could be sent; store left open. + BudgetExhausted, + /// Both operations succeeded, but an `xarm` callback still held the store + /// at the deadline; store left open. + CloseTimedOut, +} + +/// Runs the orderly shutdown barrier once: `Idle -> Closing -> Completed`, or +/// `Unavailable` / `Indeterminate` on precondition or protocol failure. +/// +/// Guarantees: +/// - Runs at most once per boot (`state != Idle` is a no-op). +/// - Never sends `FlushCachedState` unless `NotifyStorageUnmount` returned +/// [`Outcome::Accepted`]. +/// - Never retries an indeterminate operation. +/// - Closes the host xART store only after both operations succeed. +/// - Every wait ends by `start_ms + BARRIER_BUDGET_MS`, where `start_ms` is +/// when the reboot notifier entered the barrier; `begin_closing` is bounded +/// by its own drain limits, below the budget. +pub(crate) fn execute_barrier( + state: &mut BarrierState, + transport: &mut impl BarrierTransport, + start_ms: u64, +) -> BarrierResult { + if *state != BarrierState::Idle { + return BarrierResult::AlreadyRan(*state); + } + let deadline = start_ms.saturating_add(u64::from(BARRIER_BUDGET_MS)); + if !transport.preconditions_met(deadline) { + *state = BarrierState::Unavailable; + return BarrierResult::Unavailable; + } + + *state = BarrierState::Closing; + transport.begin_closing(); + + if transport.now_ms() >= deadline { + *state = BarrierState::Indeterminate; + return BarrierResult::BudgetExhausted; + } + if transport.register_ool(deadline).is_err() { + *state = BarrierState::Indeterminate; + return BarrierResult::OolFailed; + } + + let unmount_timeout = remaining_op_ms(transport.now_ms(), deadline); + if unmount_timeout == 0 { + *state = BarrierState::Indeterminate; + return BarrierResult::BudgetExhausted; + } + match transport.transact(ShutdownOp::NotifyStorageUnmount, unmount_timeout) { + Ok(Outcome::Accepted) => {} + Ok(outcome) => { + *state = BarrierState::Indeterminate; + return BarrierResult::Indeterminate { + op: ShutdownOp::NotifyStorageUnmount, + outcome, + }; + } + Err(_) => { + *state = BarrierState::Indeterminate; + return BarrierResult::SendFailed { + op: ShutdownOp::NotifyStorageUnmount, + }; + } + } + + let flush_timeout = remaining_op_ms(transport.now_ms(), deadline); + if flush_timeout == 0 { + *state = BarrierState::Indeterminate; + return BarrierResult::BudgetExhausted; + } + match transport.transact(ShutdownOp::FlushCachedState, flush_timeout) { + Ok(Outcome::Accepted) => {} + Ok(outcome) => { + *state = BarrierState::Indeterminate; + return BarrierResult::Indeterminate { + op: ShutdownOp::FlushCachedState, + outcome, + }; + } + Err(_) => { + *state = BarrierState::Indeterminate; + return BarrierResult::SendFailed { + op: ShutdownOp::FlushCachedState, + }; + } + } + + if !transport.close_store(deadline) { + *state = BarrierState::Indeterminate; + return BarrierResult::CloseTimedOut; + } + *state = BarrierState::Completed; + BarrierResult::Completed +} + +fn remaining_op_ms(now_ms: u64, deadline_ms: u64) -> u32 { + let left = deadline_ms.saturating_sub(now_ms); + u32::try_from(left.min(u64::from(OP_TIMEOUT_MS))).unwrap_or(OP_TIMEOUT_MS) +} + +struct LiveBarrier<'a>(&'a SepData); + +impl BarrierTransport for LiveBarrier<'_> { + fn now_ms(&self) -> u64 { + boottime_ms() + } + + fn preconditions_met(&self, deadline_ms: u64) -> bool { + !self.0.shutting_down.load(Relaxed) + && self.0.phase.load(Relaxed) == PHASE_READY + && self.0.sleep_gate() == pm::SleepGate::Open + && self.0.xars_offered() + && self + .0 + .xars_with_store_until(deadline_ms, |store| { + store.as_ref().is_some_and(|s| s.writes_enabled()) + }) + .unwrap_or(false) + } + + fn begin_closing(&mut self) { + self.0.xars_barrier_state.store(BarrierState::Closing as u32, Release); + // Stop new entropy draws and Touch ID captures while keeping the + // mailbox and xarm callback path fully active for the enclave's drain. + self.0.rng_sleep_prepare(); + self.0.sleep_prepare(); + } + + fn register_ool(&mut self, deadline_ms: u64) -> Result<()> { + self.0.register_ool_by(&self.0.ool_xars, Some(deadline_ms)) + } + + fn transact(&mut self, op: ShutdownOp, timeout_ms: u32) -> Result { + self.0.xars_transact(op, timeout_ms) + } + + fn close_store(&mut self, deadline_ms: u64) -> bool { + // Acquiring `store` also serialises behind any trailing xarm callback + // in `rx_work`, which fsyncs every accepted write before replying. If + // that has not finished by the deadline, leave the store open so the + // callback (and any later one) can still complete. + self.0 + .xars_with_store_until(deadline_ms, |store| drop(store.take())) + .is_some() + } +} + +impl SepData { + /// Runs `f` on the host xART store slot once its lock is free, waiting no + /// later than `deadline_ms` (boot time). `None` if the lock was still held, + /// e.g. by an `xarm` callback syncing a write. + fn xars_with_store_until( + &self, + deadline_ms: u64, + f: impl FnOnce(&mut Option) -> R, + ) -> Option { + loop { + if let Some(mut guard) = self.store.try_lock() { + return Some(f(&mut *guard)); + } + if boottime_ms() >= deadline_ms { + return None; + } + kernel::time::delay::fsleep(kernel::time::Delta::from_millis(STORE_POLL_MS)); + } + } + + /// Whether the enclave offers `xars` with the 2-page layout the driver knows. + pub(crate) fn xars_offered(&self) -> bool { + self.endpoint_present(EP_XARS) + && self.xars_named.load(Relaxed) + && self.xars_layout.load(Relaxed) == XARS_LAYOUT + } + + /// Records the discovery messages of `xars`. + pub(crate) fn xars_discovered(&self, f: &Fields) { + if f.param != EP_XARS { + return; + } + match f.ty { + DISCOVER_TYPE_DESCRIPTOR => self.xars_named.store(f.data_lo == XARS_NAME, Relaxed), + DISCOVER_TYPE_CONFIG => self.xars_layout.store(f.data_lo, Relaxed), + _ => {} + } + } + + /// Updates passive diagnostics for `xars` once bring-up finishes or after + /// `complete_attach` changes xART writability. Sends nothing and does not + /// register OOL buffers. + pub(crate) fn xars_attach(&self) { + if !self.xars_offered() { + if self.endpoint_present(EP_XARS) { + dev_dbg!( + self.dev, + "xars: the endpoint advertises layout {:#010x}; left alone\n", + self.xars_layout.load(Relaxed) + ); + } + diag::xars(diag::Xars::Absent); + } else if self.xart_writable() { + diag::xars(diag::Xars::Ready); + } else { + diag::xars(diag::Xars::ReadOnly); + } + } + + /// Whether the shutdown barrier is currently closing (used to count + /// shutdown-triggered `xarm` writes). + pub(crate) fn xars_is_closing(&self) -> bool { + BarrierState::from_u32(self.xars_barrier_state.load(Acquire)) == BarrierState::Closing + } + + /// Runs the orderly shutdown/reboot barrier (`notify_storage_unmount` then + /// non-forced `flush_cached_state`, closing the host xART store only after + /// both succeed). Called from the blocking reboot notifier before + /// `device_shutdown()`. + pub(crate) fn xars_shutdown_barrier(&self) { + // The budget starts here, at notifier entry. + let start_ms = boottime_ms(); + let mut state_guard = self.xars_barrier_lock.lock(); + self.xars_shutdown_writes.store(0, Relaxed); + + let mut transport = LiveBarrier(self); + let result = execute_barrier(&mut *state_guard, &mut transport, start_ms); + self.xars_barrier_state.store(*state_guard as u32, Release); + let elapsed_ms = boottime_ms().saturating_sub(start_ms); + let writes = self.xars_shutdown_writes.load(Relaxed); + + match result { + BarrierResult::AlreadyRan(_) => {} + BarrierResult::Unavailable => { + dev_dbg!( + self.dev, + "xars: shutdown barrier unavailable (phase {})\n", + self.phase.load(Relaxed) + ); + } + BarrierResult::Completed => { + diag::xars(diag::Xars::Flushed); + dev_info_ratelimited!( + self.dev, + "xars: shutdown barrier complete (unmount + flush, {} xarm writes in {} ms)\n", + writes, + elapsed_ms + ); + } + BarrierResult::OolFailed => { + diag::xars(diag::Xars::Failed); + dev_warn_ratelimited!( + self.dev, + "xars: shutdown barrier skipped: OOL buffer registration failed ({} ms)\n", + elapsed_ms + ); + } + BarrierResult::Indeterminate { op, outcome } => { + diag::xars(diag::Xars::Failed); + dev_warn_ratelimited!( + self.dev, + "xars: shutdown barrier indeterminate at {} ({:?}, {} xarm writes in {} ms)\n", + op.name(), + outcome, + writes, + elapsed_ms + ); + } + BarrierResult::SendFailed { op } => { + diag::xars(diag::Xars::Failed); + dev_warn_ratelimited!( + self.dev, + "xars: shutdown barrier could not send {} ({} xarm writes in {} ms)\n", + op.name(), + writes, + elapsed_ms + ); + } + BarrierResult::BudgetExhausted => { + diag::xars(diag::Xars::Failed); + dev_warn_ratelimited!( + self.dev, + "xars: shutdown barrier budget exhausted ({} xarm writes in {} ms)\n", + writes, + elapsed_ms + ); + } + BarrierResult::CloseTimedOut => { + diag::xars(diag::Xars::Failed); + dev_warn_ratelimited!( + self.dev, + "xars: shutdown barrier left the store open: an xarm write was still syncing at the deadline ({} xarm writes in {} ms)\n", + writes, + elapsed_ms + ); + } + } + } + + fn xars_transact(&self, op: ShutdownOp, timeout_ms: u32) -> Result { + let (_generation, tag) = self.xars_rx.lock().begin(); + let body = op.body(); + let sent = if !body.is_empty() { + self.ool_write(&self.ool_xars, 0, body) + .and_then(|()| self.send(encode_request(tag, op))) + } else { + self.send(encode_request(tag, op)) + }; + if let Err(e) = sent { + self.xars_rx.lock().end(); + return Err(e); + } + + let mut remaining = time::msecs_to_jiffies(timeout_ms); + let mut guard = self.xars_rx.lock(); + loop { + if self.shutting_down.load(Relaxed) { + guard.end(); + return Err(ENODEV); + } + if let Some(outcome) = guard.take() { + return Ok(outcome); + } + if remaining == 0 { + guard.end(); + return Ok(Outcome::NoReply); + } + // Uninterruptible wait: reboot path must not spin on pending signals. + match self.xars_wq.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => remaining = jiffies, + CondVarTimeoutResult::Signal { .. } => remaining = 0, + CondVarTimeoutResult::Timeout => remaining = 0, + } + } + } + + pub(crate) fn on_xars(&self, msg: Message) { + let Some(reply) = decode_reply(&msg) else { + self.xars_unexpected(&msg); + return; + }; + let delivered = self.xars_rx.lock().deliver(&reply); + if delivered { + self.xars_wq.notify_all(); + } else { + self.xars_unexpected(&msg); + } + } + + fn xars_unexpected(&self, msg: &Message) { + if diag::unhandled() <= UNHANDLED_LOG_LIMIT { + dev_info_ratelimited!( + self.dev, + "xars: unexpected message (msg0 {:#018x})\n", + msg.msg0 + ); + } + } +} + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +#[::kernel::macros::kunit_tests(apple_sep_xars)] +mod tests { + use super::*; + + // Discovery words from our Linux boot logs (M1 Pro, M2, M4 Pro, A18 Pro). + const DISCOVER_NAME: u64 = 0x7861_7273_1000_00fd; + const DISCOVER_LAYOUT: u64 = 0x0202_0202_1001_00fd; + + // Shutdown mailbox words recorded on a J616s under macOS 27.0 + // (unmount notice, then non-forced cached-state flush). + const TRACE_TX_UNMOUNT: u64 = 0x0000_0000_000d_0610; + const TRACE_TX_FLUSH: u64 = 0x0000_0000_010c_0610; + // Reply word recorded on J473 under macOS 27.2 (tag 0x06, status 0, len 0). + const TRACE_RX_OK: u64 = 0x0000_0000_0000_0610; + + #[test] + fn discovery_words_match_expected_name_and_layout() { + let name = decode(&Message { + msg0: DISCOVER_NAME, + msg1: 0, + }); + assert_eq!(name.ep, EP_DISCOVER); + assert_eq!(name.param, EP_XARS); + assert_eq!(name.ty, DISCOVER_TYPE_DESCRIPTOR); + assert_eq!(name.data_lo, XARS_NAME); + + let cfg = decode(&Message { + msg0: DISCOVER_LAYOUT, + msg1: 0, + }); + assert_eq!(cfg.ep, EP_DISCOVER); + assert_eq!(cfg.param, EP_XARS); + assert_eq!(cfg.ty, DISCOVER_TYPE_CONFIG); + assert_eq!(cfg.data_lo, XARS_LAYOUT); + } + + #[test] + fn shutdown_requests_match_the_recordings() { + let unmount = encode_request(FIRST_TAG, ShutdownOp::NotifyStorageUnmount); + assert_eq!(unmount.msg0, TRACE_TX_UNMOUNT); + assert_eq!(unmount.msg1, 0); + assert_eq!(ShutdownOp::NotifyStorageUnmount.body(), &[]); + + let flush = encode_request(FIRST_TAG, ShutdownOp::FlushCachedState); + assert_eq!(flush.msg0, TRACE_TX_FLUSH); + assert_eq!(flush.msg1, 0); + // Non-forced flush only: force_flush byte must always be 0. + assert_eq!(ShutdownOp::FlushCachedState.body(), &[0x00]); + } + + #[test] + fn recorded_reply_validates_and_bad_replies_fail() { + let reply = decode_reply(&Message { + msg0: TRACE_RX_OK, + msg1: 0, + }) + .unwrap(); + assert_eq!(reply.tag, FIRST_TAG); + assert_eq!(reply.status, STATUS_OK); + assert_eq!(reply.length, 0); + assert_eq!(reply.args, [0, 0, 0]); + assert_eq!(check_reply(FIRST_TAG, &reply), Outcome::Accepted); + + // Wrong endpoint is rejected by decode_reply. + assert!(decode_reply(&Message { + msg0: 0x0000_0000_0000_0613, + msg1: 0, + }) + .is_none()); + + // Wrong tag. + assert_eq!(check_reply(FIRST_TAG + 1, &reply), Outcome::WrongTag); + + // Nonzero service status is a refusal. + let refused = Reply { + status: 0x16, + ..reply + }; + assert_eq!(check_reply(FIRST_TAG, &refused), Outcome::Refused(0x16)); + + // Unexpected returned length or result argument is malformed. + let with_len = Reply { length: 1, ..reply }; + assert_eq!(check_reply(FIRST_TAG, &with_len), Outcome::Malformed); + let with_arg = Reply { + args: [1, 0, 0], + ..reply + }; + assert_eq!(check_reply(FIRST_TAG, &with_arg), Outcome::Malformed); + } + + #[test] + fn exchange_allocates_fresh_tags_and_ignores_late_replies() { + let mut ex = Exchange::new(); + assert_eq!(ex.current(), None); + + let (g1, t1) = ex.begin(); + assert_eq!(t1, FIRST_TAG); + assert_eq!(ex.current(), Some((g1, t1))); + + // First call times out; second call gets a fresh tag. + ex.end(); + let (g2, t2) = ex.begin(); + assert_ne!(t2, t1); + assert_ne!(t2, 0); + assert_eq!(ex.current(), Some((g2, t2))); + + // Late reply for t1 must not satisfy t2. + let late = Reply { + tag: t1, + status: STATUS_OK, + length: 0, + args: [0; 3], + }; + assert!(!ex.deliver(&late)); + assert_eq!(ex.take(), None); + + // Matching reply for t2 succeeds; a duplicate is ignored. + let ok = Reply { tag: t2, ..late }; + assert!(ex.deliver(&ok)); + assert!(!ex.deliver(&Reply { status: 2, ..ok })); + assert_eq!(ex.take(), Some(Outcome::Accepted)); + assert_eq!(ex.current(), None); + } + + #[test] + fn tag_pool_wraps_without_zero() { + let mut ex = Exchange::new(); + for _ in 0..300 { + let (_, tag) = ex.begin(); + assert!(tag >= TAG_MIN && tag <= TAG_MAX); + ex.end(); + } + } + + struct MockTransport { + now: u64, + preconditions: bool, + ool_ok: bool, + closing_step_ms: u64, + ool_step_ms: u64, + close_busy_ms: u64, + unmount_step_ms: u64, + flush_step_ms: u64, + unmount_res: Result, + flush_res: Result, + closing_called: bool, + ool_called: bool, + store_closed: bool, + ops: [Option; 4], + op_count: usize, + timeouts: [u32; 4], + } + + impl MockTransport { + fn healthy() -> Self { + MockTransport { + now: 1000, + preconditions: true, + ool_ok: true, + closing_step_ms: 0, + ool_step_ms: 0, + close_busy_ms: 0, + unmount_step_ms: 400, + flush_step_ms: 50, + unmount_res: Ok(Outcome::Accepted), + flush_res: Ok(Outcome::Accepted), + closing_called: false, + ool_called: false, + store_closed: false, + ops: [None; 4], + op_count: 0, + timeouts: [0; 4], + } + } + } + + impl BarrierTransport for MockTransport { + fn now_ms(&self) -> u64 { + self.now + } + + fn preconditions_met(&self, _deadline_ms: u64) -> bool { + self.preconditions + } + + fn begin_closing(&mut self) { + self.closing_called = true; + self.now = self.now.saturating_add(self.closing_step_ms); + } + + fn register_ool(&mut self, deadline_ms: u64) -> Result<()> { + self.ool_called = true; + // Registration that cannot finish by the deadline is not started. + if !self.ool_ok || self.now.saturating_add(self.ool_step_ms) > deadline_ms { + return Err(ETIMEDOUT); + } + self.now = self.now.saturating_add(self.ool_step_ms); + Ok(()) + } + + fn transact(&mut self, op: ShutdownOp, timeout_ms: u32) -> Result { + let idx = self.op_count; + self.ops[idx] = Some(op); + self.timeouts[idx] = timeout_ms; + self.op_count += 1; + match op { + ShutdownOp::NotifyStorageUnmount => { + self.now = self.now.saturating_add(self.unmount_step_ms); + self.unmount_res + } + ShutdownOp::FlushCachedState => { + self.now = self.now.saturating_add(self.flush_step_ms); + self.flush_res + } + } + } + + /// The store lock is held for `close_busy_ms` more by a trailing + /// xarm write that is still being synced. + fn close_store(&mut self, deadline_ms: u64) -> bool { + let free_at = self.now.saturating_add(self.close_busy_ms); + if free_at > deadline_ms { + self.now = self.now.max(deadline_ms); + return false; + } + self.now = free_at; + self.store_closed = true; + true + } + } + + /// Runs the barrier as the reboot notifier does, from its entry time. + fn run(state: &mut BarrierState, t: &mut MockTransport) -> BarrierResult { + let start = t.now; + execute_barrier(state, t, start) + } + + #[test] + fn happy_path_runs_unmount_then_flush_then_closes_store_once() { + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + + assert_eq!(run(&mut state, &mut t), BarrierResult::Completed); + assert_eq!(state, BarrierState::Completed); + assert!(t.closing_called); + assert!(t.ool_called); + assert!(t.store_closed); + assert_eq!(t.op_count, 2); + assert_eq!(t.ops[0], Some(ShutdownOp::NotifyStorageUnmount)); + assert_eq!(t.ops[1], Some(ShutdownOp::FlushCachedState)); + assert_eq!(t.timeouts[0], OP_TIMEOUT_MS); + assert_eq!(t.timeouts[1], OP_TIMEOUT_MS); + + // A second invocation (e.g. from device shutdown) sends nothing. + assert_eq!( + run(&mut state, &mut t), + BarrierResult::AlreadyRan(BarrierState::Completed) + ); + assert_eq!(t.op_count, 2); + } + + #[test] + fn unavailable_preconditions_send_nothing() { + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.preconditions = false; + + assert_eq!( + run(&mut state, &mut t), + BarrierResult::Unavailable + ); + assert_eq!(state, BarrierState::Unavailable); + assert!(!t.closing_called); + assert!(!t.ool_called); + assert!(!t.store_closed); + assert_eq!(t.op_count, 0); + } + + #[test] + fn ool_failure_leaves_store_open_and_sends_no_xars() { + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.ool_ok = false; + + assert_eq!(run(&mut state, &mut t), BarrierResult::OolFailed); + assert_eq!(state, BarrierState::Indeterminate); + assert!(!t.store_closed); + assert_eq!(t.op_count, 0); + } + + #[test] + fn indeterminate_unmount_never_sends_flush_or_closes_store() { + for bad in [Outcome::NoReply, Outcome::Refused(0x16), Outcome::Malformed] { + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.unmount_res = Ok(bad); + + assert_eq!( + run(&mut state, &mut t), + BarrierResult::Indeterminate { + op: ShutdownOp::NotifyStorageUnmount, + outcome: bad, + } + ); + assert_eq!(state, BarrierState::Indeterminate); + assert_eq!(t.op_count, 1); + assert!(!t.store_closed); + } + } + + #[test] + fn indeterminate_flush_leaves_store_open_and_does_not_retry() { + for bad in [Outcome::NoReply, Outcome::Refused(0x02), Outcome::Malformed] { + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.flush_res = Ok(bad); + + assert_eq!( + run(&mut state, &mut t), + BarrierResult::Indeterminate { + op: ShutdownOp::FlushCachedState, + outcome: bad, + } + ); + assert_eq!(state, BarrierState::Indeterminate); + assert_eq!(t.op_count, 2); + assert!(!t.store_closed); + } + } + + #[test] + fn slow_unmount_caps_or_exhausts_flush_budget() { + // 8 s unmount leaves 2 s for flush (below OP_TIMEOUT_MS). + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.unmount_step_ms = 8_000; + assert_eq!(run(&mut state, &mut t), BarrierResult::Completed); + assert_eq!(t.timeouts[1], 2_000); + + // 10 s unmount leaves 0 ms: flush is not sent and store stays open. + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.unmount_step_ms = u64::from(BARRIER_BUDGET_MS); + assert_eq!( + run(&mut state, &mut t), + BarrierResult::BudgetExhausted + ); + assert_eq!(state, BarrierState::Indeterminate); + assert_eq!(t.op_count, 1); + assert!(!t.store_closed); + } + + #[test] + fn budget_starts_at_notifier_entry() { + // Closing and OOL registration spend the budget: 7 s + 2 s leave 1 s + // for the unmount reply. + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.closing_step_ms = 7_000; + t.ool_step_ms = 2_000; + t.unmount_step_ms = 100; + assert_eq!(run(&mut state, &mut t), BarrierResult::Completed); + assert_eq!(t.timeouts[0], 1_000); + assert_eq!(t.timeouts[1], 900); + + // Registration that cannot finish by the deadline is not started. + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + let start = t.now; + t.closing_step_ms = 7_000; + t.ool_step_ms = 4_000; + assert_eq!(run(&mut state, &mut t), BarrierResult::OolFailed); + assert_eq!(state, BarrierState::Indeterminate); + assert_eq!(t.op_count, 0); + assert!(!t.store_closed); + assert!(t.now <= start + u64::from(BARRIER_BUDGET_MS)); + + // Closing that uses the whole budget sends nothing. + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.closing_step_ms = u64::from(BARRIER_BUDGET_MS); + assert_eq!(run(&mut state, &mut t), BarrierResult::BudgetExhausted); + assert_eq!(state, BarrierState::Indeterminate); + assert!(!t.ool_called); + assert_eq!(t.op_count, 0); + assert!(!t.store_closed); + } + + #[test] + fn trailing_xarm_write_past_budget_leaves_store_open() { + // Both replies arrive, but an xarm callback is still syncing a write + // when the budget runs out: return by the deadline, store still open. + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + let start = t.now; + t.close_busy_ms = 60_000; + assert_eq!(run(&mut state, &mut t), BarrierResult::CloseTimedOut); + assert_eq!(state, BarrierState::Indeterminate); + assert_eq!(t.op_count, 2); + assert!(!t.store_closed); + assert!(t.now <= start + u64::from(BARRIER_BUDGET_MS)); + + // A trailing write that finishes within the budget is waited for. + let mut state = BarrierState::Idle; + let mut t = MockTransport::healthy(); + t.close_busy_ms = 3_000; + assert_eq!(run(&mut state, &mut t), BarrierResult::Completed); + assert!(t.store_closed); + + // Nothing runs a second time after the store was left open. + let mut state = BarrierState::Indeterminate; + let mut t = MockTransport::healthy(); + assert_eq!( + run(&mut state, &mut t), + BarrierResult::AlreadyRan(BarrierState::Indeterminate) + ); + assert!(!t.closing_called); + assert_eq!(t.op_count, 0); + } +} diff --git a/tools/aurora-sep/aurora-sep b/tools/aurora-sep/aurora-sep index cd641c42e82ec..cdb1e3238e008 100755 --- a/tools/aurora-sep/aurora-sep +++ b/tools/aurora-sep/aurora-sep @@ -161,6 +161,8 @@ def status(live=True): served["stac"] = "accessory power state" if d("pnon") is not None: served["pnon"] = "LocalPolicy nonce digest" + if d("xars") is not None: + served["xars"] = "xART shutdown barrier" for ep in ("sse", "hibe", "skdl"): if d(ep) is not None: served[ep] = "checked at boot, nothing sent" @@ -274,6 +276,22 @@ def status(live=True): r.add(WARN, "pnon", pnon, "the LocalPolicy nonce digest read has not succeeded " "(the kernel log says why)") + xars = d("xars") + if xars is not None: + if xars in ("ready", "flushed"): + r.add(PASS, "xars", xars, "xART shutdown unmount and flush barrier is armed") + elif xars == "absent": + r.add(INFO, "xars", xars, "this enclave does not offer the xART control endpoint " + "as the driver knows it") + elif xars == "pending": + r.add(INFO, "xars", xars, "the bring-up has not ended yet") + elif xars == "readonly": + r.add(WARN, "xars", xars, "xART store is read-only; shutdown barrier will not run " + "until writes are enabled") + else: + r.add(WARN, "xars", xars, "the xART shutdown barrier failed or ended indeterminate " + "(the kernel log says why)") + for ep, what, reason in ( ("sse", "secure-element sharing", "nothing is sent to it, as macOS at boot"), diff --git a/tools/aurora-sep/tests/test_aurora_sep_status.py b/tools/aurora-sep/tests/test_aurora_sep_status.py index bc97814606705..4fdd72648276f 100644 --- a/tools/aurora-sep/tests/test_aurora_sep_status.py +++ b/tools/aurora-sep/tests/test_aurora_sep_status.py @@ -28,7 +28,7 @@ "matching": "unverified", "os_identity": "explicit", "hwrng": "registered", "xarm_failures": "0", "unhandled_messages": "0", "sleep": "awake", "sleeps": "3", "stac": "online", "stac_onlines": "4", "pnon": "read", - "sse": "idle", "sse_events": "0", "hibe": "idle", "skdl": "idle", + "xars": "ready", "sse": "idle", "sse_events": "0", "hibe": "idle", "skdl": "idle", } @@ -144,6 +144,28 @@ def test_the_boot_policy_digest_is_reported(self): row = [r for r in report["checks"] if r["check"] == "endpoint-clients"][0] self.assertIn("pnon", row["detail"]) + def test_the_xars_shutdown_barrier_is_reported(self): + rc, report, v = self.run_status() + self.assertEqual((rc, v["xars"]), (0, "PASS")) + row = [r for r in report["checks"] if r["check"] == "endpoint-clients"][0] + self.assertIn("xars=", row["value"]) + self.assertNotIn("xars", row["detail"]) + self.set("xars", "readonly") + rc, _, v = self.run_status() + self.assertEqual((rc, v["xars"]), (0, "WARN")) + self.set("xars", "failed") + rc, _, v = self.run_status() + self.assertEqual((rc, v["xars"]), (0, "WARN")) + self.set("xars", "absent") + rc, _, v = self.run_status() + self.assertEqual((rc, v["xars"]), (0, "INFO")) + # A kernel without the client lists xars as unserved. + self.set("xars", None) + rc, report, v = self.run_status() + self.assertNotIn("xars", v) + row = [r for r in report["checks"] if r["check"] == "endpoint-clients"][0] + self.assertIn("xars", row["detail"]) + def test_the_endpoints_checked_at_boot_are_reported(self): rc, report, v = self.run_status() self.assertEqual((rc, v["sse"], v["hibe"], v["skdl"], v["sse-events"]),