diff --git a/crates/stela-drivers/build/intel.rs b/crates/stela-drivers/build/intel.rs index f0a4471742..995fb947fd 100644 --- a/crates/stela-drivers/build/intel.rs +++ b/crates/stela-drivers/build/intel.rs @@ -52,12 +52,13 @@ const PACKERS: [(&str, &[u32]); 4] = [ /// Hosted tests of the adapters, which run in Stela's Linux environment, and /// of the encoders and packet adapters, which use the host's C library. -const LINUX_TESTS: [&str; 9] = [ +const LINUX_TESTS: [&str; 10] = [ "activation", "firmware", "ggtt_probe", "guc_reset", "huc_firmware", + "mmio_wait", "pat", "pt_walk", "wopcm", diff --git a/crates/stela-drivers/src/gpu/intel/activation.c b/crates/stela-drivers/src/gpu/intel/activation.c index c23dc1d60d..b0fd6cdccc 100644 --- a/crates/stela-drivers/src/gpu/intel/activation.c +++ b/crates/stela-drivers/src/gpu/intel/activation.c @@ -219,7 +219,7 @@ int stela_intel_activation_init(void *storage, size_t bytes, ret = io->prepare(context, (uint32_t)desc->platform, revision, desc->is_dgfx); if (ret) return ret; int64_t time = io->now_ns(context); - if (time < 0 || time > INT64_MAX - INT64_C(100000000)) return -22; + if (time < 0 || time > INT64_MAX - INT64_C(2000000000)) return -22; struct stela_intel_activation *state = storage; const struct stela_linux_owner owner = owner_of(state); stela_linux_enter(&owner); diff --git a/crates/stela-drivers/src/gpu/intel/activation.h b/crates/stela-drivers/src/gpu/intel/activation.h index 36a196325c..a783890e66 100644 --- a/crates/stela-drivers/src/gpu/intel/activation.h +++ b/crates/stela-drivers/src/gpu/intel/activation.h @@ -16,8 +16,11 @@ * writes order all required preceding accesses, reads honor original WA read * flushing. delay preserves atomic vs sleepable context, never substitutes a * 3-minute spin for a sleepable PCODE wait. invariant must fail-stop on false. - * now_ns is nonnegative, monotonic, and cannot approach INT64_MAX during the - * largest 100ms wait. All public calls require one real exclusive probe owner. + * now_ns is nonnegative, monotonic, and stays below INT64_MAX throughout each + * admitted wait and its real sleep/overshoot. GuC MMIO's largest single wait is + * 2 seconds; repeated retries retain the same live owner through genuine sleeps. + * This contract does not establish running firmware or admit a GuC request. + * All public calls require one real exclusive probe owner. */ struct stela_intel_activation_io { int (*check_context)(void *); @@ -67,8 +70,10 @@ int stela_intel_activation_wake(struct stela_intel_activation *); */ int stela_intel_activation_sleep(struct stela_intel_activation *); /* Private to the native adapters: Linux's xe_mmio_wait32 contract. Poll with - * doubling delays until (read & mask) == value or the timeout passes, then - * check once more; *out is the last read. Returns 0 or -ETIMEDOUT. */ + * doubling delays capped at 100 ms (atomic delays capped at MAX_UDELAY_MS), + * stop at the deadline, then check once more; *out is the last read, if present. + * Returns 0 or -ETIMEDOUT. Invalid + * clock/deadline returns -EINVAL before any register read or output change. */ int stela_intel_mmio_wait32(const struct stela_intel_activation_io *, void *, uint32_t offset, uint32_t mask, uint32_t value, uint32_t timeout_us, uint32_t *out, bool atomic); diff --git a/crates/stela-drivers/src/gpu/intel/activation.rs b/crates/stela-drivers/src/gpu/intel/activation.rs index 0f8112c17e..ff04bd7aad 100644 --- a/crates/stela-drivers/src/gpu/intel/activation.rs +++ b/crates/stela-drivers/src/gpu/intel/activation.rs @@ -35,8 +35,11 @@ pub struct PciIdentity { /// Ordered naturally-aligned MMIO32 operations must use the provided canonical /// CPU pointer, honor original read-flush WA and posting/ordering semantics, /// never conflate it with a physical/guest address and never fail/unwind. -/// The clock is qualified monotonic nonnegative nanoseconds, sufficiently below -/// i64::MAX for a 100ms deadline. Delay honors atomic/sleepable context. All calls +/// The clock is qualified monotonic nonnegative nanoseconds and remains below +/// i64::MAX throughout every admitted deadline and actual sleep/overshoot. GuC +/// MMIO needs up to two seconds per wait and retains the actual owner throughout +/// repeated retries; this contract alone does not admit running firmware or its +/// requests. Delay honors atomic/sleepable context. All calls /// and final Drop occur on the allowed native CPU/process context; no callback /// may reenter, activate guest services, or manufacture power/IRQ/coherence. /// `finish` drains actual probe accesses/posted writes and prevents new accesses diff --git a/crates/stela-drivers/src/gpu/intel/mmio.c b/crates/stela-drivers/src/gpu/intel/mmio.c index 2eb068d3c7..b798bfc2aa 100644 --- a/crates/stela-drivers/src/gpu/intel/mmio.c +++ b/crates/stela-drivers/src/gpu/intel/mmio.c @@ -4,6 +4,7 @@ * through its canonical uncached mapping. */ #include "device.h" #include +#include #include #include #include "regs/xe_gt_regs.h" @@ -115,23 +116,32 @@ int stela_intel_mmio_wait32(const struct stela_intel_activation_io *io, void *co bool atomic) { io->invariant(context, !(offset & 3) && (uint64_t)offset + 4 <= XE_REG_ADDR_MAX); - int64_t end = io->now_ns(context) + (int64_t)timeout_us * 1000; - uint32_t wait = 10, read = io->read32(context, offset); - int ret = 0; - while ((read & mask) != value) { - int64_t now = io->now_ns(context); - if (now > end) { - read = io->read32(context, offset); - ret = (read & mask) == value ? 0 : -ETIMEDOUT; + int64_t start = io->now_ns(context), duration = (int64_t)timeout_us * 1000; + /* A bad calibration/epoch must not authorize register access or signed + * deadline overflow. Keep the output untouched when no read took place. */ + if (start < 0 || start > INT64_MAX - duration) return -EINVAL; + int64_t end = start + duration; + uint32_t wait = 10, read; + int ret = -ETIMEDOUT; + for (;;) { + read = io->read32(context, offset); + if ((read & mask) == value) { + ret = 0; break; } - uint32_t left = (uint32_t)((end - now) / 1000) + 1; - if (wait > left) wait = left; - io->delay_us(context, wait, atomic ? wait : wait << 1, atomic); - if (wait < 1000) wait <<= 1; - read = io->read32(context, offset); + int64_t now = io->now_ns(context); + if (now >= end) break; + uint64_t left = (uint64_t)(end - now) / 1000; + if (wait > left) wait = (uint32_t)left; + uint32_t delay = atomic ? min(wait, MAX_UDELAY_MS * 1000U) : wait; + io->delay_us(context, delay, atomic ? delay : wait << 1, atomic); + wait = min(wait << 1, 100000U); } - *out = read; + if (ret) { + read = io->read32(context, offset); + if ((read & mask) == value) ret = 0; + } + if (out) *out = read; return ret; } @@ -142,6 +152,7 @@ int xe_mmio_wait32(struct xe_mmio *mmio, struct xe_reg reg, u32 mask, u32 val, u u32 addr = offset(dev, mmio, reg), read; int ret = stela_intel_mmio_wait32(dev->io, dev->context, addr, mask, val, timeout_us, &read, atomic); + if (ret == -EINVAL) return ret; /* The clock refused before any read. */ observe(dev, addr, read, false); if (out_val) *out_val = read; return ret; diff --git a/crates/stela-drivers/src/gpu/intel/tests/mmio_wait.c b/crates/stela-drivers/src/gpu/intel/tests/mmio_wait.c new file mode 100644 index 0000000000..087a74eb05 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/tests/mmio_wait.c @@ -0,0 +1,97 @@ +/* SPDX-License-Identifier: MIT */ +/* Actual native wait helper over a retained register/clock peer. */ +#include "../activation.h" +#include "../device.h" +#include "xe_mmio.h" +#include +#include +#include + +struct peer { + int64_t now; + unsigned reads, delays, ready_at; + uint32_t maximum_delay; + bool atomic; +}; +static uint32_t read32(void *context, uint32_t offset) +{ + struct peer *peer = context; + assert(offset == 0x20); + ++peer->reads; + return peer->ready_at && peer->reads >= peer->ready_at ? 1 : 0; +} +static int64_t now_ns(void *context) { return ((struct peer *)context)->now; } +static void delay_us(void *context, uint32_t minimum, uint32_t maximum, bool atomic) +{ + struct peer *peer = context; + assert(maximum >= minimum && atomic == peer->atomic); + assert(maximum == (atomic ? minimum : minimum * 2)); + if (minimum > peer->maximum_delay) peer->maximum_delay = minimum; + peer->now += (int64_t)minimum * 1000; + ++peer->delays; +} +static void invariant(void *context, bool condition) { (void)context; assert(condition); } +static const struct stela_intel_activation_io io = { + .read32 = read32, .now_ns = now_ns, .delay_us = delay_us, .invariant = invariant, +}; + +int main(void) +{ + uint32_t output; + unsigned cases = 0; + for (unsigned atomic = 0; atomic < 2; ++atomic) { + for (unsigned invalid = 0; invalid < 3; ++invalid) { + struct peer peer = {.now = invalid == 0 ? -1 : invalid == 1 ? INT64_MAX : INT64_MAX - 1999999999, + .ready_at = 1, .atomic = atomic != 0}; + output = 0xdeadbeef; + assert(stela_intel_mmio_wait32(&io, &peer, 0x20, 1, 1, 2000000, &output, peer.atomic) == -EINVAL); + assert(!peer.reads && !peer.delays && output == 0xdeadbeef); + ++cases; + } + /* At a zero deadline the original polls once and performs its final + * read without issuing any delay. Completion may arrive on that read. */ + for (unsigned ready = 1; ready <= 3; ++ready) { + struct peer peer = {.ready_at = ready, .atomic = atomic != 0}; + output = 0xdeadbeef; + int ret = stela_intel_mmio_wait32(&io, &peer, 0x20, 1, 1, 0, &output, peer.atomic); + assert(ret == (ready <= 2 ? 0 : -ETIMEDOUT)); + assert(peer.reads == (ready == 1 ? 1u : 2u) && !peer.delays); + assert(output == (ready <= 2 ? 1u : 0u)); + ++cases; + } + /* Original final read can observe completion after the nominal bound. */ + for (unsigned ready = 1; ready < 5; ++ready) { + struct peer peer = {.ready_at = ready, .atomic = atomic != 0}; + output = 0xdeadbeef; + int ret = stela_intel_mmio_wait32(&io, &peer, 0x20, 1, 1, 3, &output, peer.atomic); + assert(ret == (ready <= 3 ? 0 : -ETIMEDOUT)); + assert(output == (ready <= 3 ? 1u : 0u)); + assert(peer.reads == (ready <= 3 ? ready : 3)); + assert(peer.delays == (ready == 1 ? 0u : 1u)); + ++cases; + } + /* The maximum uint32 duration must not turn left+1 into zero delay. */ + struct peer peer = {.now = INT64_MAX - (int64_t)UINT32_MAX * 1000, + .ready_at = 2, .atomic = atomic != 0}; + assert(!stela_intel_mmio_wait32(&io, &peer, 0x20, 1, 1, UINT32_MAX, &output, peer.atomic)); + assert(peer.reads == 2 && peer.delays == 1 && output == 1); + ++cases; + /* Both original backoff caps must be reached on a long wait. */ + peer = (struct peer){.ready_at = 0, .atomic = atomic != 0}; + assert(stela_intel_mmio_wait32(&io, &peer, 0x20, 1, 1, 2000000, &output, peer.atomic) == -ETIMEDOUT); + assert(peer.maximum_delay == (atomic ? 5000u : 100000u)); + ++cases; + } + /* The Xe wrapper must not observe/store an uninitialized rejected read. */ + struct peer peer = {.now = INT64_MAX}; + struct stela_xe device; + struct xe_gt gt = {0}; + memset(&device, 0, sizeof(device)); + device.io = &io; device.context = &peer; + stela_xe_init(&device, >, XE_GT_TYPE_MAIN); + output = 0xdeadbeef; + assert(xe_mmio_wait32(>.mmio, XE_REG(0x20), 1, 1, 2000000, &output, false) == -EINVAL); + assert(!peer.reads && !peer.delays && output == 0xdeadbeef); + printf("intel_mmio_wait: %u peer scenarios\n", cases + 1); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/tests/mmio_wait_oracle.c b/crates/stela-drivers/src/gpu/intel/tests/mmio_wait_oracle.c new file mode 100644 index 0000000000..dc91131512 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/tests/mmio_wait_oracle.c @@ -0,0 +1,93 @@ +/* SPDX-License-Identifier: MIT */ +/* Compare complete original poll transcripts with the actual native adapter. */ +#include "activation.h" +#include "xe_mmio.h" +#include "regs/xe_reg_defs.h" +#include +#include +#include + +extern int printf(const char *, ...); +extern int fflush(void *); +#define check(x) do { if (!(x)) { printf("line %u: %s\n", __LINE__, #x); fflush((void *)0); __builtin_trap(); } } while (0) + +struct event { u64 a, b; unsigned kind; bool atomic; }; +struct model { + struct event trace[4096]; + unsigned count, reads, ready_at; + s64 now; + u32 clock_step; + bool atomic; +}; +static struct model actual, original, *current; +void stela_linux_warn(const char *file, int line, const char *condition, unsigned int flags) +{ (void)file; (void)line; (void)condition; (void)flags; check(false); } +static void record(unsigned kind, u64 a, u64 b, bool atomic) +{ + check(current->count < 4096); + current->trace[current->count++] = (struct event){.a = a, .b = b, .kind = kind, .atomic = atomic}; +} +static u32 read_peer(void *context, u32 offset) +{ + current = context; + check(offset == 0x20); + ++current->reads; + u32 value = current->ready_at && current->reads >= current->ready_at ? 0x80000001u : 0x80000000u; + record(1, offset, value, false); + return value; +} +static s64 clock_peer(void *context) +{ + current = context; + s64 now = current->now; + record(2, (u64)now, 0, false); + current->now += current->clock_step; + return now; +} +static void delay_peer(void *context, u32 minimum, u32 maximum, bool atomic) +{ + current = context; + check(atomic == current->atomic); + record(3, minimum, maximum, atomic); + current->now += (s64)minimum * 1000; +} +static void invariant(void *context, bool valid) { (void)context; check(valid); } +static const struct stela_intel_activation_io io = { + .read32 = read_peer, .now_ns = clock_peer, .delay_us = delay_peer, .invariant = invariant, +}; +u32 original_read32(struct xe_mmio *mmio, struct xe_reg reg) +{ (void)mmio; return read_peer(current, reg.addr); } +ktime_t ktime_get_raw(void) { return clock_peer(current); } +void original_udelay(unsigned long delay) +{ check(delay <= UINT32_MAX); delay_peer(current, (u32)delay, (u32)delay, true); } +void original_usleep_range(unsigned long minimum, unsigned long maximum) +{ check(maximum <= UINT32_MAX); delay_peer(current, (u32)minimum, (u32)maximum, false); } +int original_wait32(struct xe_mmio *, struct xe_reg, u32, u32, u32, u32 *, bool); + +int main(void) +{ + const u32 durations[] = {0, 1, 3, 9, 10, 11, 100, 1000, 99999, 100000, 100001, 2000000, UINT32_MAX}; + const unsigned ready[] = {0, 1, 2, 3, 5, 12, 22, 40}; + const u32 steps[] = {0, 333, 1000000}; + unsigned cases = 0; + for (unsigned atomic = 0; atomic < 2; ++atomic) + for (unsigned d = 0; d < sizeof(durations) / sizeof(durations[0]); ++d) + for (unsigned r = 0; r < sizeof(ready) / sizeof(ready[0]); ++r) + for (unsigned s = 0; s < sizeof(steps) / sizeof(steps[0]); ++s) { + if (durations[d] == UINT32_MAX && !ready[r]) continue; + memset(&actual, 0, sizeof(actual)); + actual.ready_at = ready[r]; actual.clock_step = steps[s]; actual.atomic = atomic != 0; + original = actual; + u32 a = 0xdeadbeef, b = 0xdeadbeef; + int actual_result = stela_intel_mmio_wait32(&io, &actual, 0x20, 1, 1, durations[d], &a, actual.atomic); + current = &original; + int original_result = original_wait32(NULL, XE_REG(0x20), 1, 1, durations[d], &b, original.atomic); + check(actual_result == original_result && a == b && actual.count == original.count && actual.reads == original.reads); + for (unsigned i = 0; i < actual.count; ++i) + check(actual.trace[i].kind == original.trace[i].kind && actual.trace[i].a == original.trace[i].a && + actual.trace[i].b == original.trace[i].b && actual.trace[i].atomic == original.trace[i].atomic); + ++cases; + } + printf("original/native complete MMIO polling transcripts: %u\n", cases); + return 0; +} diff --git a/crates/stela-drivers/tests/reference/intel_mmio_wait_oracle.py b/crates/stela-drivers/tests/reference/intel_mmio_wait_oracle.py new file mode 100644 index 0000000000..384de9ebb9 --- /dev/null +++ b/crates/stela-drivers/tests/reference/intel_mmio_wait_oracle.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +# Original Xe source copyright 2022 Intel Corporation. +"""Compare complete original Xe polling with the actual native C adapter. + +--flags contains a JSON array of actual driver C compiler flags, including the +canonical generated asm/include directories. No configuration is synthesized. +The fixture models register/clock/delay boundaries, not physical timing. +""" +import argparse +import hashlib +import json +from pathlib import Path +import subprocess + +PIN = "cc9de5d4b5ab6459f5774946aa3195ad51236fa8" +DONOR = "drivers/gpu/drm/xe/xe_mmio.c" +SHA256 = "8ebf27aafa9ad03a06d68179bf566d06e10a8d63dece557e02cea3df0884ce71" +GROUP_SHA256 = "a8c0cf96a83524185d7d198dd5f6a6919ae692ffc2aa47efa63c98ff13e9ba2e" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--linux", type=Path, required=True) + parser.add_argument("--flags", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--cc", default="clang") + args = parser.parse_args() + root = Path(__file__).resolve().parents[4] + intel = root / "crates/stela-drivers/src/gpu/intel" + donor = (args.linux / DONOR).read_bytes() + if hashlib.sha256(donor).hexdigest() != SHA256: + raise SystemExit("pinned original Xe MMIO source integrity mismatch") + flags = json.loads(args.flags.read_text()) + if not isinstance(flags, list) or not all(isinstance(v, str) for v in flags): + raise SystemExit("compiler flags must be a JSON string array") + if any(v in {"-c", "-o", "-E", "-S"} for v in flags): + raise SystemExit("compiler flags must not select an input/output mode") + text = donor.decode() + group = text[text.index("#define __XE_MMIO_WAIT_MAX_BACKOFF_100MS"):text.index("/**\n * xe_mmio_wait32()")] + if hashlib.sha256(group.encode()).hexdigest() != GROUP_SHA256: + raise SystemExit("complete original polling group integrity mismatch") + args.out.mkdir(parents=True, exist_ok=False) + oracle = args.out / "original.c" + oracle.write_text(text[:text.index("#include")] + '''#include +#include +#include +#include +#include "xe_mmio.h" +#include "regs/xe_reg_defs.h" +u32 original_read32(struct xe_mmio *, struct xe_reg); +void original_udelay(unsigned long); +void original_usleep_range(unsigned long, unsigned long); +#undef udelay +#undef usleep_range +#define xe_mmio_read32 original_read32 +#define udelay original_udelay +#define usleep_range original_usleep_range +''' + group + '''int original_wait32(struct xe_mmio *mmio, struct xe_reg reg, u32 mask, u32 value, + u32 timeout, u32 *out, bool atomic) +{ return __xe_mmio_wait32(mmio, reg, mask, value, timeout, out, atomic, true); } +''') + paths = [intel / "mmio.c", oracle, intel / "tests/mmio_wait_oracle.c"] + base = [args.cc, *flags, "-isystem", str(intel), "-isystem", str(args.linux / "drivers/gpu/drm/xe")] + result = dict(scope="Complete unchanged original private poll core vs actual native wait: ordered register/clock/delay transcript comparisons; modeled boundaries only", + donor=dict(pin=PIN, path=DONOR, sha256=SHA256, group_sha256=GROUP_SHA256), builds=[]) + for path in paths: + # Linux does not apply Stela's owned-C conversion diagnostics to its + # original function bodies. Keep those diagnostics on both owned units. + command = base + (["-Wno-conversion", "-Wno-sign-conversion"] if path == oracle else ["-Wconversion", "-Wsign-conversion"]) + command += ["-c", str(path), "-o", str(args.out / (path.stem + ".o"))] + built = subprocess.run(command, cwd=root / "crates/stela-drivers", capture_output=True, text=True) + result["builds"].append(dict(path=str(path), sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + command=command, exit=built.returncode, stderr=built.stderr)) + if built.returncode: + break + success = False + if len(result["builds"]) == 3 and all(row["exit"] == 0 for row in result["builds"]): + command = [args.cc, "-fsanitize=address,undefined", "-fno-sanitize-recover=all", + *[str(args.out / (path.stem + ".o")) for path in paths], "-o", str(args.out / "test")] + linked = subprocess.run(command, capture_output=True, text=True) + result["link"] = dict(command=command, exit=linked.returncode, stderr=linked.stderr) + if linked.returncode == 0: + result["binary_sha256"] = hashlib.sha256((args.out / "test").read_bytes()).hexdigest() + ran = subprocess.run([str(args.out / "test")], capture_output=True, text=True, timeout=30) + result["run"] = dict(exit=ran.returncode, stdout=ran.stdout, stderr=ran.stderr) + success = ran.returncode == 0 + (args.out / "measurement.json").write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(dict(output=str(args.out), passed=success, run=result.get("run")))) + raise SystemExit(0 if success else 1) + + +if __name__ == "__main__": + main()