diff --git a/crates/reims-vgpu-core/src/gpu_task/memory.rs b/crates/reims-vgpu-core/src/gpu_task/memory.rs index 3a4df4dc8..13e0e7b8e 100644 --- a/crates/reims-vgpu-core/src/gpu_task/memory.rs +++ b/crates/reims-vgpu-core/src/gpu_task/memory.rs @@ -842,6 +842,77 @@ mod tests { } } + /// A function whose IR sits over a hole in the task's page table, IR the guest has not + /// mapped: the resolver's lookup raises the function lookup's failure, where a nil function + /// would reach Metal and end the process, and makes the function once the guest maps the page + #[test] + fn a_function_over_a_hole_raises_its_lookup_until_the_page_is_mapped() { + use crate::raise::RaiseId; + use crate::resources::manager::create::function::ObjectFunction; + use crate::resources::manager::records::OperationHeader; + use crate::resources::manager::resolver::function_with_function_ref; + use crate::resources::manager::{ObjectKind, RaiseKind as ManagerRaise}; + use crate::testkit::platform::FAKE_REGISTRY_ID; + use zerocopy::IntoBytes; + + let mut entries = rw_pages(4); + entries[2] = 0; + let tx = fixture(1, &entries); + // entry 1 at task offset 12: a function whose 20-byte record is at task offset 0x100 + tx.ram + .write_u32(page_pa(ROOT_PAGE) + ROOT_OBJECT_LIST_LENGTH, 24); + tx.ram.write_u32(page_pa(DATA_PAGE) + 12, 6 | (20 << 8)); + tx.ram.write_u64(page_pa(DATA_PAGE) + 16, 0x100); + let ir_offset = 2 * PAGE + 0x10; + let function = ObjectFunction { + offset: ir_offset, + length: 4, + }; + let header = OperationHeader { + command_type: 15, + field4: 0, + }; + tx.ram + .write(page_pa(DATA_PAGE) + 0x100, function.as_bytes()); + tx.ram.write(page_pa(DATA_PAGE) + 0x10c, header.as_bytes()); + tx.ram.write(page_pa(DATA_PAGE + 2) + 0x10, &[9, 8, 7, 6]); + assert_eq!( + handshake_with(&tx, ROOT_PAGE, TASK_LEN, FAKE_REGISTRY_ID, true), + vec![(1, pid())] + ); + tx.task.ensure_object_list_mapped(Hold::NONE).unwrap(); + let (_, manager, _) = tx.task.parts(); + // The resource manager's lines, which `Lines` leaves out + let capture = crate::testkit::logs::capture(); + let raised = function_with_function_ref(Hold::NONE, &manager, 1) + .err() + .unwrap(); + assert_eq!( + raised.id(), + RaiseId::Manager(ManagerRaise::Lookup(ObjectKind::Function)) + ); + let want = format!( + "function 1 not made: its IR, 0x4 bytes at task offset {ir_offset:#x}, is not \ + mapped: a hole in the page table" + ); + let lines: Vec = capture.take().into_iter().map(|(_, _, m)| m).collect(); + assert!(lines.contains(&want), "{want}: {lines:?}"); + assert!(!tx.sels().contains(&"newLibraryWithData:error:")); + // the guest maps the page: the next lookup makes the function from its IR + tx.ram.write_u32(page_pa(PT_PAGE) + 8, (DATA_PAGE + 2) | W); + tx.p.world().set_library_functions(vec!["main0".to_owned()]); + assert!( + function_with_function_ref(Hold::NONE, &manager, 1) + .unwrap() + .is_some() + ); + let made = tx.p.call_log().calls_to("newLibraryWithData:error:"); + assert_eq!( + made.last().unwrap().args, + vec![crate::testkit::calllog::Arg::Bytes(vec![9, 8, 7, 6])] + ); + } + /// A failed read is logged with the byte of the copy where the page's bytes would have /// gone, and the copy goes on #[test] diff --git a/crates/reims-vgpu-core/src/resources/manager/create/function.rs b/crates/reims-vgpu-core/src/resources/manager/create/function.rs index b0570001f..126c40cd3 100644 --- a/crates/reims-vgpu-core/src/resources/manager/create/function.rs +++ b/crates/reims-vgpu-core/src/resources/manager/create/function.rs @@ -1,5 +1,13 @@ //! Functions (object type 6, command 15): the record names where the function's IR sits in the //! task's memory; Metal makes a library of it, and the library's one function is the object. +//! +//! IR the task cannot copy refuses the function, except IR over a hole in the task's page table, +//! which raises the function lookup's failure: a guest commits a buffer's pages to the task's +//! page table as it prepares a command buffer that lists the buffer, so a hole is IR the guest +//! has not mapped. A nil function would reach Metal, which ends the process at a nil vertex or +//! compute function; the raise faults the exec instead, as an empty entry's lookup does +//! (`resolver`), and caches nothing, so a lookup once the guest has mapped the IR makes the +//! function (docs/qemu.md, "x86-64 macOS guests: WebGPU render bundles"). use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; @@ -12,10 +20,10 @@ use crate::platform::device::GpuDevice; use crate::platform::resource::Library; use crate::raise::RaiseResult; use crate::raise::{OnFault, Raise}; -use crate::resources::manager::DeathKind; use crate::resources::manager::cache::nil_object; use crate::resources::manager::icb::ManagerOps; use crate::resources::manager::records::OperationHeader; +use crate::resources::manager::{DeathKind, ObjectKind, RaiseKind}; use crate::rt::Hold; /// The command type that makes a function from IR. @@ -70,10 +78,12 @@ fn new_function_with_ir>( Ok(Ok(library.new_function(OnFault::Return, name)?)) } -/// A function from `entry` and its record. +/// The function `reference` names, from `entry` and its record. IR over a hole in the task's +/// page table raises the function lookup's failure; IR the task cannot otherwise copy refuses it. pub(crate) fn create>( hold: Hold<'_>, m: &M, + reference: u32, entry: &ObjectEntry, mut cursor: Cursor, ) -> RaiseResult> { @@ -97,6 +107,14 @@ pub(crate) fn create>( let (offset, length) = (function.offset, function.length); let data = match m.get_data(hold, offset, u64::from(length)) { Ok(data) => data, + Err(missing) if missing.hole => { + log::warn!( + "function {reference} not made: its IR, {length:#x} bytes at task offset \ + {offset:#x}, is not mapped: {missing}" + ); + let kind = ObjectKind::Function; + return Err(Raise::new(RaiseKind::Lookup(kind)).with_detail(kind.failure())); + } Err(missing) => { return Ok(Err(format!( "the function's IR, {length:#x} bytes at task offset {offset:#x}, is not in \ @@ -119,7 +137,9 @@ pub(crate) fn create>( mod tests { use super::*; use crate::platform::types::NsErrorText; + use crate::raise::RaiseId; use crate::resources::manager::icb::testing::*; + use crate::resources::manager::lookup::NoData; use crate::testkit::calllog::Arg; use crate::testkit::capture::catch_death; use crate::testkit::{FakePlatform, Fk, Step, kind}; @@ -131,7 +151,7 @@ mod tests { } fn make(o: &FakeOps, ty: u32, data: &[u8]) -> Result, String> { - create::(Hold::NONE, o, &entry(ty), cursor(data)).unwrap() + create::(Hold::NONE, o, 3, &entry(ty), cursor(data)).unwrap() } fn error(description: &str) -> Step { @@ -184,6 +204,39 @@ mod tests { assert!(o.log().is_empty()); } + #[test] + fn ir_over_a_hole_raises_the_function_lookup_s_failure() { + let mut o = FakeOps::new(); + o.no_data = NoData { + hole: true, + why: "a hole in the page table".to_owned(), + }; + let (r, lines) = logged(|| { + create::( + Hold::NONE, + &o, + 3, + &entry(6), + cursor(&record(0x40, 4, 15)), + ) + }); + let raised = r.err().unwrap(); + assert_eq!( + raised.id(), + RaiseId::Manager(RaiseKind::Lookup(ObjectKind::Function)) + ); + assert_eq!(raised.detail(), Some("function lookup failed")); + assert_eq!( + lines, + vec![ + "function 3 not made: its IR, 0x4 bytes at task offset 0x40, is not mapped: a \ + hole in the page table" + ] + ); + assert_eq!(o.calls(), vec!["get_data(0x40, 0x4)"]); + assert!(o.log().is_empty()); + } + #[test] fn one_function_is_made_from_the_ir() { let mut o = FakeOps::new(); diff --git a/crates/reims-vgpu-core/src/resources/manager/resolver.rs b/crates/reims-vgpu-core/src/resources/manager/resolver.rs index 2d522644c..1ff693e44 100644 --- a/crates/reims-vgpu-core/src/resources/manager/resolver.rs +++ b/crates/reims-vgpu-core/src/resources/manager/resolver.rs @@ -5,13 +5,17 @@ //! The resolver's context object is the metal crate's, one per pipeline-descriptor send, //! holding [`function_with_function_ref`] as its resolver. //! -//! A failed lookup is nil to Metal, as Apple's framework answers it, except a function whose -//! entry is empty (type 0), which raises the function lookup's failure: Metal aborts on a nil -//! vertex or compute function, and the raise faults the exec instead, as every other failed -//! lookup of the decode does (`interplay_lifetime_held_pipeline_function_retyped`). A guest -//! empties a task's entries when the process that owns it ends, without waiting for the execs -//! that process queued, so an exec the host runs late makes its pipelines from empty entries -//! (x86-64 macOS 26 guests' icon services, docs/qemu.md). +//! A failed lookup is nil to Metal, as Apple's framework answers it, except two, which raise the +//! function lookup's failure: Metal aborts on a nil vertex or compute function, and the raise +//! faults the exec instead, as every other failed lookup of the decode does. +//! - A function whose entry is empty (type 0) +//! (`interplay_lifetime_held_pipeline_function_retyped`). A guest empties a task's entries when +//! the process that owns it ends, without waiting for the execs that process queued, so an +//! exec the host runs late makes its pipelines from empty entries (x86-64 macOS 26 guests' +//! icon services, docs/qemu.md). +//! - A function whose IR sits over a hole in the task's page table, IR the guest has not +//! mapped, which its creator raises (`create/function.rs`, `mutgap_svc_function_over_hole`; +//! docs/qemu.md, "x86-64 macOS guests: WebGPU render bundles"). use crate::num::Truncate; use crate::platform::Platform; @@ -22,7 +26,8 @@ use crate::rt::Hold; /// The function `function_ref` names: its low 32 bits are the reference. A lookup error is /// logged and nil to Metal, unless the reference's entry is empty, which raises the function -/// lookup's failure; a raise from the lookup (a task cursor or a creator raising) is `Err` too. +/// lookup's failure; a raise from the lookup (a task cursor, or a creator raising, as one does +/// for IR over a hole) is `Err` too. /// The platform carries an `Err` through Metal's frames to the caller's handler. pub fn function_with_function_ref( hold: Hold<'_>, diff --git a/crates/reims-vgpu-core/src/resources/manager/states.rs b/crates/reims-vgpu-core/src/resources/manager/states.rs index 4efe15b57..1e57cb952 100644 --- a/crates/reims-vgpu-core/src/resources/manager/states.rs +++ b/crates/reims-vgpu-core/src/resources/manager/states.rs @@ -104,7 +104,7 @@ state_kind! { state_kind! { /// The functions: released last of the manager's caches, after its lookup. Functions: Function in functions, - |m, hold, _, entry, cursor, _| function::create(hold, m, entry, cursor) + |m, hold, reference, entry, cursor, _| function::create(hold, m, reference, entry, cursor) } state_kind! { diff --git a/docs/qemu.md b/docs/qemu.md index 872ac2db2..1e58a23c9 100644 --- a/docs/qemu.md +++ b/docs/qemu.md @@ -1210,6 +1210,38 @@ Without the key, the aborts also fault the GPU. **Measured** with macOS reims-ctl counts these faults' lines in QEMU's log, and from the third tells the user to set the key from Recovery. +### x86-64 macOS guests: WebGPU render bundles + +**Measured** with a macOS 26 guest on an RTX 5080 Laptop GPU host: opening +Safari's WebGPU renderBundles sample ended QEMU. The host read the records +of a render pipeline's two functions, could not copy either function's IR +("the function's IR is not in task memory", which did not yet say why), +handed Metal both as nil, and Metal ended the process at a render +descriptor with no vertex function. In the 9.5 s before it the guest sent +no exec (67), and the host committed no command buffer in the last 4.5 s; +the guest sent 1,700 to 2,900 info indirects (69) and 1,000 to 2,000 +DiscardResources (63) a second, and the host's trace ends 0.14 ms after the +last info indirect. + +**Read**, from the guest's Metal driver and kext: +- A render pipeline holds its vertex and fragment functions' IR buffers. + Every command stream that names the pipeline adds those buffers to its + resource list: a render encoder's setRenderPipelineState, and an info + encoder's queries of the pipeline. +- The kext commits a listed buffer's pages to the task's page table as it + prepares the stream's resource list. + +So why the copy failed is not settled: IR whose pages the guest had not yet +committed, or a range past the task's end. The host now logs which. IR over +a hole raises the function lookup's failure ("function N not made: its IR +... is not mapped: a hole in the page table"), so the exec or info faults +where Metal would end the process, as for an empty entry (section 6.18 of +docs/testing.md, `mutgap_svc_function_over_hole`). Nothing is cached, so a +lookup once the guest has mapped the IR makes the function. IR past the +task's end is still nil to Metal, as Apple's framework answers it +(`compute_death_function_data_out_of_range`, measured). Whether the sample +draws with this is not yet measured. + ### x86-64 macOS guests: thumbnail extensions On an x86-64 macOS 26 guest, Quick Look's image and video thumbnail diff --git a/docs/testing.md b/docs/testing.md index f624c9d00..8b7c3c916 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -2745,13 +2745,19 @@ strings follow the entries, and a value gives their offset from the blob's start; an array is a u32 count then u32 offsets. A function is written as its `functionRef` (u32), which Metal resolves through the context's `functionWithFunctionRef:`; the device's context resolves it as an -object-list reference. A failed lookup resolves to nil, except one whose entry -is empty (type 0), which raises the function lookup's failure: the exec faults -("function lookup failed") rather than reaching Metal's abort on a nil -function. A guest empties a task's entries when the process that owns it -ends, without waiting for the execs that process queued, so an exec the host -runs after that end can meet them (`resources/manager/resolver.rs`, -`interplay_lifetime_held_pipeline_function_retyped`). +object-list reference. A failed lookup resolves to nil, except two, which raise +the function lookup's failure: the exec faults ("function lookup failed") +rather than reaching Metal's abort on a nil function (`resources/manager/resolver.rs`). +- One whose entry is empty (type 0). A guest empties a task's entries when the + process that owns it ends, without waiting for the execs that process + queued, so an exec the host runs after that end can meet them + (`interplay_lifetime_held_pipeline_function_retyped`). +- One whose IR sits over a hole in the task's page table. A guest commits a + buffer's pages as it prepares a command buffer that lists the buffer, so a + hole is IR the guest has not mapped, and nothing is cached: a lookup once the + guest has mapped it makes the function (docs/qemu.md, "x86-64 macOS guests: + WebGPU render bundles"; `mutgap_svc_function_over_hole`). IR the task cannot + otherwise copy (past the task's end, or ending at it) is still nil to Metal. | blob | bytes (`` = a function ref, u32 LE) | |---|---| @@ -4040,7 +4046,7 @@ found or the code shows, that no expected file holds. | blocks setup: a map that finds its run block full among 128 blocks, while an emptied block stays after the others (runs added before an empty block all go to the block before it) and the runs' total is not a multiple of 240 | `compact` packs the blocks from the front, leaves the last non-empty one short with the empty one after it, and asserts `to_steal != 0`: host death at the map | **measured**, `mutgap_mem_tracker_compact_empty_block` | | blocks setup: a run block of 240 runs (239 single-page runs and one of three pages), an unmap inside the three-page run, which splits it in place to 241 runs, then a map into the block | `RunBlock::split` keeps `old_count - half` runs, 121 and 121 of 241, and asserts that they add up: host death at the map | **measured**, `mutgap2_res_tracker_split_odd_death` (`mutgap2_res_tracker_split_adjacent` is the even control: 240 runs split into two of 120) | | a guest version below 10 using object type 11 or 15 in-process | assert `mapperIOSurfaces`: host death. The service checks no feature, and a type 15 buffer works there | **measured** for type 15 in the map setup, `mutgap_svc_mapper_below_v10`; type 11 **read** | -| a malformed serialized pipeline descriptor (garbage, truncated to 1 or 5 bytes), a function ref resolving to nil (ref 0, a wrong type, a short record or header, data outside the task, commandType 14, an empty, truncated or two-function library), an unspecialized function constant, a render descriptor with a nil vertex function or a buffer as its vertex function | abort inside Metal: host death in every setup | **measured**, `compute_death_blob_*`, `compute_death_function_*`, `render_objects_malformed_*`. A function ref whose entry is empty (type 0) is not among them: it raises, and the exec faults (section 6.18, `interplay_lifetime_held_pipeline_function_retyped`) | +| a malformed serialized pipeline descriptor (garbage, truncated to 1 or 5 bytes), a function ref resolving to nil (ref 0, a wrong type, a short record or header, data outside the task, commandType 14, an empty, truncated or two-function library), an unspecialized function constant, a render descriptor with a nil vertex function or a buffer as its vertex function | abort inside Metal: host death in every setup | **measured**, `compute_death_blob_*`, `compute_death_function_*`, `render_objects_malformed_*`. A function ref whose entry is empty (type 0), or whose IR sits over a hole in the task's page table, is not among them: it raises, and the exec faults (section 6.18, `interplay_lifetime_held_pipeline_function_retyped`, `mutgap_svc_function_over_hole`) | | DispatchThreadgroupsIndirect or DispatchThreadsIndirect with indirect buffer ref 0 | nil reaches Metal: host death in every setup | **measured**, `compute_death_threadgroups_indirect_nil`, `compute_death_threads_indirect_nil` | | a protection envelope with options 1 around a compute pass | Metal aborts opening the encoder: host death in every setup | **measured**, `compute_death_protection_options`; options 2 and all ones only fault (`compute_err_protected_encoder`, whose docstring says 3 dies too: not locked) | | a second encoder over an open one (a carried decoder reused), an encoder left open at commit, a protection envelope while a carried encoder is open | Metal asserts: host death in every setup | **measured**, `compute_death_second_encoder`, `exec_carried_compute_reopened` and `_isolate`, `render_segments_open_twice`, `exec_open_encoder_at_commit` and `_isolate`, `render_segments_open_last`, `exec_protection_envelope_open_encoder` (section 6.13) | diff --git a/tests/suite/scenarios/mutgap_service.py b/tests/suite/scenarios/mutgap_service.py index 24ebe9e4b..f90252397 100644 --- a/tests/suite/scenarios/mutgap_service.py +++ b/tests/suite/scenarios/mutgap_service.py @@ -11,6 +11,7 @@ import struct from pgtest import abi from pgtest.abi import PAGE from pgtest.compute_objects import Compute as C, Rig, function_record +from pgtest.covgap_svc_util import point, punch from pgtest.registry import scenario from pgtest.resources_build import (RGBA8Unorm, RTask, b_copy_buf_buf, b_copy_tex_buf, b_fill_buf, buffer_rec, desc1, simple_dim, texture_rec) @@ -172,6 +173,34 @@ def mutgap_svc_function_across_pages(): place, fault=False) +@scenario +def mutgap_svc_function_over_hole(): + """A function whose metallib sits on a task page the guest made a hole + (its leaf 0) after the task was installed: IR the guest has not mapped + yet. The exec's pipeline names the function; copying its IR + walks into the hole, and the function's lookup raises ("function lookup + failed"), so the exec faults in every setup, where a nil function would + have Metal abort building the pipeline (contrast + mutgap_svc_function_at_task_end). Nothing is cached: once the guest + points the leaf back at its page, the same exec makes the function and + the pipeline, and double_gid writes out[gid] = 2 gid for 4 threads.""" + r = Rig("mutgap_svc_function_over_hole", mutgap_svc_function_over_hole.__doc__, pages=64) + out, out_va = r.buffer() + va = r.t.reserve(PAGE) + n = r.s.mem_file(r.t.gpa(va), KERNEL) + fn = r.raw(abi.T_FUNCTION, function_record(va, n)) + pso = r.pipeline(fn) + r.ready() + vpn = va // PAGE + punch(r.t, vpn) + dispatch = (C.set_pipeline(pso), C.set_buffers(0, [(out, 0)]), C.dispatch_threads((4, 1, 1), (4, 1, 1))) + r.compute(*dispatch, fault=True, label="the function's IR over a hole") + point(r.t, vpn, r.s.pfn(r.t.data + vpn)) + r.compute(*dispatch, label="the function's IR mapped again") + r.dump(out_va, 0x20, "out") + return r.end() + + @scenario def mutgap_svc_readonly_leaf_buffer_write(): """A shared buffer (type 1, flags 0) over a read-only leaf (bit 31