From bd41d21140953602ac77ccb9225ef562e68074b5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 16:35:02 -0500 Subject: [PATCH 1/7] drm/asahi: g16: add RENDER_RAY_QUERY and BOUNDED_AS_BUILD support Implement cleanroom G16G (M4) hardware ray tracing support on top of the M4 production tree, advertising DRM_ASAHI_FEATURE_RENDER_RAY_QUERY and DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD: - Add pure RT validation, Gen1 SCS sizing, and intersection table helpers in g16/rt.rs (with TAIL_ENABLED = 0x2c), plus UAPI flags/reservations in asahi_drm.h and params.rs. - Extend command.rs stream parsing and SpanBatch VM admission for render ray-query stages, compute ray/SCS requests, and AS-build flags without reintroducing per-span VM locks. - Add demand-sized SCS UMA pools and freelist placement (0x80000 records in dedicated SCS windows) across slots.rs, pools.rs, resources.rs, hw.rs, and fw/buffer.rs, isolating SCS vs base arenas on reuse while retaining firmware PB/UMA leases across closed-VM reclaim. - Wire RT register encoding and J773g SCS bracketing (0x017e1 = 1 first, 0x017d9 = 1 last) in encode/{compute,render}.rs and engine.rs, pinning RT/SCS compute jobs to pipe 0, guarding horizon batching, and applying the 10 s long-job deadline allowance in recovery/logic.rs. Non-RT submits remain byte-identical. - Add test-ray-tracing.py and update asahi-m4 host selftests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 198 +++++- drivers/gpu/drm/asahi/g16/encode.rs | 12 +- drivers/gpu/drm/asahi/g16/encode/compute.rs | 162 ++++- drivers/gpu/drm/asahi/g16/encode/render.rs | 179 +++++- drivers/gpu/drm/asahi/g16/engine.rs | 149 ++++- drivers/gpu/drm/asahi/g16/fw/buffer.rs | 24 +- drivers/gpu/drm/asahi/g16/fw/graph.rs | 11 + drivers/gpu/drm/asahi/g16/fw/work.rs | 16 +- drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 10 +- drivers/gpu/drm/asahi/g16/hw.rs | 81 ++- drivers/gpu/drm/asahi/g16/job.rs | 10 + drivers/gpu/drm/asahi/g16/mod.rs | 3 +- drivers/gpu/drm/asahi/g16/object.rs | 2 +- drivers/gpu/drm/asahi/g16/params.rs | 6 +- drivers/gpu/drm/asahi/g16/pools.rs | 243 ++++++-- drivers/gpu/drm/asahi/g16/queue.rs | 32 +- drivers/gpu/drm/asahi/g16/recovery.rs | 33 +- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 61 ++ drivers/gpu/drm/asahi/g16/resources.rs | 157 ++++- drivers/gpu/drm/asahi/g16/rt.rs | 531 ++++++++++++++++ drivers/gpu/drm/asahi/g16/slots.rs | 151 ++++- include/uapi/drm/asahi_drm.h | 2 +- .../drivers/gpu/asahi-m4/check-compute.rs | 5 +- .../gpu/asahi-m4/test-command-stream.py | 31 +- .../gpu/asahi-m4/test-progress-wrap.py | 26 +- .../drivers/gpu/asahi-m4/test-publication.py | 84 +-- .../drivers/gpu/asahi-m4/test-ray-tracing.py | 587 ++++++++++++++++++ .../drivers/gpu/asahi-m4/test-resources.py | 249 ++++---- 28 files changed, 2646 insertions(+), 409 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g16/rt.rs create mode 100644 tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 3d6e66ff8bdfd..c45d53bc86eab 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -9,7 +9,10 @@ //! Render/compute attachments are retained with the immutable command; the whole //! VM job guard protects indirect and bindless accesses through retirement. //! Exact historical prefixes become immutable per-command dependencies. Ray-query state -//! remains disabled. +//! (RENDER_RAY_QUERY) and the AS-build flag (BOUNDED_AS_BUILD) are the M4 Pro's G17P command +//! set ([`super::rt`]): compute scratch layouts and intersection tables, render ray-query +//! stages, and compute flag bit 2 (alongside COMPUTE_NO_QUERY_ACCESS); every other compute +//! flag and reserved word stays MBZ. use core::mem::{offset_of, size_of}; use core::ops::Range; @@ -169,6 +172,10 @@ impl Order { pub(crate) struct RenderCommand { /// The payload, zero-extended to the full UAPI structure. pub(crate) cmd: uapi::drm_asahi_cmd_render, + /// The validated ray-query state of the vertex and fragment stages. + pub(crate) ray_query: [super::rt::RayQueryStage; 2], + /// The SCS-capable UMA pool of both stages' scratch. + pub(crate) scs: super::rt::ScsSeeds, /// Retained timestamp destinations, published after full command retirement. pub(crate) timestamp_outputs: crate::timestamp::Destinations, /// Explicit hardware attachments in effect for each render engine. @@ -179,6 +186,12 @@ pub(crate) struct RenderCommand { /// A validated compute command. pub(crate) struct ComputeCommand { pub(crate) cmd: uapi::drm_asahi_cmd_compute, + /// The validated scratch layout and intersection tables. + pub(crate) ray: super::rt::ComputeRay, + /// The SCS-capable UMA pool of the scratch. + pub(crate) scs: super::rt::ScsSeeds, + /// DRM_ASAHI_COMPUTE_AS_BUILD. + pub(crate) as_build: bool, /// The compute attachments in effect (validated writable). pub(crate) attachments: KVec, /// Retained timestamp destinations, published after full command retirement. @@ -187,12 +200,43 @@ pub(crate) struct ComputeCommand { pub(crate) query_access: bool, } +impl ComputeCommand { + /// Whether this compute command uses ray-tracing or SCS-scratch state. + pub(crate) fn is_rt(&self) -> bool { + self.as_build || self.ray.intersection.enabled() || self.scs.needed != 0 + } +} + /// A validated command. pub(crate) enum Command { Render(KBox), Compute(KBox), } +impl Command { + /// The command traces rays or builds acceleration structures and gets the long execution + /// allowance, as do the other commands of its submission (`Job::long`). + pub(crate) fn long(&self) -> bool { + match self { + Command::Render(r) => { + super::rt::select(false, r.ray_query.map(|stage| stage.traces()), false) + } + Command::Compute(c) => { + super::rt::select(c.ray.intersection.enabled(), [false; 2], c.as_build) + } + } + } + + /// The SCS-capable UMA pool the command runs on ([`super::rt::ScsSeeds::NONE`] without + /// shader-context scratch). + pub(crate) fn scs(&self) -> super::rt::ScsSeeds { + match self { + Command::Render(r) => r.scs, + Command::Compute(c) => c.scs, + } + } +} + /// Inline storage for the common 1-2 command submission, spilling to a heap `KVec` above 2. pub(crate) enum Commands { Empty, @@ -314,6 +358,10 @@ pub(crate) struct Context<'a> { pub(crate) vm: &'a mmu::Vm, /// The queue's USC window base. pub(crate) usc_base: u64, + /// Enabled GPU cores, which SCS memory is sized for. + pub(crate) active_cores: u32, + /// The queue's reserved render scratch pages per stage (`render_scs_layout`). + pub(crate) render_scs: [u16; 2], } /// A stream whose timestamps and ordinals are resolved ([`ParsedStream::prepare`]), before its @@ -450,6 +498,32 @@ fn render_payload( } } +/// Render payload bytes before the ray-query stages: they follow the historical prefixes. +const RAY_QUERY_START: usize = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); + +/// The ray-query stages of a render payload; a shorter payload reads both stages zeroed. +/// Bounded by [`RENDER_STAGE_PREFIXES_OFF`] so 480-byte `STAGE_PREFIXES` tails stay separate. +fn render_ray_query(bytes: &[u8]) -> Result<[super::rt::RayQueryStage; 2]> { + let rq_end = bytes.len().min(RENDER_STAGE_PREFIXES_OFF); + super::rt::RayQueryStage::parse_pair(bytes.get(RAY_QUERY_START..rq_end).unwrap_or(&[])) +} + +/// The scratch layout and intersection tables of a compute command. The M5 auxiliary +/// allocation and the reserved word stay MBZ. +fn compute_ray(cmd: &uapi::drm_asahi_cmd_compute) -> Result { + super::rt::ComputeRay::new( + cmd.scs_layout, + cmd.cdm_auxiliary_allocation, + cmd.reserved, + cmd.intersection_pool, + cmd.intersection_pool_bytes, + cmd.intersection_first, + cmd.intersection_count, + cmd.intersection_default_program, + cmd.intersection_default_control, + ) +} + /// Whether `[start, start + size)` is a nonempty range inside `range`. fn inside(start: u64, size: u64, range: &Range) -> bool { size != 0 && start >= range.start && start < range.end && size <= range.end - start @@ -505,20 +579,12 @@ fn validate_render_entry( ) -> Result<( uapi::drm_asahi_cmd_render, Option, + [super::rt::RayQueryStage; 2], )> { let (packet, prefixes) = render_payload(entry.payload)?; let cmd = &packet; - // Ray-query extensions belong to G17; reject every nonzero byte - // between the common historical-prefix fields and the stage-prefix tail. - let end = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); - let rq_end = entry.payload.len().min(RENDER_STAGE_PREFIXES_OFF); - if entry - .payload - .get(end..rq_end) - .is_some_and(|tail| tail.iter().any(|&b| b != 0)) - { - return Err(EINVAL); - } + // The ray-query stages after the historical prefixes (RENDER_RAY_QUERY). + let ray_query = render_ray_query(entry.payload)?; if let Some(prefixes) = prefixes { if (prefixes.ta_vdm_barrier != NONE && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) || (prefixes.ta_cdm_barrier != NONE @@ -556,8 +622,6 @@ fn validate_render_entry( { return Err(EINVAL); } - // `payload` rejects nonzero ray-query bytes beyond the prior - // extension. RENDER_RAY_QUERY is never advertised on G16. // Never discard unflagged high words, nor accept the flag without them. if cmd.flags & RSRC_SPEC_HI != 0 && entry.payload.len() < RSRC_SPEC_HI_MIN { return Err(EINVAL); @@ -570,17 +634,19 @@ fn validate_render_entry( { return Err(EINVAL); } - Ok((packet, prefixes)) + Ok((packet, prefixes, ray_query)) } fn validate_compute_entry( entry: &Entry<'_>, range: &Range, -) -> Result { +) -> Result<(uapi::drm_asahi_cmd_compute, super::rt::ComputeRay, bool)> { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; let cmd = &packet; - if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 - || cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base + let Some(as_build) = super::rt::as_build(cmd.flags & !COMPUTE_NO_QUERY_ACCESS) else { + return Err(EINVAL); + }; + if cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base || !inside( cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, @@ -589,24 +655,16 @@ fn validate_compute_entry( { return Err(EINVAL); } - // The G17P scratch layout and intersection tables: never on G16. if cmd .ts_end_copies .iter() .any(|ts| ts.handle != 0 || ts.offset != 0) - || packet.scs_layout != 0 - || packet.cdm_auxiliary_allocation != 0 - || packet.reserved != 0 - || packet.intersection_pool != 0 - || packet.intersection_pool_bytes != 0 - || packet.intersection_first != 0 - || packet.intersection_count != 0 - || packet.intersection_default_program != 0 - || packet.intersection_default_control != 0 { return Err(EINVAL); } - Ok(packet) + // The G17P scratch layout and intersection tables (RENDER_RAY_QUERY). + let ray = compute_ray(cmd)?; + Ok((packet, ray, as_build)) } /// Checks that `[start, end)` (rounded out to pages) lies inside the user address range and @@ -1231,6 +1289,68 @@ fn check_render( Ok(()) } +/// The hardware reads the intersection pool and the default intersection program: both must +/// be mapped readable, as on the M4 Pro. +fn check_intersection( + batch: &mut SpanBatch, + vm: &mmu::Vm, + tables: &super::rt::IntersectionTables, +) -> Result { + if !tables.enabled() { + return Ok(()); + } + let end = tables.pool.checked_add(tables.pool_bytes).ok_or(EINVAL)?; + batch.push(vm, tables.pool, end, true, false)?; + let code = tables.default_code(); + if code != 0 { + batch.push(vm, code, code.checked_add(64).ok_or(EINVAL)?, true, false)?; + } + Ok(()) +} + +/// Per-command render ray-query admission. A render's scratch must fit what its queue +/// reserved (`render_scs_layout`): the render's UMA pool was sized for that (EINVAL beyond it, +/// as on the M4 Pro). Returns the SCS-capable pool the render runs on, sized for the +/// reservation ([`super::rt::pool_seeds`]). +fn check_render_ray( + batch: &mut SpanBatch, + context: &Context<'_>, + stages: &[super::rt::RayQueryStage; 2], +) -> Result { + for stage in stages { + check_intersection(batch, context.vm, &stage.intersection)?; + } + if !stages.iter().any(|stage| stage.scratch.enabled()) { + return Ok(super::rt::ScsSeeds::NONE); + } + let pages = stages.map(|stage| stage.scratch.pages()); + let needed = super::rt::required_seeds(context.active_cores, &pages)?; + let reserved = super::rt::required_seeds(context.active_cores, &context.render_scs)?; + if needed > reserved { + return Err(EINVAL); + } + let pool = super::rt::pool_seeds(context.active_cores, context.render_scs)?; + Ok(super::rt::ScsSeeds { needed, pool }) +} + +/// Per-command compute ray admission: the tables are mapped and the scratch fits an +/// SCS-capable UMA pool (E2BIG). Returns the SCS-capable pool the command runs on. +fn check_compute_ray( + batch: &mut SpanBatch, + context: &Context<'_>, + ray: &super::rt::ComputeRay, +) -> Result { + check_intersection(batch, context.vm, &ray.intersection)?; + if !ray.scratch.enabled() { + return Ok(super::rt::ScsSeeds::NONE); + } + let pages = ray.scratch.pages(); + Ok(super::rt::ScsSeeds { + needed: super::rt::required_seeds(context.active_cores, &[pages])?, + pool: super::rt::pool_seeds(context.active_cores, [pages, 0])?, + }) +} + /// Per-command compute admission. fn check_compute( batch: &mut SpanBatch, @@ -1240,7 +1360,7 @@ fn check_compute( ) -> Result<(u64, u64)> { let vm = context.vm; let (base, end) = (cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end); - if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 + if super::rt::as_build(cmd.flags & !COMPUTE_NO_QUERY_ACCESS).is_none() || cmd.sampler_count != 0 || cmd.sampler_heap != 0 || !helper_is_empty(&cmd.helper) @@ -1366,7 +1486,8 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { - let (packet, prefixes) = validate_render_entry(&entry, counts, early_tiling)?; + let (packet, prefixes, ray_query) = + validate_render_entry(&entry, counts, early_tiling)?; counts[RENDER] += 1; if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { return Err(EINVAL); @@ -1399,6 +1520,8 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result Result { - let packet = validate_compute_entry(&entry, &range)?; + let (packet, ray, as_build) = validate_compute_entry(&entry, &range)?; counts[COMPUTE] += 1; if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { return Err(EINVAL); @@ -1433,6 +1556,9 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result Result { let Prepared { - commands, + mut commands, orders, counts, } = self; @@ -1555,7 +1681,7 @@ impl Prepared { { let scratch = &mut proof.scratch; scratch.batch.clear(); - for command in commands.iter() { + for command in commands.iter_mut() { match command { Command::Render(render) => { check_render( @@ -1565,6 +1691,8 @@ impl Prepared { &render.vertex_attachments, &render.fragment_attachments, )?; + render.scs = + check_render_ray(&mut scratch.batch, context, &render.ray_query)?; if vdm_count >= scratch.vdm_vas.len() { return Err(EINVAL); } @@ -1578,6 +1706,8 @@ impl Prepared { &compute.cmd, &compute.attachments, )?; + compute.scs = + check_compute_ray(&mut scratch.batch, context, &compute.ray)?; if cdm_count >= scratch.cdm_ranges.len() { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index 9fdc397dc3cfc..5c91c50db2884 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -8,7 +8,7 @@ use kernel::{prelude::*, uapi}; -use super::fw::graph::manager; +use super::fw::graph::{manager, pools}; use super::fw::work::{self, barrier, compute, fs, initbm, scene, ta, REG_RECORD}; use super::hw; @@ -72,8 +72,9 @@ mod compute_encoder; use compute_encoder::put_generation; #[allow(unused_imports)] // Pure encoder utilities are exercised by the host ABI harness. pub(crate) use compute_encoder::{ - encode_compute, encode_compute_for, init_compute_pool, preserve_compute_descriptor, - ComputeEncodeError, ComputeRefs, + encode_compute, encode_compute_for, encode_compute_rt, init_compute_pool, + preserve_compute_descriptor, ComputeEncodeError, ComputeRefs, ComputeRt, + COMPUTE_SCS_DRIVER_WORD, }; /// Tiling geometry and register words of a render (accelerator count 2). @@ -281,6 +282,7 @@ pub(crate) fn barrier( mod render_encoder; #[allow(unused_imports)] // Includes private-tail variants rejected by the shared Mesa UAPI. pub(crate) use render_encoder::{ - append_fs_timestamp_copies, encode_fs, encode_fs_for, encode_ta, encode_ta_for, fill_scene, - initbm, render_attachments, scene, scene_prefix, scene_render, PassRefs, RenderRefs, + append_fs_timestamp_copies, encode_fs, encode_fs_for, encode_fs_rt, encode_ta, encode_ta_for, + encode_ta_rt, fill_scene, initbm, render_attachments, scene, scene_prefix, scene_render, + PassRefs, RenderRefs, StageRt, RENDER_SCS_ENABLE, }; diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 179f39cb4c3bf..71191ebabfc35 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -3,7 +3,7 @@ //! Pure G16G compute encoding (25G83 and 26B123 work layouts). Publication and lifetime proofs //! belong to the engine. -use super::{compute, manager, put16, put32, put64, put8, uapi}; +use super::{compute, manager, pools, put16, put32, put64, put8, uapi}; /// Stores the binding generation `v` as a little-endian integer of `bytes` (1 or 8) bytes. pub(super) fn put_generation(b: &mut [u8], off: usize, bytes: usize, v: u8) { @@ -65,6 +65,59 @@ pub(crate) struct ComputeRefs { pub(crate) submitted: u64, } +/// The first and last register records of a ray-query compute work item, as macOS 27.2 on the +/// J773g writes them: 0x017e1 = 1 first (only in ray-query items) and 0x017d9 = 1 last. macOS +/// also writes the trailing 0x017d9 in some compute work without ray queries; G16G's +/// non-ray-query work keeps the list it has always had. +const RAY_QUERY_FIRST: (u32, u64) = (0x017e1, 1); +const RAY_QUERY_LAST: (u32, u64) = (0x017d9, 1); +/// Write the SCS driver word 0x1a141 after 0x1a0e9 for a command with scratch, as g17's G17P +/// compute program does (zero on Gen1). Off: 25F84's program does not write it. Trace +/// question T1. +pub(crate) const COMPUTE_SCS_DRIVER_WORD: bool = false; + +/// The ray-tracing words of one compute work item, and the UMA pool it runs with. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct ComputeRt { + /// 0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1. + pub(crate) intersection: [u64; 6], + /// 0x101d1. + pub(crate) size: u64, + /// 0xd479. + pub(crate) tail: u64, + /// 0x1a0e9. + pub(crate) stack: u64, + /// 0x107a1. + pub(crate) window: u64, + /// 0x1a141, with [`COMPUTE_SCS_DRIVER_WORD`]. + pub(crate) driver: u64, + /// The command has scratch (the gated registers apply). + pub(crate) scs: bool, + /// Freelist entries of the unit's UMA pool, published in a fresh descriptor (SEEDS_A/B). + pub(crate) seeds: u32, + /// Records of the unit's freelist, published in a fresh descriptor (+0x1c). + pub(crate) records: u32, +} + +impl ComputeRt { + /// A command without ray state in a base UMA pool: the words G16G has always written. + pub(crate) const DISABLED: Self = Self { + intersection: [0; 6], + size: 0, + tail: 0, + stack: 8, + window: 0xff0000, + driver: 0, + scs: false, + seeds: 8192, + records: manager::UNK_1C_VALUE, + }; +} + +/// Register records of a compute work item at most: the 24 of [`compute::SEL`], 0x10071, the +/// ray-query first and last records and the gated SCS driver word. +const MAX_REGS: usize = compute::SEL.len() + 4; + const FW_START: u64 = 0xfffffc2000000000; const FW_END: u64 = 0xfffffc2ffc000000; const VM_START: u64 = 0x4000; @@ -185,8 +238,38 @@ pub(crate) fn encode_compute( } /// [`encode_compute`] for the work layout of another firmware ABI. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_compute_for( + layout: &compute::Layout, + r: &ComputeRefs, + c: &uapi::drm_asahi_cmd_compute, + att: &[uapi::drm_asahi_attachment], + ts_va: &[u64; 2], + ctx: u32, + n: u64, + fault_mask: u32, + w: &mut [u8; compute::WORK_SIZE], + q: &mut [u8; compute::SEQ_SIZE], +) -> Result<(), ComputeEncodeError> { + encode_compute_rt( + layout, + r, + c, + att, + ts_va, + ctx, + n, + fault_mask, + &ComputeRt::DISABLED, + w, + q, + ) +} + +/// [`encode_compute_for`] with the command's ray-tracing words and its unit's UMA pool. With +/// [`ComputeRt::DISABLED`] the bytes are [`encode_compute_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_compute_rt( layout: &compute::Layout, r: &ComputeRefs, c: &uapi::drm_asahi_cmd_compute, @@ -195,9 +278,19 @@ pub(crate) fn encode_compute_for( ctx: u32, _n: u64, fault_mask: u32, + rt: &ComputeRt, w: &mut [u8; compute::WORK_SIZE], q: &mut [u8; compute::SEQ_SIZE], ) -> Result<(), ComputeEncodeError> { + // Whole 2-MiB pool rows within the freelist the manager reports, which is never smaller + // than a base unit's. + if rt.seeds == 0 + || rt.seeds % 512 != 0 + || rt.seeds > rt.records + || rt.records < manager::UNK_1C_VALUE + { + return Err(ComputeEncodeError::Storage); + } if ctx == 0 || ctx >= 64 { return Err(ComputeEncodeError::Context); } @@ -230,7 +323,12 @@ pub(crate) fn encode_compute_for( compute::CONTEXT_STORE_SIZE as u64, 0x4000, ) - || !gpu(r.pool_state_gva, compute::POOL_STATE_SIZE as u64, 0x4000) + // The freelist: one u64 seed address per record. + || !gpu( + r.pool_state_gva, + u64::from(rt.records) * core::mem::size_of::() as u64, + 0x4000, + ) || !gpu(r.page_list_gva, compute::PAGE_LIST_SIZE as u64, 0x4000) || (r.usc_base != 0 && !gpu(r.usc_base, 0x100000000, 0x100000000)) { @@ -272,6 +370,7 @@ pub(crate) fn encode_compute_for( } } let pre = r.preempt_gva; + let [i0, i1, i2, i3, i4, i5] = rt.intersection; let values = [ pre, base, @@ -282,16 +381,16 @@ pub(crate) fn encode_compute_for( 0x154024201, 0x10c08860, 0x1c, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, - 0xff0000, + i0, + i1, + i2, + i3, + i4, + i5, + rt.size, + rt.tail, + rt.stack, + rt.window, 0x13200400020, 0x200000001, 1, @@ -300,15 +399,32 @@ pub(crate) fn encode_compute_for( ]; w.fill(0); q.fill(0); - for (i, (&sel, &value)) in compute::SEL.iter().zip(values.iter()).enumerate() { - put32(w, compute::REGS + i * 12, sel); - put64(w, compute::REGS + i * 12 + 4, value); + let mut records = [(0u32, 0u64); MAX_REGS]; + let mut count = 0; + let mut push = |sel: u32, value: u64| { + records[count] = (sel, value); + count += 1; + }; + if rt.scs { + push(RAY_QUERY_FIRST.0, RAY_QUERY_FIRST.1); + } + for (&sel, &value) in compute::SEL.iter().zip(values.iter()) { + push(sel, value); + if sel == 0x1a0e9 && COMPUTE_SCS_DRIVER_WORD && rt.scs { + push(0x1a141, rt.driver); + } } - let count = if r.usc_base == 0 { 24 } else { 25 }; if r.usc_base != 0 { - put32(w, compute::REGS + 24 * 12, 0x10071); - put64(w, compute::REGS + 24 * 12 + 4, r.usc_base); + push(0x10071, r.usc_base); + } + if rt.scs { + push(RAY_QUERY_LAST.0, RAY_QUERY_LAST.1); + } + for (i, &(sel, value)) in records[..count].iter().enumerate() { + put32(w, compute::REGS + i * 12, sel); + put64(w, compute::REGS + i * 12 + 4, value); } + let count = count as u16; put32(w, 0, 3); put32(w, 0xc, ctx); put64( @@ -412,12 +528,12 @@ pub(crate) fn encode_compute_for( put32(w, d + manager::INDEX, r.uma_slot); put32(w, d + manager::ONE, 2); put64(w, d + manager::FREELIST, r.pool_state_gva); - put32(w, d + manager::UNK_1C, manager::UNK_1C_VALUE); - put32(w, d + manager::SEEDS_A, 8192); - put32(w, d + manager::SEEDS_B, 8192); + put32(w, d + manager::UNK_1C, rt.records); + put32(w, d + manager::SEEDS_A, rt.seeds); + put32(w, d + manager::SEEDS_B, rt.seeds); put64(w, d + manager::POOL_TABLE, r.page_list_gva); put32(w, d + 0x40, 4); - put32(w, d + 0x48, 128); + put32(w, d + manager::ROW_WORDS, pools::row_words(rt.seeds)); put64(w, compute::DESCRIPTOR_COUNTER, r.counter_fw); // Native M+0x5c distinguishes shared compute from per-workqueue-private pools. // Retain the existing value for these persistent units reused across queues; diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index 0d7f569c9a54a..647ce05126453 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -69,6 +69,61 @@ pub(crate) struct PassRefs { pub(crate) ta_scratch: u64, } +/// Write the macOS 27.2 J773g SCS enable pair (`0x017e1 = 1` before `at`, `0x017d9 = 1` at the +/// end) in the register list of a render stage with scratch: `0x017e1 = 1` first in the TA list +/// (before `0x1748`) and after `0x1739` in the FS list, with `0x017d9 = 1` last in both, matching +/// `encode::compute` (`RAY_QUERY_FIRST`/`RAY_QUERY_LAST`) and the M5 render register lists. +pub(crate) const RENDER_SCS_ENABLE: bool = true; + +/// The ray-query words of one render stage (the M4 Pro's 25G83 render programs). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct StageRt { + /// TA 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1; FS 0x1a0a9, 0x1a0b1, 0x1a079, + /// 0x1a081, 0x1a0d9, 0x1a0e1. + pub(crate) intersection: [u64; 6], + /// TA 0x101c9, FS 0x101c1. + pub(crate) size: u64, + /// TA 0xd471, FS 0xd469. + pub(crate) tail: u64, + /// TA 0x1a0f1, FS 0x1a0f9. + pub(crate) stack: u64, + /// TA 0x10799; FS 0x10791 with bit 9. + pub(crate) window: u64, + /// The stage has scratch (the gated register applies). + pub(crate) scs: bool, +} + +impl StageRt { + /// A stage without ray queries: the words G16G has always written. + pub(crate) const DISABLED: Self = Self { + intersection: [0; 6], + size: 0, + tail: 0, + stack: 8, + window: 0xff0000, + scs: false, + }; +} + +/// Register records, bracketed with `0x017e1 = 1` before record `at` and `0x017d9 = 1` at the +/// end when `RENDER_SCS_ENABLE && scs`; returns the record count. +fn stage_regs(dst: &mut [u8], sel: &[u32], val: &[u64], scs: bool, at: usize) -> u16 { + if !(RENDER_SCS_ENABLE && scs) { + regs(dst, sel, val); + return sel.len() as u16; + } + regs(dst, &sel[..at], &val[..at]); + put32(dst, REG_RECORD * at, 0x017e1); + put64(dst, REG_RECORD * at + 4, 1); + if let Some(rest) = dst.get_mut(REG_RECORD * (at + 1)..) { + regs(rest, &sel[at..], &val[at..]); + } + let last = REG_RECORD * (sel.len() + 1); + put32(dst, last, 0x017d9); + put64(dst, last + 4, 1); + sel.len() as u16 + 2 +} + fn scene_list_va(r: &RenderRefs, p: &PassRefs) -> u64 { if p.scene_list != 0 { p.scene_list @@ -158,8 +213,40 @@ pub(crate) fn encode_ta( /// Encode the 66-record single-cluster tiler work of `layout`'s ABI and its exact 0x300 /// sequence. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_ta_for( + layout: &ta::Layout, + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + target: u32, + geo: &Geometry, + cl: Option<&ClusterLayout>, + w: &mut [u8; ta::WORK_SIZE], + q: &mut [u8; ta::SEQ_SIZE], +) { + encode_ta_rt( + layout, + r, + p, + u, + ts_va, + ctx, + target, + geo, + cl, + &StageRt::DISABLED, + w, + q, + ) +} + +/// [`encode_ta_for`] with the vertex stage's ray-query words. With [`StageRt::DISABLED`] the +/// bytes are [`encode_ta_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_ta_rt( layout: &ta::Layout, r: &RenderRefs, p: &PassRefs, @@ -169,6 +256,7 @@ pub(crate) fn encode_ta_for( target: u32, geo: &Geometry, _cl: Option<&ClusterLayout>, + rt: &StageRt, w: &mut [u8; ta::WORK_SIZE], q: &mut [u8; ta::SEQ_SIZE], ) { @@ -229,16 +317,16 @@ pub(crate) fn encode_ta_for( 0, 0x1c, 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, - 0xff0000, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + rt.window, u64::from(r.parameter_id), compact(scene_list_va(r, p)), compact(scene_list_va(r, p)), @@ -251,7 +339,7 @@ pub(crate) fn encode_ta_for( // USC base is a shared queue property carried by the render refs. r.usc_base, ]; - regs(&mut w[ta::REGS..], &ta::SEL, &val); + let count = stage_regs(&mut w[ta::REGS..], &ta::SEL, &val, rt.scs, 0); put64(w, 4, r.counter[0]); put32(w, 0xc, ctx); put64(w, 0x10, r.notifier); @@ -260,8 +348,8 @@ pub(crate) fn encode_ta_for( put64(w, 0x28, p.scene); put64(w, 0x30, p.scene + 0x100); put64(w, 0x740, p.ta_work_gva + 0x40); - put16(w, 0x748, 66); - put16(w, 0x74a, 66 * 12); + put16(w, 0x748, count); + put16(w, 0x74a, count * 12); put64(w, 0x760, p.tpc_fw); put64(w, ta::TPC_BYTES, geo.tpc_bytes); put64(w, 0x770, p.ta_seq); @@ -340,8 +428,42 @@ pub(crate) fn encode_fs( } /// Encode the 82-record fragment work of `layout`'s ABI and base 0x380 sequence. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_fs_for( + layout: &fs::Layout, + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + usc: u64, + n: u64, + target: u32, + geo: &Geometry, + w: &mut [u8; fs::WORK_SIZE], + q: &mut [u8], +) { + encode_fs_rt( + layout, + r, + p, + u, + ts_va, + ctx, + usc, + n, + target, + geo, + &StageRt::DISABLED, + w, + q, + ) +} + +/// [`encode_fs_for`] with the fragment stage's ray-query words. With [`StageRt::DISABLED`] +/// the bytes are [`encode_fs_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_fs_rt( layout: &fs::Layout, r: &RenderRefs, p: &PassRefs, @@ -352,6 +474,7 @@ pub(crate) fn encode_fs_for( _n: u64, target: u32, geo: &Geometry, + rt: &StageRt, w: &mut [u8; fs::WORK_SIZE], q: &mut [u8], ) { @@ -375,7 +498,7 @@ pub(crate) fn encode_fs_for( u64::from(geo.isp_blocks), u64::from(geo.screen), 0, - 0xff0200, + rt.window | 1 << 9, p.heap_gva & !63, u.isp_scissor_base & !3, u.isp_dbias_base & !3, @@ -423,15 +546,15 @@ pub(crate) fn encode_fs_for( 0x1c, 0, geo.native_tiles, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, 0x6000400020, 0x200000001, u64::from(r.uuid), @@ -441,7 +564,7 @@ pub(crate) fn encode_fs_for( compact(scene_list_va(r, p)), usc, ]; - regs(&mut w[fs::REGS..], &fs::SEL, &val); + let count = stage_regs(&mut w[fs::REGS..], &fs::SEL, &val, rt.scs, 1); put32(w, 0, 1); put64(w, 4, r.counter[1]); put32(w, 0xc, ctx); @@ -459,8 +582,8 @@ pub(crate) fn encode_fs_for( put32(w, 0x68, geo.blocks); put32(w, 0x78, geo.tiles); put64(w, 0x780, p.fs_work_gva + 0x80); - put16(w, 0x788, 82); - put16(w, 0x78a, 82 * 12); + put16(w, 0x788, count); + put16(w, 0x78a, count * 12); put64(w, 0x7a0, u.isp_dbias_base); put64(w, 0x7b0, u.isp_scissor_base); put64(w, 0x7c0, u.isp_oclqry_base); diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 7994d956ac782..26009c05701a5 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -20,7 +20,7 @@ use kernel::{prelude::*, sync::Arc}; use super::channel::Channel; use super::command::{Command, ComputeCommand, RenderCommand}; -use super::encode::{self, ComputeRefs, Geometry, RenderRefs}; +use super::encode::{self, ComputeRefs, ComputeRt, Geometry, RenderRefs, StageRt}; use super::fw::channels::{SubmitRecord, RING_SLOTS}; use super::fw::graph::{notifier_page, qstate}; use super::fw::work::{self, BarrierType}; @@ -330,6 +330,8 @@ pub(crate) struct Flight { pub(crate) initbm: bool, /// Whether this flight publishes CPU-written command timestamps on retirement. pub(crate) has_timestamps: bool, + /// Whether this flight runs ray-tracing or SCS-scratch compute (pinned to compute pipe 0). + pub(crate) rt_compute: bool, } impl Flight { @@ -371,6 +373,7 @@ impl Flight { pb_binding: 0, initbm: false, has_timestamps: false, + rt_compute: false, } } } @@ -1125,14 +1128,17 @@ impl Firmware { // immediately instead of spinning on EAGAIN and stalling unrelated compute. if class_error.is_none() && matches!(command(&job, job.progress.sent()), Some(Command::Render(_))) - && (job + && (job.resources.pb_slot_mask().is_ok_and(|(mask, home)| { + self.pools.exhausted_for_mask_mode( + &job.vm, + mask, + home, + job.resources.render_scs(), + ) + }) || job .resources - .pb_slot_mask() - .is_ok_and(|(mask, home)| self.pools.exhausted_for_mask(&job.vm, mask, home)) - || job - .resources - .render_passes() - .is_ok_and(|n| self.slots.render_exhausted_within(n))) + .render_passes() + .is_ok_and(|n| self.slots.render_exhausted_within(n))) { self.engine.unpend(&job); let _ = job.mark_terminal_retired(); @@ -1294,11 +1300,15 @@ impl Firmware { let cmd = command(job, job.progress.sent()); let is_render = matches!(cmd, Some(Command::Render(_))); let is_compute = matches!(cmd, Some(Command::Compute(_))); + let is_rt_compute = is_compute + && (job.resources.compute_scs() + || matches!(cmd, Some(Command::Compute(c)) if c.is_rt())); job.vm.status.get() != 0 || self.engine.flights.iter().any(|f| { f.doomed || f.recovery_suspect || f.initbm + || (is_rt_compute && f.computes != 0 && f.compute_pipe != 0) || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) @@ -1308,8 +1318,13 @@ impl Firmware { .pb_slot_mask() .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) .is_ok_and(|(mask, home, blocks)| { - self.pools - .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) + self.pools.can_pipeline_in_mask_blocks_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) })) } @@ -1462,8 +1477,13 @@ impl Firmware { .flights .iter() .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let rt_pipe1_busy = (job.resources.compute_scs() || c.is_rt()) + && e.flights + .iter() + .any(|f| f.computes != 0 && f.compute_pipe != 0); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); !cross_vm_render + && !rt_pipe1_busy && !waits_for_timestamps && compute_count < params::compute_flights() && !self.slots.compute_exhausted() @@ -1490,8 +1510,13 @@ impl Firmware { .pb_slot_mask() .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) .is_ok_and(|(mask, home, blocks)| { - self.pools - .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) + self.pools.can_pipeline_in_mask_blocks_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) }) && job .resources @@ -1781,8 +1806,15 @@ impl Firmware { &self, waits: [Option; sizes::COMPUTE_PIPES], units: usize, + rt_compute: bool, ) -> usize { - if units <= super::resources::BASE_COMPUTE_UNITS + if rt_compute + || self + .engine + .flights + .iter() + .any(|fl| fl.computes != 0 && fl.rt_compute) + || units <= super::resources::BASE_COMPUTE_UNITS || !self.slots.compute_available_for_pipe(units, 1) { return 0; @@ -1833,12 +1865,16 @@ impl Firmware { .prepare_pb_in_flight(alloc_slot, draw, render_pipelined)?; let (pb_mask, _) = job.resources.pb_slot_mask()?; let heap_blocks = job.resources.pb_heap_blocks()?; - // Reuse this VM's retired epoch of the allocator slot when still bound and sized for the - // VM's current PB heap (no reseed/InitBM); if the PB heap grew, rotate onto a fresh epoch. - let (epoch, reused) = match self - .pools - .reusable_for_mask(alloc_slot, &job.vm, pb_mask, heap_blocks) - { + let render_scs = job.resources.render_scs(); + // Reuse this VM's retired epoch of the allocator slot when still bound, matching the + // SCS mode, and sized for the VM's current PB heap (no reseed/InitBM). + let (epoch, reused) = match self.pools.reusable_for_mask_mode( + alloc_slot, + &job.vm, + pb_mask, + heap_blocks, + render_scs, + ) { Some(e) => { self.pools.stats.reused += 1; a.init_buffer = false; @@ -1849,10 +1885,11 @@ impl Firmware { return Err(EAGAIN); } let e = job.resources.take_pb()?; - if let Err(err) = e.prepare( + if let Err(err) = e.prepare_with_scs( alloc_slot, job.resources.pb_heap_gva(alloc_slot)?, heap_blocks, + render_scs, ) { job.resources.return_pb(e); return Err(err); @@ -2023,12 +2060,14 @@ impl Firmware { (0usize, [None; sizes::COMPUTE_PIPES]) } else { let units = job.resources.compute_units()?; + let rt_compute = job.resources.compute_scs() + || matches!(cmd, Command::Compute(c) if c.is_rt()); let waits = self.wait_compute_stamps_for( job, job.command_order(index) .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; - (self.choose_compute_pipe(waits, units), waits) + (self.choose_compute_pipe(waits, units, rt_compute), waits) }; let pipe_behind = !render && self @@ -2157,8 +2196,9 @@ impl Firmware { .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) .min(ring_more) .min(pipe_fold_cap); + let rt_head = job.resources.compute_scs() || c.is_rt(); // Fold trailing barrier-free compute commands of the base job first. - while more_slots > 0 && end < job.progress.count() { + while !rt_head && more_slots > 0 && end < job.progress.count() { let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { break; }; @@ -2170,6 +2210,9 @@ impl Firmware { let Some(Command::Compute(c2)) = command(job, end) else { break; }; + if c2.is_rt() { + break; + } self.prefix_compute( job, &job.resources, @@ -2187,7 +2230,7 @@ impl Firmware { // Compute horizon: fold subsequent ready, barrier-free compute-only jobs of // the same queue and VM into the same CDM producer advance and doorbell. // Any non-qualifying job of this queue ends the scan so no later job overtakes it. - if end == job.progress.count() { + if !rt_head && !job.long() && end == job.progress.count() { hz_stop = Some(0); let mut idx = 0; while idx < self.engine.pending.len() { @@ -2208,6 +2251,11 @@ impl Firmware { if !Arc::ptr_eq(&j2.vm, &job.vm) || j2.progress.sent() != 0 || n2 == 0 + || j2.long() + || j2.resources.compute_scs() + || (0..n2).any(|k| { + matches!(command(&j2, k), Some(Command::Compute(c2)) if c2.is_rt()) + }) || !j2.can_fold_horizon_job(first_seq) { hz_stop = Some(3); @@ -2420,6 +2468,8 @@ impl Firmware { break; }; if !Arc::ptr_eq(&j2.vm, &job.vm) + || j2.long() != job.long() + || j2.resources.render_scs() != job.resources.render_scs() || n2 == 0 || n2_usize > more_renders || !j2.can_fold_render_horizon_job(first_seq) @@ -2819,11 +2869,12 @@ impl Firmware { target_stamp: target, submitted, }; + let rt = compute_rt(&cmd.ray, s.seeds); let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; let w = image(&mut scratch.cw)?; // User results are published coherently after the complete retirement receipt. // The firmware's internal timestamp pair remains enabled. - encode::encode_compute_for( + encode::encode_compute_rt( self.init.abi.compute(), &refs, &cmd.cmd, @@ -2832,6 +2883,7 @@ impl Firmware { job.vm.slot, n, 1, + &rt, w, image(&mut scratch.cq)?, ) @@ -2905,6 +2957,7 @@ impl Firmware { f.uma_submitted = submitted; f.csubmitted[member] = submitted; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); + f.rt_compute |= resources.compute_scs() || cmd.is_rt(); wmb(); if let Some((wait_fs, bar_type)) = fs2c_bar { g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; @@ -3051,7 +3104,14 @@ impl Firmware { let heap_blocks = resources.pb_heap_blocks()?; let alloc_slot = self .pools - .pick_slot_in_mask_blocks(&job.vm, behind, pb_mask, pb_home, heap_blocks) + .pick_slot_in_mask_blocks_mode( + &job.vm, + behind, + pb_mask, + pb_home, + heap_blocks, + resources.render_scs(), + ) .ok_or(EAGAIN)?; let slot_pipelined = self.pools.slot_inflight(alloc_slot) > 0; let (refs, init_buffer, epoch, binding) = @@ -3083,7 +3143,8 @@ impl Firmware { geometry.validate_capacity(p.tpc.size as u64, p.tilemap.size as u64)?; resources.set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes, heap_bytes)?; let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; - encode::encode_ta_for( + let [vertex_rt, fragment_rt] = cmd.ray_query.map(|stage| stage_rt(&stage)); + encode::encode_ta_rt( self.init.abi.ta(), &refs, &pass, @@ -3093,10 +3154,11 @@ impl Firmware { target, &geometry, None, + &vertex_rt, image(&mut scratch.ta)?, image(&mut scratch.tas)?, ); - encode::encode_fs_for( + encode::encode_fs_rt( self.init.abi.fs(), &refs, &pass, @@ -3107,6 +3169,7 @@ impl Firmware { draw, target, &geometry, + &fragment_rt, image(&mut scratch.fs)?, &mut scratch.fss[..], ); @@ -3311,3 +3374,35 @@ impl Firmware { self.power.utilization.busy(now); } } + +/// The compute register words of a validated command's ray state ([`super::rt`]) in a unit +/// whose UMA pool has `seeds` freelist entries, in a freelist of +/// [`super::rt::freelist_records`]. Without ray state in a base unit these are the words of +/// [`ComputeRt::DISABLED`]. +fn compute_rt(ray: &super::rt::ComputeRay, seeds: u32) -> ComputeRt { + ComputeRt { + intersection: ray.intersection.words(), + size: ray.scratch.size_word(), + tail: ray.scratch.compute_tail_word(), + stack: ray.scratch.stack_word(), + window: ray.scratch.window_word(), + driver: ray.scratch.driver_word(), + scs: ray.scratch.enabled(), + seeds, + records: super::rt::freelist_records(seeds), + } +} + +/// The TA or FS register words of a validated render stage's ray state. As the M4 Pro's +/// render programs, a stage's tail word is its scratch tail; its auxiliary intersection word +/// is validated but not written. +fn stage_rt(stage: &super::rt::RayQueryStage) -> StageRt { + StageRt { + intersection: stage.intersection.words(), + size: stage.scratch.size_word(), + tail: stage.scratch.tail_word(), + stack: stage.scratch.stack_word(), + window: stage.scratch.window_word(), + scs: stage.scratch.enabled(), + } +} diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index 07317ee4663dc..e0a7b43b677bf 100644 --- a/drivers/gpu/drm/asahi/g16/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g16/fw/buffer.rs @@ -51,6 +51,8 @@ pub(crate) mod uma_manager { pub(crate) const SIZE: usize = 0xa0; pub(crate) const COMPLETED: usize = 0x54; pub(crate) const SEEDS: u32 = 8192; + /// Freelist records of a base pool (+0x1c), its 0x20000-byte freelist. + pub(crate) const RECORDS: u32 = 16384; } pub(crate) mod uma_pools { pub(crate) const POOLS: usize = 16; @@ -116,24 +118,32 @@ pub(crate) fn pb_manager_image( } /// One retained M4 UMA descriptor shared by TA and FS (slot 33..64). +/// A UMA manager whose freelist of `records` records (+0x1c) holds `seeds` entries (available +/// and total): [`uma_manager::SEEDS`] in [`uma_manager::RECORDS`] for a base pool. pub(crate) fn uma_manager_image( descriptor: u64, slot: u32, state_gpu: u64, list_gpu: u64, submitted_fw: u64, + seeds: u32, + records: u32, ) -> [u8; uma_manager::SIZE] { let mut m = [0; uma_manager::SIZE]; put64(&mut m, 0, descriptor); put32(&mut m, 8, slot); put32(&mut m, 0x10, 2); put64(&mut m, 0x14, state_gpu); - put32(&mut m, 0x1c, 16384); - put32(&mut m, 0x24, 8192); - put32(&mut m, 0x2c, 8192); + put32(&mut m, 0x1c, records); + put32(&mut m, 0x24, seeds); + put32(&mut m, 0x2c, seeds); put64(&mut m, 0x30, list_gpu); put32(&mut m, 0x40, 4); - put32(&mut m, 0x48, 128); + put32( + &mut m, + super::graph::manager::ROW_WORDS, + super::graph::pools::row_words(seeds), + ); put64(&mut m, 0x4c, submitted_fw); // +0x54 is the ASC completion count; +0x5c is the compute-exclusion flag. // Both start at zero for paired render engines and are never AP command serials. @@ -217,6 +227,12 @@ mod tests { 0x7012000000, 0x7012020000, 0xfffffc2000700000, + uma_manager::SEEDS, + uma_manager::RECORDS, + ); + assert_eq!( + (r32(&m, 0x1c), r32(&m, 0x24), r32(&m, 0x2c)), + (16384, 8192, 8192) ); assert_eq!(r64(&m, 0), 0xfffffc2000400000); assert_eq!(r32(&m, 8), 33); diff --git a/drivers/gpu/drm/asahi/g16/fw/graph.rs b/drivers/gpu/drm/asahi/g16/fw/graph.rs index e3c95e2756720..80279283a4dab 100644 --- a/drivers/gpu/drm/asahi/g16/fw/graph.rs +++ b/drivers/gpu/drm/asahi/g16/fw/graph.rs @@ -138,6 +138,10 @@ pub(crate) mod manager { pub(crate) const COMPLETED: usize = 0x54; /// ASC compute-exclusion bookkeeping. AP initializes once; never a command serial. pub(crate) const COMPUTE_EXCLUSION: usize = 0x5c; + /// Eight per valid pool-table row ([`super::pools::row_words`]): macOS 27.2 on the J773g + /// writes 8 x rows on every pool (20, 24 and 108 rows seen) and counts a pool's growth + /// in the same unit. A 16-row base pool has 128. + pub(crate) const ROW_WORDS: usize = 0x48; } /// A private 32 MiB UMA pool: 8192 4 KiB freelist entries and sixteen 2 MiB rows. @@ -151,6 +155,13 @@ pub(crate) mod pools { pub(crate) const STATE_BYTES: usize = 0x20000; pub(crate) const TABLE_BYTES: usize = 0x4000; pub(crate) const SEEDS: usize = 8192; + /// [`super::manager::ROW_WORDS`] of a pool of `seeds` entries in whole rows: the u64 words + /// of its valid pool-table rows, eight per 0x40-byte row. + pub(crate) const fn row_words(seeds: u32) -> u32 { + let rows = seeds as u64 * SEED_BYTES / ROW_BYTES; + (rows * (TABLE_STRIDE / core::mem::size_of::()) as u64) as u32 + } + const _: () = assert!(row_words(SEEDS as u32) == 128); } /// The nonzero 25G83 queue header; the rest of the fresh 0x24c0 object remains zero. Keeping diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index 0341c5f6116da..f50fc22164d4c 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -66,9 +66,9 @@ pub(crate) mod compute; pub(crate) mod ta { pub(crate) const WORK_SIZE: usize = 0x940; /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) - /// spans of a TA work image. The intervening zero gap is cleared on full scrubs and skipped - /// on clean same-VM reuse. - pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x360; + /// spans of a TA work image (including two optional SCS register records). The intervening + /// zero gap is cleared on full scrubs and skipped on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x370; pub(crate) const TAIL_ACTIVE_START: usize = 0x740; pub(crate) const SEQ_SIZE: usize = 0x300; pub(crate) const SEQ_OBJECT: usize = 0x1000; @@ -112,7 +112,7 @@ pub(crate) mod ta { && l.auxiliary + 8 <= WORK_SIZE } const _: () = assert!(valid(&V25G83) && valid(&V26B123)); - const _: () = assert!(REGS + SEL.len() * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 66] = [ @@ -130,9 +130,9 @@ pub(crate) mod ta { pub(crate) mod fs { pub(crate) const WORK_SIZE: usize = 0xca0; /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) - /// spans of an FS work image. The intervening zero gap is cleared on full scrubs and skipped - /// on clean same-VM reuse. - pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x460; + /// spans of an FS work image (including two optional SCS register records). The intervening + /// zero gap is cleared on full scrubs and skipped on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x470; pub(crate) const TAIL_ACTIVE_START: usize = 0x780; pub(crate) const SEQ_SIZE: usize = 0x380; pub(crate) const SEQ_OBJECT: usize = 0x1000; @@ -179,7 +179,7 @@ pub(crate) mod fs { && l.flag < WORK_SIZE } const _: () = assert!(valid(&V25G83) && valid(&V26B123)); - const _: () = assert!(REGS + SEL.len() * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 82] = [ diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index 0bde4d35e8860..bb5ccf0ccc846 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -3,10 +3,10 @@ //! J713/G16G 25G83 compute packet layout. All offsets are bytes. pub(crate) const WORK_SIZE: usize = 0x2000; -/// Active head span of a compute work image: header (`0x00..0x18`) plus up to 25 register -/// records (`0x20..0x14c`), rounded up to 16-byte alignment. Bytes between -/// `HEAD_ACTIVE_SIZE` and `BODY_ACTIVE_START` remain zeroed after a full write. -pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x150; +/// Active head span of a compute work image: header (`0x00..0x18`) plus up to 28 register +/// records (`0x20..0x170`, including USC base and RT/SCS records), 16-byte aligned. Bytes +/// between `HEAD_ACTIVE_SIZE` and `BODY_ACTIVE_START` remain zeroed after a full write. +pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x170; /// First active body byte of a compute work image (`work_gva + 0x20` pointer at `0x720`). pub(crate) const BODY_ACTIVE_START: usize = 0x720; /// Exclusive end of the active body span of a compute work image (`0xf00..0xf08` tail). @@ -89,7 +89,7 @@ const fn valid(l: &Layout) -> bool { const _: () = assert!( valid(&V25G83) && valid(&V26B123) - && REGS + 25 * 12 <= HEAD_ACTIVE_SIZE + && REGS + (SEL.len() + 4) * 12 <= HEAD_ACTIVE_SIZE && HEAD_ACTIVE_SIZE <= BODY_ACTIVE_START && BODY_ACTIVE_START <= GENERATION && DESCRIPTOR + DESCRIPTOR_SIZE <= BODY_ACTIVE_END diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 155c8f528abb2..1e80e2303466c 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -573,9 +573,9 @@ pub(crate) mod client { // Persistent compute units reused across application queues. Units 0 and 1 keep their // original 64 MiB placement below the render allocators; extension units (2..COMPUTE_UNITS) - // pack at a 40 MiB stride from 0x7080000000 up to the PB heap (0x70c0000000), clear of the - // dynamic PB page-list range 0x7040000000..0x7080000000 and leaving 7.25 MiB guard above - // each unit's 32.75 MiB footprint (`0x20c0000`). Every alias is inside Mesa's reserved hole. + // pack at a 40 MiB stride from 0x7080000000 up to the SCS compute records (0x70b8000000), + // clear of [`DYNAMIC`] and [`SCS_POOLS`] and leaving 7.25 MiB guard above each unit's + // 32.75 MiB footprint (`0x20c0000`). Every alias is inside Mesa's reserved hole. pub(crate) const EXT_COMPUTE_STRIDE: u64 = 0x02800000; pub(crate) const fn compute_base(k: u64) -> u64 { if k < 2 { @@ -606,6 +606,19 @@ pub(crate) mod client { pub(crate) const WORK_OFF: u64 = 0; pub(crate) const CWORK_STRIDE: u64 = 0x4000; + // SCS-capable compute units (ray-query scratch), one 64 MiB interval each after the last + // compute unit (0x70b7000000) and below the PB heap (0x70c0000000), holding the unit's + // list, preempt, auxiliary and context records at the base units' offsets from their + // state. Its UMA pool and freelist are in its SCS pool window ([`scs_compute_pool`]). + pub(crate) const fn scs_compute_records(k: u64) -> u64 { + 0x70b8000000 + k * 0x04000000 + } + /// Offsets of a compute unit's records from its state. + pub(crate) const COMPUTE_LIST_OFF: u64 = compute_list(0) - compute_state(0); + pub(crate) const COMPUTE_PREEMPT_OFF: u64 = compute_preempt(0) - compute_state(0); + pub(crate) const COMPUTE_AUX_OFF: u64 = compute_aux(0) - compute_state(0); + pub(crate) const COMPUTE_CONTEXT_OFF: u64 = compute_context(0) - compute_state(0); + // Render allocator units contain one 32 MiB UMA pool and its persistent lists in a // 64 MiB stride. Per-VM local slots 0..4 live in 0x7010000000..0x7020000000; local slots // 4..MAX_VM_PB_SLOTS live in 0x7008000000..0x7010000000, above base compute units 0..2 @@ -632,6 +645,29 @@ pub(crate) mod client { pub(crate) const fn render_pb_pages(k: u64) -> u64 { render_base(k) + 0x2040000 } + // SCS-capable render allocators: the list and descriptor in their render unit's interval + // past its records, at the base allocator's offsets from its state. The UMA pool and + // freelist are in the allocator's SCS pool window ([`scs_render_pool`]). + pub(crate) const fn scs_render_records(k: u64) -> u64 { + render_base(k) + 0x2100000 + } + /// Kernel-placed client objects (PB page lists, `Objects::alloc_dynamic_client`). + pub(crate) const DYNAMIC: Range = 0x7040000000..0x7060000000; + /// SCS pool windows, after [`DYNAMIC`] and up to the CT window: each holds one + /// SCS-capable UMA pool and, right after it, its freelist (`rt::window_bytes`). Windows 0 + /// and 1 are the SCS compute units', 2 and 3 the SCS render allocators'. + pub(crate) const SCS_POOLS: u64 = 0x7060000000; + pub(crate) const SCS_POOL_WINDOW: u64 = 0x8000000; + pub(crate) const SCS_POOL_WINDOWS: u64 = 4; + pub(crate) const fn scs_compute_pool(k: u64) -> u64 { + SCS_POOLS + k * SCS_POOL_WINDOW + } + pub(crate) const fn scs_render_pool(k: u64) -> u64 { + SCS_POOLS + (2 + k) * SCS_POOL_WINDOW + } + /// Offsets of a render allocator's records from its state. + pub(crate) const RENDER_LIST_OFF: u64 = render_list(0) - render_state(0); + pub(crate) const RENDER_DESCRIPTOR_OFF: u64 = render_descriptor(0) - render_state(0); pub(crate) const PB_HEAP: u64 = 0x70c0000000; pub(crate) const PB_HEAP_SIZE: u64 = 0x10000000; pub(crate) const fn pb_heap(k: u64) -> u64 { @@ -811,6 +847,45 @@ pub(crate) mod sizes { super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) <= super::engine::RENDER_UMA_SLOT ); + /// SCS-capable compute units per VM, which share ledger indices (and UMA slots) with the + /// first base units. + pub(crate) const SCS_COMPUTE_UNITS: usize = 2; + /// Bytes of a base UMA pool (its seeds of 4 KiB). + pub(crate) const POOL_BYTES: u64 = 0x2000000; + const _: () = assert!( + super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::scs_compute_records(0) + && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64 - 1) + + super::client::COMPUTE_CONTEXT_OFF + + 0x40000 + <= super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) + && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) + <= super::client::PB_HEAP + && super::client::WORK_PAGE + + (COMPUTE_UNITS + SCS_COMPUTE_UNITS) as u64 * super::client::CWORK_STRIDE + <= super::client::compute_base(0) + ); + const _: () = assert!( + super::client::render_pb_pages(0) + super::client::PB_PAGE_LIST_SIZE + <= super::client::scs_render_records(0) + && super::client::scs_render_records(0) + super::client::RENDER_DESCRIPTOR_OFF + 0x4000 + <= super::client::render_base(1) + && super::client::scs_render_records(BASE_PB_SLOTS as u64 - 1) + + super::client::RENDER_DESCRIPTOR_OFF + + 0x4000 + <= super::client::render_base(BASE_PB_SLOTS as u64) + ); + // One window per SCS compute unit and render allocator, between the dynamic range and the + // CT window. + const _: () = assert!( + super::client::DYNAMIC.end <= super::client::scs_compute_pool(0) + && super::client::scs_compute_pool(SCS_COMPUTE_UNITS as u64) + == super::client::scs_render_pool(0) + && super::client::scs_render_pool(BASE_PB_SLOTS as u64) + == super::client::SCS_POOLS + + super::client::SCS_POOL_WINDOWS * super::client::SCS_POOL_WINDOW + && super::client::scs_render_pool(BASE_PB_SLOTS as u64) <= super::client::CT + && super::client::pass_base(RENDER_SLOTS as u64) <= super::client::DYNAMIC.start + ); /// Maximum jobs folded into one barrier-free compute horizon prefix. pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; /// Jobs admitted to the engine per logical queue: enough to keep a queue's commands diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index c52f60a11e2b8..a5dbc19b7d3e9 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -98,6 +98,8 @@ pub(crate) struct Job { pub(crate) vm: Arc, /// Validated commands, in submission order (at most 64). pub(crate) commands: Commands, + /// Any command traces rays or builds acceleration structures (`Command::long`). + long: bool, pub(crate) resources: super::resources::Prepared, /// Immutable dependency/order ledger, one entry for every accepted command. orders: Orders, @@ -151,6 +153,7 @@ impl Job { if commands.len() != orders.len() { return Err(EINVAL); } + let long = commands.iter().any(Command::long); let progress = super::engine::Progress::new(commands.len()); let guard = MappingGuard { guard, @@ -162,6 +165,7 @@ impl Job { queue, vm, commands, + long, orders, resources, fence, @@ -183,6 +187,12 @@ impl Job { ) } + /// The job gets the long execution allowance (ray traversal or acceleration-structure + /// builds, `recovery::logic::LONG_DEADLINE_MS`). + pub(crate) fn long(&self) -> bool { + self.long + } + /// Latches a hardware/publication failure before any later work can be published. /// Called under the device lock; it deliberately does not signal the fence. pub(crate) fn latch_failure(&self, error: Error) { diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 9d12ae3e8df9a..0c870a79c49c0 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -69,6 +69,7 @@ mod queue; mod recovery; mod regs; mod resources; +mod rt; mod sleep; mod slots; mod timestamp; @@ -635,8 +636,8 @@ impl Gpu { let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; let feed = feed::Feed::new()?; let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; - let scrub_queue = slots::ScrubQueue::new_boxed()?; let active_render_vms = Arc::new(AtomicU32::new(0), GFP_KERNEL)?; + let scrub_queue = slots::ScrubQueue::new_boxed()?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 2ebe1a008fbbb..4c94bfb15c44e 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -444,7 +444,7 @@ impl Objects { lower: None, cpu: true, }, - Some(0x7040000000..0x7080000000), + Some(hw::client::DYNAMIC), ) } diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index ed93d1fd6469f..434faf2ee2a04 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -6,8 +6,8 @@ //! SOFT_FAULTS suppressed by `soft_faults`, VDM_USC_INVALIDATE, and `INDEPENDENT_QUEUES` from //! `queue_limits`), G16 advertises per-command input readiness/errors, exact queue-local historical //! prefixes, fragment-only and staged render barriers (`RENDER_STAGE_PREFIXES_V2`), independent -//! logical queues, `FEW_PRIMITIVES`, and `COMPUTE_NO_QUERY_ACCESS`. Ray queries are not -//! advertised. +//! logical queues, `FEW_PRIMITIVES`, `COMPUTE_NO_QUERY_ACCESS`, render ray queries +//! (`RENDER_RAY_QUERY`) and bounded AS builds (`BOUNDED_AS_BUILD`). use kernel::{prelude::*, uapi}; @@ -100,6 +100,8 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_RAY_QUERY) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD) | crate::g17::sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; params.gpu_generation = GPU_GENERATION; diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 8c801b7940461..c08da53d7fac2 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -15,7 +15,8 @@ pub(crate) mod lifetime; use super::fw::buffer::{self, uma_manager}; use super::hw::{client, engine, pte, sizes}; -use super::object::{Class, Factory, FwLease, FwObject, Objects, Placement, Request}; +use super::object::{Class, Factory, FwLease, FwObject, Objects, Request}; +use super::slots::Placement; use super::Firmware; use crate::driver::AsahiDrmDevice; use core::{ @@ -83,6 +84,8 @@ pub(crate) struct PoolSet { heap: Arc, /// Blocks of the shared heap (the PB managers' lists cover the whole 256 MiB window). heap_blocks: u32, + /// Freelist entries of every allocator's UMA pool. + seeds: u32, } fn alloc( @@ -95,7 +98,7 @@ fn alloc( o.alloc(Request { size, class, - placement: Placement::Anywhere, + placement: super::object::Placement::Anywhere, offset: 0, client, lower: None, @@ -135,14 +138,14 @@ fn write_records( } impl Allocator { /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. - #[allow(dead_code)] pub(crate) fn new( o: &mut Objects, fw_factory: &Factory, k: u64, heap: &Arc, + placement: Placement, ) -> Result { - Self::new_at(o, fw_factory, k, k as u32, heap) + Self::new_at(o, fw_factory, k, k as u32, heap, placement) } /// Render allocator mapped at per-VM local VA index `local_idx` (`0..MAX_VM_PB_SLOTS`) /// and bound to device-wide hardware slot `hw_slot` (`parameter_id`, UMA slot @@ -153,10 +156,30 @@ impl Allocator { local_idx: u64, hw_slot: u32, heap: &Arc, + placement: Placement, ) -> Result { + placement.check()?; if local_idx >= sizes::MAX_VM_PB_SLOTS as u64 || (hw_slot as usize) >= sizes::PB_SLOTS { return Err(EINVAL); } + let (pool_va, state_va, freelist_va) = match placement { + Placement::Base => ( + client::render_pool(local_idx), + client::render_state(local_idx), + client::render_state(local_idx), + ), + Placement::Scs { .. } => { + if local_idx >= sizes::BASE_PB_SLOTS as u64 { + return Err(EINVAL); + } + let pool = client::scs_render_pool(local_idx); + ( + pool, + client::scs_render_records(local_idx), + pool + placement.pool_bytes() as u64, + ) + } + }; let nc = |va| Some((va, pte::LEAF_NC)); // Native UMA software metadata is ASC-owned and never needs a client GPU alias. // Keep descriptor + submitted in a VM-free FwLease so firmware's global UMA table @@ -169,32 +192,26 @@ impl Allocator { o, 0x4000, Class::Shared, - nc(client::render_descriptor(local_idx)), - false, - )?; - let pool = alloc( - o, - 0x2000000, - Class::Shared, - nc(client::render_pool(local_idx)), + nc(state_va + client::RENDER_DESCRIPTOR_OFF), false, )?; + let pool = alloc(o, placement.pool_bytes(), Class::Shared, nc(pool_va), false)?; let state = alloc( o, - 0x20000, + placement.freelist_bytes(), Class::Shared, - nc(client::render_state(local_idx)), + nc(freelist_va), true, )?; let list = alloc( o, 0x4000, Class::Shared, - nc(client::render_list(local_idx)), + nc(state_va + client::RENDER_LIST_OFF), true, )?; let heap = heap.clone(); - super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; + super::slots::init_uma_pool(&state, &list, gva(&pool)?, placement.seeds())?; descriptor.write( 0, &buffer::uma_manager_image( @@ -203,6 +220,8 @@ impl Allocator { gva(&state)?, gva(&list)?, submitted.va, + placement.seeds(), + super::rt::freelist_records(placement.seeds()), ), )?; Ok(Self { @@ -341,7 +360,14 @@ impl PoolSet { let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; for (local, &hw_slot) in slots.iter().enumerate() { units.push( - Allocator::new_at(o, fw_factory, local as u64, hw_slot as u32, &heap)?, + Allocator::new_at( + o, + fw_factory, + local as u64, + hw_slot as u32, + &heap, + Placement::Base, + )?, GFP_KERNEL, )?; } @@ -349,8 +375,33 @@ impl PoolSet { units, heap, heap_blocks, + seeds: Placement::Base.seeds(), + }) + } + /// The SCS-capable allocators of this set's VM (ray-query scratch): one per base PB slot, + /// sharing this set's PB heap and hardware slot IDs, each with a pool of `seeds` entries + /// ([`super::rt::pool_seeds`]). PB epoch reuse keeps base and SCS bindings strictly disjoint. + pub(crate) fn scs(&self, o: &mut Objects, fw_factory: &Factory, seeds: u32) -> Result { + let heap = self.heap.clone(); + let placement = Placement::Scs { seeds }; + let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; + for (local, unit) in self.units.iter().enumerate() { + units.push( + Allocator::new_at(o, fw_factory, local as u64, unit.id(), &heap, placement)?, + GFP_KERNEL, + )?; + } + Ok(Self { + units, + heap, + heap_blocks: self.heap_blocks, + seeds, }) } + /// Freelist entries of the set's UMA pools. + pub(crate) fn seeds(&self) -> u32 { + self.seeds + } #[allow(dead_code)] pub(crate) fn unit(&self, k: usize) -> Option<&Allocator> { self.units.get(k) @@ -556,60 +607,87 @@ impl Pools { (Arc::ptr_eq(&owner._vm, vm) && owner.exposed.load(Ordering::Acquire)) .then(|| owner.clone()) } - /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// Like [`Self::reusable`], but also requires the retired epoch's SCS mode to match + /// `want_scs` so a base render and an SCS render never share an active UMA descriptor slot. + pub(crate) fn reusable_mode( + &self, + k: usize, + vm: &Arc, + want_scs: bool, + ) -> Option> { + self.reusable(k, vm) + .filter(|owner| owner.scs() == want_scs) + } + /// Like [`Self::reusable_mode`], but forces a fresh `InitBM` epoch when the VM's PB heap grew /// past the retired epoch's `heap_blocks` and a displaced slot in `slot_mask` is available /// to rotate onto safely. - pub(crate) fn reusable_for_mask( + pub(crate) fn reusable_for_mask_mode( &self, k: usize, vm: &Arc, slot_mask: u32, min_blocks: u32, + want_scs: bool, ) -> Option> { if k >= sizes::PB_SLOTS || (slot_mask & (1u32 << k)) == 0 { return None; } - let owner = self.reusable(k, vm)?; + let owner = self.reusable_mode(k, vm, want_scs)?; if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_in_mask(slot_mask) { Some(owner) } else { None } } - /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// Like [`Self::reusable_mode`], but forces a fresh `InitBM` epoch when the VM's PB heap grew /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available /// to rotate onto safely. #[allow(dead_code)] - pub(crate) fn reusable_for_within( + pub(crate) fn reusable_for_within_mode( &self, k: usize, vm: &Arc, limit: usize, min_blocks: u32, + want_scs: bool, ) -> Option> { - let owner = self.reusable(k, vm)?; + let owner = self.reusable_mode(k, vm, want_scs)?; if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_within(limit) { Some(owner) } else { None } } - /// Selects a physical PB/UMA allocator slot in `slot_mask` for `vm`, preferring `home` when - /// claiming an unused warm slot (`0..WARM_PB_SLOTS`) so up to `WARM_PB_SLOTS` concurrent VMs - /// bind disjoint warm slots regardless of arrival order. - pub(crate) fn pick_slot_in_mask_blocks( + /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available + /// to rotate onto safely. + #[allow(dead_code)] + pub(crate) fn reusable_for_within( + &self, + k: usize, + vm: &Arc, + limit: usize, + min_blocks: u32, + ) -> Option> { + self.reusable_for_within_mode(k, vm, limit, min_blocks, false) + } + /// Selects a physical PB/UMA allocator slot in `slot_mask` for `vm` and `want_scs`, + /// preferring `home` when claiming an unused warm slot (`0..WARM_PB_SLOTS`) so up to + /// `WARM_PB_SLOTS` concurrent VMs bind disjoint warm slots regardless of arrival order. + pub(crate) fn pick_slot_in_mask_blocks_mode( &self, vm: &Arc, behind: bool, slot_mask: u32, home: usize, min_blocks: u32, + want_scs: bool, ) -> Option { let in_mask = |k: usize| k < sizes::PB_SLOTS && (slot_mask & (1u32 << k)) != 0; if let Some(a) = self.active { if in_mask(a) && self - .reusable_for_mask(a, vm, slot_mask, min_blocks) + .reusable_for_mask_mode(a, vm, slot_mask, min_blocks, want_scs) .is_some() { return Some(a); @@ -618,7 +696,7 @@ impl Pools { if let Some(k) = (0..sizes::PB_SLOTS).find(|&k| { in_mask(k) && self - .reusable_for_mask(k, vm, slot_mask, min_blocks) + .reusable_for_mask_mode(k, vm, slot_mask, min_blocks, want_scs) .is_some() }) { return Some(k); @@ -655,56 +733,68 @@ impl Pools { .find(|&k| in_mask(k) && self.slot_displaced(k)) }) } - /// Whether `vm` has a warm reusable PB slot in `slot_mask` covering `min_blocks` so it can - /// pipeline without InitBM. - pub(crate) fn can_pipeline_in_mask_blocks( + /// Whether `vm` has a warm reusable PB slot in `slot_mask` matching `want_scs` and + /// covering `min_blocks` so it can pipeline without InitBM. + pub(crate) fn can_pipeline_in_mask_blocks_mode( &self, vm: &Arc, slot_mask: u32, home: usize, min_blocks: u32, + want_scs: bool, ) -> bool { - self.pick_slot_in_mask_blocks(vm, true, slot_mask, home, min_blocks) + self.pick_slot_in_mask_blocks_mode(vm, true, slot_mask, home, min_blocks, want_scs) .is_some() } - /// Whether no allocator slot in `slot_mask` can accept a render for `vm` once drained. - pub(crate) fn exhausted_for_mask( + /// Whether no allocator slot in `slot_mask` can accept a render for `vm` and `want_scs` + /// once drained. + pub(crate) fn exhausted_for_mask_mode( &self, vm: &Arc, slot_mask: u32, home: usize, + want_scs: bool, ) -> bool { self.inflight.iter().all(|&c| c == 0) && self - .pick_slot_in_mask_blocks(vm, false, slot_mask, home, 0) + .pick_slot_in_mask_blocks_mode(vm, false, slot_mask, home, 0, want_scs) .is_none() } - /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused - /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm` and `want_scs`, + /// requiring any reused epoch to match `want_scs` and cover at least `min_blocks` when a + /// displaced slot is available for rotation. /// /// When `behind` is true (pipelining behind active flights), only a healthy warm reusable - /// slot already bound to `vm` (preferring `self.active`, then any other slot in `0..limit`) - /// is eligible; cold VMs or VMs whose PB heap expanded return `None` so the engine drains - /// once before rotating onto a fresh `InitBM` epoch. + /// slot already bound to `vm` with matching SCS mode (preferring `self.active`, then any + /// other slot in `0..limit`) is eligible; cold VMs, base<->SCS transitions, or VMs whose PB + /// heap expanded return `None` so the engine drains once before rotating onto a fresh + /// `InitBM` epoch. /// When `behind` is false (engine drained), a qualifying warm reusable slot for `vm` is /// preferred; otherwise an already-used displaced slot is chosen first (preserving the 2-slot /// working set) or the lowest fresh slot is claimed. #[allow(dead_code)] - pub(crate) fn pick_slot_within_blocks( + pub(crate) fn pick_slot_within_blocks_mode( &self, vm: &Arc, behind: bool, limit: usize, min_blocks: u32, + want_scs: bool, ) -> Option { let n = limit.min(sizes::PB_SLOTS); if let Some(a) = self.active { - if a < n && self.reusable_for_within(a, vm, n, min_blocks).is_some() { + if a < n + && self + .reusable_for_within_mode(a, vm, n, min_blocks, want_scs) + .is_some() + { return Some(a); } } - if let Some(k) = (0..n).find(|&k| self.reusable_for_within(k, vm, n, min_blocks).is_some()) - { + if let Some(k) = (0..n).find(|&k| { + self.reusable_for_within_mode(k, vm, n, min_blocks, want_scs) + .is_some() + }) { return Some(k); } if behind { @@ -715,6 +805,18 @@ impl Pools { .find(|&k| self.slot_displaced(k) && self.owners[k].is_some()) .or_else(|| (0..n).find(|&k| self.slot_displaced(k))) } + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused + /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. + #[allow(dead_code)] + pub(crate) fn pick_slot_within_blocks( + &self, + vm: &Arc, + behind: bool, + limit: usize, + min_blocks: u32, + ) -> Option { + self.pick_slot_within_blocks_mode(vm, behind, limit, min_blocks, false) + } /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. #[allow(dead_code)] pub(crate) fn pick_slot_within( @@ -730,6 +832,19 @@ impl Pools { pub(crate) fn pick_slot(&self, vm: &Arc, behind: bool) -> Option { self.pick_slot_within(vm, behind, sizes::PB_SLOTS) } + /// Whether `vm` has a warm reusable PB slot within `0..limit` matching `want_scs` and + /// covering `min_blocks` so it can pipeline without InitBM. + #[allow(dead_code)] + pub(crate) fn can_pipeline_within_blocks_mode( + &self, + vm: &Arc, + limit: usize, + min_blocks: u32, + want_scs: bool, + ) -> bool { + self.pick_slot_within_blocks_mode(vm, true, limit, min_blocks, want_scs) + .is_some() + } /// Whether `vm` has a warm reusable PB slot within `0..limit` covering `min_blocks` and can /// pipeline without InitBM. #[allow(dead_code)] @@ -739,8 +854,7 @@ impl Pools { limit: usize, min_blocks: u32, ) -> bool { - self.pick_slot_within_blocks(vm, true, limit, min_blocks) - .is_some() + self.can_pipeline_within_blocks_mode(vm, limit, min_blocks, false) } /// Whether `vm` has a warm reusable PB slot within `0..limit` and can pipeline without InitBM. #[allow(dead_code)] @@ -769,6 +883,20 @@ impl Pools { } !(0..sizes::PB_SLOTS).any(|k| self.slot_displaced(k)) } + /// Whether no allocator slot within `0..limit` can accept a render for `vm` and `want_scs` + /// once drained. + #[allow(dead_code)] + pub(crate) fn exhausted_for_within_mode( + &self, + vm: &Arc, + limit: usize, + want_scs: bool, + ) -> bool { + self.inflight.iter().all(|&c| c == 0) + && self + .pick_slot_within_blocks_mode(vm, false, limit, 0, want_scs) + .is_none() + } /// Whether no allocator slot within `0..limit` can accept a render for `vm` once drained. /// /// When a VM prepared fewer PB slots than needed after a render hang (or when only one @@ -776,7 +904,7 @@ impl Pools { /// instead of spinning on `EAGAIN` until the administrative publication deadline fails the GPU. #[allow(dead_code)] pub(crate) fn exhausted_for_within(&self, vm: &Arc, limit: usize) -> bool { - self.inflight.iter().all(|&c| c == 0) && self.pick_slot_within(vm, false, limit).is_none() + self.exhausted_for_within_mode(vm, limit, false) } /// Whether no allocator slot can accept a render for `vm` once the engine is drained. #[allow(dead_code)] @@ -992,6 +1120,7 @@ pub(crate) struct PbEpochInner { /// High-water block count previously written into the zero-allocated `pages`/`blocks` lists, /// so fresh `InitBM` seeding writes only the active prefix (plus any shrink tail). seeded_blocks: AtomicU32, + scs: AtomicBool, exposed: AtomicBool, /// VM-free firmware lease keeping `records` (`manager`, `ring`, `counter`, `misc`, `initbm`) /// mapped across closed-VM reclaim until a newer `InitBM` overwrites `pb_mgr_table[k]`. @@ -1023,6 +1152,7 @@ impl PbEpoch { assigned: AtomicU32::new(u32::MAX), heap_blocks: AtomicU32::new(0), seeded_blocks: AtomicU32::new(0), + scs: AtomicBool::new(false), exposed: AtomicBool::new(false), records_lease, _objects: o, @@ -1043,7 +1173,20 @@ impl PbEpoch { /// Seed only unpublished storage. A retry may choose another physical slot; after /// exposure neither the manager nor any of its firmware-mutated lists is reset. + #[allow(dead_code)] pub(crate) fn prepare(&self, k: usize, heap: u64, heap_blocks: u32) -> Result { + self.prepare_with_scs(k, heap, heap_blocks, false) + } + + /// Like [`Self::prepare`], recording whether this epoch is bound to the VM's SCS-capable + /// render allocators (`scs == true`) or its base allocators (`scs == false`). + pub(crate) fn prepare_with_scs( + &self, + k: usize, + heap: u64, + heap_blocks: u32, + scs: bool, + ) -> Result { if k >= sizes::PB_SLOTS || self.exposed.load(Ordering::Acquire) || heap_blocks == 0 @@ -1085,11 +1228,15 @@ impl PbEpoch { self.seeded_blocks.store(heap_blocks, Ordering::Release); self.assigned.store(k as u32, Ordering::Release); self.heap_blocks.store(heap_blocks, Ordering::Release); + self.scs.store(scs, Ordering::Release); Ok(()) } pub(crate) fn heap_blocks(&self) -> u32 { self.heap_blocks.load(Ordering::Acquire) } + pub(crate) fn scs(&self) -> bool { + self.scs.load(Ordering::Acquire) + } pub(crate) fn check_assignment(&self, k: usize) -> Result { if self.assigned.load(Ordering::Acquire) != k as u32 { return Err(EINVAL); diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index f8e8462a063f1..0b83aef27f1dc 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -10,8 +10,12 @@ //! process (such as a compositor). It reserves no hardware graph or execution context. //! QUEUE_CREATE validates //! `usc_exec_base` (4 GiB aligned, the window inside the user range) and refuses a failed VM or -//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. Ray-query scratch layouts are -//! refused by the shared default `reserve_render_scs` (RENDER_RAY_QUERY is never advertised). +//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. `render_scs_layout` (the +//! largest ray-query scratch layouts of the queue's render stages) is reserved at creation: +//! EINVAL for a malformed layout, E2BIG beyond the largest SCS-capable UMA pool; a render +//! whose scratch exceeds the reservation is refused (EINVAL), as on the M4 Pro. The +//! reservation also sizes the SCS-capable render pools its VM creates for it +//! ([`super::rt::pool_seeds`]). //! //! QUEUE_DESTROY (dropping the queue) drains: the scheduler entity is torn down first, which //! waits (killable) until every accepted job has been handed to the engine; the engine then runs @@ -156,6 +160,10 @@ pub(crate) struct Queue { vm: Arc, shared: Arc, timeline: Arc, + /// Enabled GPU cores, which SCS memory is sized for. + active_cores: u32, + /// Reserved render scratch pages per stage (`render_scs_layout`). + render_scs: [u16; 2], // Last field: all preceding fields (especially scheduler) drop before capacity returns. _credit: QueueCredit, } @@ -216,6 +224,8 @@ impl Queue { vm: vm_state, shared: gpu.shared.clone(), timeline, + active_cores: gpu.id.core_masks.iter().map(|mask| mask.count_ones()).sum(), + render_scs: [0; 2], _credit: credit, }) } @@ -246,6 +256,8 @@ impl Queue { &command::Context { vm: &self.vm.vm, usc_base: self.state.usc_base, + active_cores: self.active_cores, + render_scs: self.render_scs, }, &mut self.proof, )?; @@ -321,6 +333,22 @@ impl Queue { } impl crate::queue::Queue for Queue { + /// RENDER_RAY_QUERY: the largest scratch layouts of the queue's vertex and fragment stages. + /// A render's UMA pool serves both stages of one render at a time, so their extra pages add + /// up ([`super::rt::required_seeds`]). + fn reserve_render_scs(&mut self, layouts: [u64; 2]) -> Result { + if self.accepted != [0; 2] { + return Err(EBUSY); + } + let pages = [ + super::rt::ScratchRequest::new(layouts[0])?.pages(), + super::rt::ScratchRequest::new(layouts[1])?.pages(), + ]; + super::rt::required_seeds(self.active_cores, &pages)?; + self.render_scs = pages; + Ok(()) + } + fn submit( &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 8e9b9a61e3bab..e641735511142 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -51,8 +51,8 @@ pub(crate) fn push_completion(done: &mut Completions, job: &Arc, result: Re } pub(crate) struct Recovery { - pub(crate) deadline_ns: u64, - pub(crate) compute_deadline_ns: u64, + /// Per-class host deadlines, ordinary and long-job ([`logic::Deadlines`]). + pub(crate) deadlines: logic::Deadlines, /// Per-class (render, compute) long-command warning deadlines; diagnostic only. warning_deadline_ns: [u64; 2], pub(crate) long_commands: u64, @@ -79,8 +79,7 @@ pub(crate) struct Recovery { impl Recovery { pub(crate) fn new() -> Self { Self { - deadline_ns: logic::EXPIRED, - compute_deadline_ns: logic::EXPIRED, + deadlines: logic::Deadlines::EXPIRED, warning_deadline_ns: [u64::MAX; 2], long_commands: 0, publication_wait_deadline: None, @@ -116,15 +115,18 @@ impl Firmware { pub(crate) fn renew_render_deadline(&mut self) { let now = now_ns(); - self.recovery.deadline_ns = logic::renew(now, params::deadline_ms(), 0).0; + let renewed = logic::Deadlines::renew(now, params::deadline_ms(), 0); + self.recovery.deadlines.any = renewed.any; + self.recovery.deadlines.long_any = renewed.long_any; self.recovery.warning_deadline_ns[super::command::RENDER] = now.saturating_add(5_000_000_000); } pub(crate) fn renew_compute_deadline(&mut self) { let now = now_ns(); - self.recovery.compute_deadline_ns = - logic::renew(now, 0, params::compute_deadline_ms()).1; + let renewed = logic::Deadlines::renew(now, 0, params::compute_deadline_ms()); + self.recovery.deadlines.compute = renewed.compute; + self.recovery.deadlines.long_compute = renewed.long_compute; self.recovery.warning_deadline_ns[super::command::COMPUTE] = now.saturating_add(5_000_000_000); } @@ -206,6 +208,16 @@ impl Firmware { .flights .iter() .any(|flight| flight.computes != 0); + let has_long_render = self + .engine + .flights + .iter() + .any(|flight| flight.renders != 0 && flight.job.long()); + let has_long_compute = self + .engine + .flights + .iter() + .any(|flight| flight.computes != 0 && flight.job.long()); if has_render && logic::expired( now, @@ -232,8 +244,11 @@ impl Firmware { "M4 GPU compute command has no completion-stamp progress for 5s; execution may still be active\n" ); } - if (has_render && logic::expired(now, self.recovery.deadline_ns)) - || (has_compute && logic::expired(now, self.recovery.compute_deadline_ns)) + // Ray traversal and AS builds: every flight of such a job (`Job::long`). + let render_deadline = self.recovery.deadlines.select(false, has_long_render); + let compute_deadline = self.recovery.deadlines.select(true, has_long_compute); + if (has_render && logic::expired(now, render_deadline)) + || (has_compute && logic::expired(now, compute_deadline)) { dev_err!( self.dev(), diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index f93b2cd35f4ff..528760bb1654d 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -182,6 +182,67 @@ pub(crate) fn renew(now: u64, deadline_ms: u32, compute_deadline_ms: u32) -> (u6 ) } +/// Ray traversal and acceleration-structure builds can run past one administrative deadline +/// (CTS stress). As on the M4 Pro (g17 `timeout::select`: two-second polls plus four extra +/// ones), a job with such a command gets at least ten seconds per flight. Still bounded: +/// this is an allowance, not evidence of GPU progress. +pub(crate) const LONG_DEADLINE_MS: u32 = 10_000; + +/// The administrative deadline of a long job, ms: at least [`LONG_DEADLINE_MS`], unless the +/// deadline is disabled (zero). +pub(crate) const fn long_deadline_ms(milliseconds: u32) -> u32 { + if milliseconds == 0 || milliseconds >= LONG_DEADLINE_MS { + milliseconds + } else { + LONG_DEADLINE_MS + } +} + +/// The four host deadlines renewed together: ordinary and compute-only, each plain and for a +/// long job. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Deadlines { + pub(crate) any: u64, + pub(crate) compute: u64, + pub(crate) long_any: u64, + pub(crate) long_compute: u64, +} + +impl Deadlines { + pub(crate) const EXPIRED: Self = Self { + any: EXPIRED, + compute: EXPIRED, + long_any: EXPIRED, + long_compute: EXPIRED, + }; + + /// All four from `now`. + pub(crate) fn renew(now: u64, deadline_ms: u32, compute_deadline_ms: u32) -> Self { + let (any, compute) = renew(now, deadline_ms, compute_deadline_ms); + let (long_any, long_compute) = renew( + now, + long_deadline_ms(deadline_ms), + long_deadline_ms(compute_deadline_ms), + ); + Self { + any, + compute, + long_any, + long_compute, + } + } + + /// The deadline of the oldest flight: compute-only or not, of a long job or not. + pub(crate) const fn select(&self, compute_only: bool, long: bool) -> u64 { + match (compute_only, long) { + (true, false) => self.compute, + (false, false) => self.any, + (true, true) => self.long_compute, + (false, true) => self.long_any, + } + } +} + /// Zero explicitly opts long-running work out of the host's administrative watchdog. /// Completion stamps cannot distinguish a running shader from a firmware-silent hang. fn host_deadline(now: u64, milliseconds: u32) -> u64 { diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index c3b5d0acfed90..84d5623728910 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -9,7 +9,7 @@ use super::{ command::Command, object::{Factory, Objects}, pools::{PbEpoch, PoolSet}, - slots::{ComputeSlot, PassSlot}, + slots::{ComputeSlot, PassSlot, Placement}, vm::VmState, }; use crate::mmu; @@ -17,7 +17,7 @@ use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use kernel::{ new_condvar, new_mutex, new_spinlock_irq, prelude::*, - sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SpinLockIrq}, + sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SetOnce, SpinLockIrq}, }; /// Never-exposed PB epochs an open VM keeps on standby after bursts drain. @@ -55,17 +55,22 @@ const BURST_GAP_NS: u64 = 2_000_000; const BURST_COMMANDS: usize = 3; impl ComputeArena { - /// Allocates one self-contained compute unit `k` (its index fixes its client addresses and - /// hardware UMA slot). + /// Freelist entries of the unit's UMA pool. + pub(crate) fn seeds(&self) -> u32 { + self.unit.seeds + } + /// Allocates one self-contained compute unit `k` (its index and `placement` fix its client + /// addresses; the index fixes its hardware UMA slot). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, k: usize, + placement: Placement, ) -> Result> { let mut objects = factory.objects(vm); - let unit = ComputeSlot::new(&mut objects, factory, k as u64)?; + let unit = ComputeSlot::new_in(&mut objects, factory, k as u64, placement)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { @@ -88,18 +93,20 @@ pub(crate) struct ComputeUnitSet { units: KVec>, } impl ComputeUnitSet { - /// Units `range` (each index fixes its client addresses and hardware UMA slot). + /// Units `range` (each index and `placement` fix its client addresses; the index fixes its + /// hardware UMA slot). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, range: core::ops::Range, + placement: Placement, ) -> Result> { let mut units = KVec::with_capacity(range.len(), GFP_KERNEL)?; for k in range { units.push( - ComputeArena::new(factory, bind, vm, live, k)?, + ComputeArena::new(factory, bind, vm, live, k, placement)?, GFP_KERNEL, )?; } @@ -108,6 +115,10 @@ impl ComputeUnitSet { fn len(&self) -> usize { self.units.len() } + /// Freelist entries of the set's UMA pools (all its units share a placement). + pub(crate) fn seeds(&self) -> u32 { + self.units.first().map_or(0, |arena| arena.seeds()) + } fn unit(&self, idx: usize) -> Option<&ComputeSlot> { self.units.get(idx).map(|arena| &arena.unit) } @@ -302,11 +313,20 @@ impl core::ops::Deref for RenderArena { &self.0 } } +/// The SCS-capable render allocators of a render arena and the mappings they own. +pub(crate) struct ScsPools { + pub(crate) pools: PoolSet, + _objects: Objects, +} + pub(crate) struct RenderInner { pub(crate) passes: KVec, pub(crate) pools: PoolSet, /// Device-wide physical PB/UMA allocator slots `[home, alt]` bound to `pools.unit(0..2)`. pub(crate) base_pb_slots: [usize; BASE_PB_SLOTS], + /// [`PoolSet::scs`], with the VM's first render that has scratch. Held with the arena, so + /// a pass slot's owner lease keeps it too. Dropped before the arena's own mappings. + pub(crate) scs: SetOnce, pub(crate) tpc_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_last: [AtomicU64; BASE_RENDER_SLOTS], @@ -345,6 +365,7 @@ impl RenderArena { passes, pools, base_pb_slots, + scs: SetOnce::new(), tpc_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_last: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], @@ -357,6 +378,30 @@ impl RenderArena { GFP_KERNEL, )?) } + /// Creates the SCS-capable render allocators with pools of `seeds.pool` entries unless + /// they exist. Existing ones must hold `seeds.needed`: once the hardware may hold them they + /// cannot grow (E2BIG). Called under the VM cache's construction mutex, before any job uses + /// them. + fn ensure_scs(&self, factory: &Factory, vm: &mmu::Vm, seeds: super::rt::ScsSeeds) -> Result { + if let Some(scs) = self.scs.as_ref() { + return if scs.pools.seeds() >= seeds.needed { + Ok(()) + } else { + Err(E2BIG) + }; + } + let mut objects = factory.objects(vm); + let pools = self.pools.scs(&mut objects, factory, seeds.pool)?; + objects.finish_private()?; + // The construction mutex excludes a second populate. + if !self.scs.populate(ScsPools { + pools, + _objects: objects, + }) { + return Err(EBUSY); + } + Ok(()) + } pub(crate) fn set_dirty(&self, k: usize, tpc: u64, tilemap: u64) -> Result { let pass = self.passes.get(k).ok_or(EINVAL)?; if tpc > pass.tpc.size as u64 || tilemap > pass.tilemap.size as u64 { @@ -468,6 +513,7 @@ impl PoolExtArena { local_idx as u64, hw_slot as u32, heap, + Placement::Base, )?; objects.finish_private()?; Ok(Arc::new( @@ -583,6 +629,8 @@ struct Ready { compute: Option>, /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. compute_ext: Option>, + /// SCS-capable units, for jobs with compute scratch. + compute_scs: Option>, render: Option>, /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). render_ext: [Option>; EXT_RENDER_TIERS.len()], @@ -778,6 +826,7 @@ impl Cache { ( ready.compute.take(), ready.compute_ext.take(), + ready.compute_scs.take(), ready.render.take(), core::mem::take(&mut ready.render_ext), core::mem::take(&mut ready.pb_heap_ext), @@ -804,6 +853,22 @@ impl Cache { .count() .try_into()?; let render = render_count != 0; + // Scratch is sized on top of a pool's base pages: such a job runs on SCS-capable + // storage, for all its commands of that engine, whose pools hold the largest of them. + let scs = |engine: fn(&Command) -> bool| { + commands + .iter() + .filter(|&c| engine(c)) + .map(Command::scs) + .fold(super::rt::ScsSeeds::NONE, |a, b| super::rt::ScsSeeds { + needed: a.needed.max(b.needed), + pool: a.pool.max(b.pool).max(b.needed), + }) + }; + let compute_seeds = scs(|c| matches!(c, Command::Compute(_))); + let render_seeds = scs(|c| matches!(c, Command::Render(_))); + let compute_scs = compute_seeds.needed != 0; + let render_scs = render_seeds.needed != 0; let (compute, compute_ext, render_arena, render_ext, pb_heap_ext, pb_ext) = { // Never held by publication, completion, recovery, fence signalling or // standby waits, so Cache::close() and same-VM compute SUBMITs never block. @@ -811,16 +876,36 @@ impl Cache { if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { return Err(EIO); } - if compute && ready.compute.is_none() { + if compute && !compute_scs && ready.compute.is_none() { ready.compute = Some(ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, &self.live, 0..BASE_COMPUTE_UNITS, + Placement::Base, )?); } - if compute && ready.compute_ext.is_none() { + if compute_scs { + match ready.compute_scs.as_ref().map(|set| set.seeds()) { + None => { + ready.compute_scs = Some(ComputeUnitSet::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + 0..super::hw::sizes::SCS_COMPUTE_UNITS, + Placement::Scs { + seeds: compute_seeds.pool, + }, + )?); + } + // The units cannot grow once the hardware may hold them. + Some(seeds) if seeds < compute_seeds.needed => return Err(E2BIG), + Some(_) => {} + } + } + if compute && !compute_scs && ready.compute_ext.is_none() { let units = super::params::compute_units(); if units > BASE_COMPUTE_UNITS { // SAFETY: ktime_get has no preconditions. @@ -840,6 +925,7 @@ impl Cache { &vm.vm, &self.live, BASE_COMPUTE_UNITS..units, + Placement::Base, ) .ok(); } @@ -861,6 +947,13 @@ impl Cache { ready.render_vm_counter = Some(hints.active_render_vms.clone()); } } + if render_scs { + ready.render.as_ref().ok_or(EINVAL)?.ensure_scs( + &self.factory, + &vm.vm, + render_seeds, + )?; + } if render { if let Some(base) = ready.render.as_ref() { let quarantined = hints.quarantined_pb_mask; @@ -1000,8 +1093,16 @@ impl Cache { [const { None }; EXT_PB_SLOTS] }; ( - if compute { ready.compute.clone() } else { None }, - if compute { ready.compute_ext.clone() } else { None }, + match (compute, compute_scs) { + (true, true) => ready.compute_scs.clone(), + (true, false) => ready.compute.clone(), + (false, _) => None, + }, + if compute && !compute_scs { + ready.compute_ext.clone() + } else { + None + }, if render { ready.render.clone() } else { None }, render_ext, pb_heap_ext, @@ -1102,7 +1203,9 @@ impl Cache { Ok(Prepared { compute, compute_ext, + compute_scs, render: render_arena, + render_scs, render_ext, pb_heap_ext, pb_ext, @@ -1118,7 +1221,11 @@ pub(crate) struct Prepared { pub(crate) compute: Option>, /// The VM's extension compute units when the job was prepared. pub(crate) compute_ext: Option>, + /// The job's computes use the VM's SCS-capable compute arena (`0..SCS_COMPUTE_UNITS`). + compute_scs: bool, pub(crate) render: Option>, + /// The job's renders use the arena's SCS-capable allocators (`render.scs`). + render_scs: bool, /// The VM's demand-grown extension render pass tiers when the job was prepared. pub(crate) render_ext: [Option>; EXT_RENDER_TIERS.len()], /// The VM's demand-grown contiguous PB heap extension tiers when the job was prepared. @@ -1165,6 +1272,14 @@ impl Prepared { .and_then(|ext| ext.arena(k - base.len())) } } + /// Whether this job's computes use SCS-capable compute units. + pub(crate) fn compute_scs(&self) -> bool { + self.compute_scs + } + /// Whether this job's renders use SCS-capable render allocators. + pub(crate) fn render_scs(&self) -> bool { + self.render_scs + } /// Physical PB/UMA allocator slot bitmask and preferred home slot this job can use. pub(crate) fn pb_slot_mask(&self) -> Result<(u32, usize)> { let base = self.render()?; @@ -1172,9 +1287,11 @@ impl Prepared { for &slot in &base.base_pb_slots { mask |= 1u32 << slot; } - for (idx, ext) in self.pb_ext.iter().enumerate() { - if ext.is_some() { - mask |= 1u32 << (super::hw::sizes::WARM_PB_SLOTS + idx); + if !self.render_scs { + for (idx, ext) in self.pb_ext.iter().enumerate() { + if ext.is_some() { + mask |= 1u32 << (super::hw::sizes::WARM_PB_SLOTS + idx); + } } } Ok((mask, base.base_pb_slots[0])) @@ -1182,7 +1299,17 @@ impl Prepared { fn pb_allocator(&self, k: usize) -> Result<&super::pools::Allocator> { let base = self.render()?; if let Some(local) = base.base_pb_slots.iter().position(|&slot| slot == k) { - return base.pools.unit(local).ok_or(EINVAL); + return if self.render_scs { + base.scs + .as_ref() + .and_then(|scs| scs.pools.unit(local)) + .ok_or(EINVAL) + } else { + base.pools.unit(local).ok_or(EINVAL) + }; + } + if self.render_scs { + return Err(EINVAL); } let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS).ok_or(EINVAL)?; self.pb_ext diff --git a/drivers/gpu/drm/asahi/g16/rt.rs b/drivers/gpu/drm/asahi/g16/rt.rs new file mode 100644 index 0000000000000..4119afade7c23 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/rt.rs @@ -0,0 +1,531 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Hardware ray tracing on G16G (RENDER_RAY_QUERY and BOUNDED_AS_BUILD). +//! +//! The command state is the shared G17P UAPI: a compute command's packed shader-context +//! scratch (SCS) layout and intersection tables, a render's per-stage ray-query state, and the +//! compute AS-build flag. The validation, the register words they become and the SCS memory +//! sizing are those of the M4 Pro (T6041, the same G16 GPU generation) on its 26B123 firmware +//! (`g17::fw::variant::V26B123`), except where macOS 27.2 on the J773g (G16G, 26B123) has +//! been traced: a ray-query compute item's 0x017e1/0x017d9 records and 0xd479 tail +//! ([`super::encode`]), and the SCS pools' freelists (+0x1c, [`SCS_FREELIST_RECORDS`]) and +//! row words (+0x48). This module is pure: no kernel objects, no allocation. +//! +//! What neither settles for G16G stays off behind a named gate or is open, as trace questions +//! of mesa#577: +//! +//! - 0x017d9 (SCS enable) in a render stage, [`super::encode`]'s `RENDER_SCS_ENABLE` (T5, +//! T6): the M4 Pro's 25G83 render programs write it in a stage with SCS. No G16G render with +//! ray queries has been traced. +//! - 0x1a141 (SCS driver word), `COMPUTE_SCS_DRIVER_WORD` (T1): macOS's ray-query compute +//! items on the J773g do not write it. +//! - An SCS-enable bit in the work or microsequence, as g17's kick header has (T6): none is +//! known, so nothing is written. +//! - A traversal exclusion between clients (T8): the A18 Pro needs one (`g17::traversal`), the +//! M4 Pro's variants do not set it; G16G adds none. +//! - How macOS sizes the SCS pool for a given request (T3): it grows its compute pool beyond +//! the M4 Pro's extras ([`pool_seeds`]); one request size does not give the rule. + +use kernel::prelude::*; + +/// Validated per-command shader-context scratch request (g17 `fw::compute::ScratchRequest`). +/// +/// The layout word is Apple's packed SCS layout: depth (bits 0:15), levels (16:23), cliques +/// (24:31), user (32:47) and driver (48:63). The region the hardware needs is derived with the +/// Gen1 section model: fixed prefixes totalling [`Self::FIXED_BYTES`], then per-thread stack, +/// per-thread driver and per-thread user bytes, rounded up with a two-page guard. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ScratchRequest { + pages: u16, + window: u64, + stack: u64, + driver: u64, + tail: u64, +} + +impl ScratchRequest { + /// Native ScsLayoutGen1::getSectionEnd(4). + const FIXED_BYTES: u64 = 0x58000; + const THREADS_PER_CLIQUE: u64 = 32; + const BYTES_PER_STACK_ENTRY: u64 = 8; + const PAGE_SHIFT: u32 = 12; + const PAGE_SIZE: u64 = 1 << Self::PAGE_SHIFT; + const PAGES_PER_MIB: u64 = 1 << (20 - Self::PAGE_SHIFT); + /// Window word when enabled: bit 24 plus the clique count at 16:23. + const WINDOW_ENABLED: u64 = 1 << 24; + /// Disabled window word: the value G16G's work lists write today. + pub(crate) const WINDOW_DISABLED: u64 = 0xff_0000; + /// Disabled stack word: the value G16G's work lists write today. + pub(crate) const STACK_DISABLED: u64 = 8; + /// TA/FS tail reservation when enabled (0xd471, 0xd469), matching macOS 27.2's J773g + /// ray-query tail reservation (0x2c). + const TAIL_ENABLED: u64 = 0x2c; + /// Compute tail reservation when enabled (0xd479), as macOS 27.2 on the J773g writes it in + /// its ray-query compute work. + const COMPUTE_TAIL_ENABLED: u64 = 0x2c; + + /// No scratch. + pub(crate) const NONE: Self = Self { + pages: 0, + window: Self::WINDOW_DISABLED, + stack: Self::STACK_DISABLED, + driver: 0, + tail: 0, + }; + + /// Payload-free layouts request no scratch even if depth or cliques are set. + pub(crate) fn new(layout: u64) -> Result { + let depth = layout & u64::from(u16::MAX); + let cliques = (layout >> 24) & u64::from(u8::MAX); + let user = (layout >> 32) & u64::from(u16::MAX); + let driver = (layout >> 48) & u64::from(u16::MAX); + if user == 0 && driver == 0 { + return Ok(Self::NONE); + } + let threads = cliques + .checked_mul(Self::THREADS_PER_CLIQUE) + .ok_or(EINVAL)?; + let stack_bytes = threads + .checked_mul( + depth + .checked_mul(Self::BYTES_PER_STACK_ENTRY) + .ok_or(EINVAL)?, + ) + .ok_or(EINVAL)?; + let driver_bytes = threads.checked_mul(driver).ok_or(EINVAL)?; + let user_bytes = threads.checked_mul(user).ok_or(EINVAL)?; + let end = Self::FIXED_BYTES + .checked_add(stack_bytes) + .and_then(|bytes| bytes.checked_add(driver_bytes)) + .and_then(|bytes| bytes.checked_add(user_bytes)) + .and_then(|bytes| bytes.checked_add(2 * Self::PAGE_SIZE - 1)) + .ok_or(EINVAL)?; + let pages = end >> Self::PAGE_SHIFT; + Ok(Self { + pages: u16::try_from(pages).map_err(|_| EINVAL)?, + window: Self::WINDOW_ENABLED | (cliques << 16), + stack: depth & !7, + // The Gen1 register list publishes no level region: the word stays zero. + driver: 0, + tail: Self::TAIL_ENABLED, + }) + } + + pub(crate) fn enabled(self) -> bool { + self.pages != 0 + } + + /// Per-core 4-KiB pages of the request. + pub(crate) fn pages(self) -> u16 { + self.pages + } + + /// 0x101d1 (compute), 0x101c9 (TA), 0x101c1 (FS): the pages and their 1-MiB count. + pub(crate) fn size_word(self) -> u64 { + let pages = u64::from(self.pages); + pages | (pages.div_ceil(Self::PAGES_PER_MIB) << 16) + } + + /// 0x107a1 (compute), 0x10799 (TA); the FS 0x10791 also sets bit 9. + pub(crate) fn window_word(self) -> u64 { + self.window + } + + /// 0x1a0e9 (compute), 0x1a0f1 (TA), 0x1a0f9 (FS). + pub(crate) fn stack_word(self) -> u64 { + self.stack + } + + /// 0x1a141 (compute), written only with `COMPUTE_SCS_DRIVER_WORD`. + pub(crate) fn driver_word(self) -> u64 { + self.driver + } + + /// 0xd471 (TA), 0xd469 (FS). + pub(crate) fn tail_word(self) -> u64 { + self.tail + } + + /// 0xd479 (compute). + pub(crate) fn compute_tail_word(self) -> u64 { + if self.enabled() { + Self::COMPUTE_TAIL_ENABLED + } else { + 0 + } + } +} + +/// Validated intersection tables (g17 `fw::compute::IntersectionTables`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct IntersectionTables { + pub(crate) pool: u64, + pub(crate) pool_bytes: u64, + first: u32, + count: u32, + pub(crate) default_program: u64, + default_control: u64, +} + +impl IntersectionTables { + pub(crate) const NONE: Self = Self { + pool: 0, + pool_bytes: 0, + first: 0, + count: 0, + default_program: 0, + default_control: 0, + }; + + /// The HAL200 Gen1 table: a 16-KiB aligned pool of 16-KiB units below 2^48, a byte-sized + /// table length of 25 bits, 128-byte entries, and a default program whose 48-bit code + /// address is 64-byte aligned and whose control word has bit 40 set. + pub(crate) fn new( + pool: u64, + pool_bytes: u64, + first: u32, + count: u32, + default_program: u64, + default_control: u64, + ) -> Result { + if pool == 0 { + if pool_bytes != 0 + || first != 0 + || count != 0 + || default_program != 0 + || default_control != 0 + { + return Err(EINVAL); + } + return Ok(Self::NONE); + } + let end = pool.checked_add(pool_bytes).ok_or(EINVAL)?; + let blocks_end = u64::from(first) + u64::from(count); + let code = default_program & 0x0000_ffff_ffff_ffff; + if pool & 0x3fff != 0 + || pool_bytes == 0 + || pool_bytes & 0x3fff != 0 + || end > (1u64 << 48) + || (pool_bytes >> 14) >= (1u64 << 25) + || count == 0 + || count >= (1 << 18) + || blocks_end * 128 > pool_bytes + || code & 63 != 0 + || default_control & !0x0000_7fff_0000_3fff != 0 + || (code == 0 && (default_program != 0 || default_control != 0)) + || (code != 0 && default_control & (1u64 << 40) == 0) + { + return Err(EINVAL); + } + Ok(Self { + pool, + pool_bytes, + first, + count, + default_program, + default_control, + }) + } + + /// A render stage's 48-byte table: the auxiliary word (zero or 8..=32, only with a pool), + /// four MBZ bytes, then the fields of [`Self::new`]. Bytes past 48 must be zero. The + /// auxiliary word is validated only: the M4 Pro's render programs write the scratch tail + /// where its compute program would write it. + pub(crate) fn parse(bytes: &[u8]) -> Result { + if bytes + .get(48..) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { + return Err(EINVAL); + } + let mut tail = [0u8; 48]; + let count = bytes.len().min(tail.len()); + tail[..count].copy_from_slice(&bytes[..count]); + let u32_at = + |at: usize| u32::from_le_bytes([tail[at], tail[at + 1], tail[at + 2], tail[at + 3]]); + let u64_at = |at: usize| u64::from(u32_at(at)) | u64::from(u32_at(at + 4)) << 32; + let auxiliary = u32_at(0); + if u32_at(4) != 0 || (auxiliary != 0 && !(8..=32).contains(&auxiliary)) { + return Err(EINVAL); + } + let tables = Self::new( + u64_at(8), + u64_at(16), + u32_at(24), + u32_at(28), + u64_at(32), + u64_at(40), + )?; + if auxiliary != 0 && !tables.enabled() { + return Err(EINVAL); + } + Ok(tables) + } + + pub(crate) fn enabled(self) -> bool { + self.pool != 0 + } + + /// The 48-bit address of the default program, or zero. + pub(crate) fn default_code(self) -> u64 { + self.default_program & 0x0000_ffff_ffff_ffff + } + + /// The six table words: compute 0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1; TA + /// 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1; FS 0x1a0a9, 0x1a0b1, 0x1a079, + /// 0x1a081, 0x1a0d9, 0x1a0e1. The M4 Pro's encoding (AGXMetalG17P endComputePass): the + /// first entry, the byte length, and two fixed pool words. Zero without tables, the value + /// G16G's work lists write today. + pub(crate) fn words(self) -> [u64; 6] { + if !self.enabled() { + return [0; 6]; + } + [ + self.pool + u64::from(self.first) * 128, + 0xc000_0000 | (u64::from(self.count) << 7), + 0x6f_0000_0000, + 0x3feff, + self.default_program, + self.default_control, + ] + } +} + +/// The ray state of a compute command. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ComputeRay { + pub(crate) intersection: IntersectionTables, + pub(crate) scratch: ScratchRequest, +} + +impl ComputeRay { + #[allow(dead_code, reason = "The empty state of the host regressions.")] + pub(crate) const NONE: Self = Self { + intersection: IntersectionTables::NONE, + scratch: ScratchRequest::NONE, + }; + + /// As the M4 Pro (G17P command set): an auxiliary allocation is M5-only and must be zero, + /// as must the reserved word; tables and scratch are independent of each other. + #[allow(clippy::too_many_arguments)] + pub(crate) fn new( + scs_layout: u64, + auxiliary: u32, + reserved: u32, + pool: u64, + pool_bytes: u64, + first: u32, + count: u32, + default_program: u64, + default_control: u64, + ) -> Result { + if auxiliary != 0 || reserved != 0 { + return Err(EINVAL); + } + Ok(Self { + intersection: IntersectionTables::new( + pool, + pool_bytes, + first, + count, + default_program, + default_control, + )?, + scratch: ScratchRequest::new(scs_layout)?, + }) + } +} + +/// The ray state of one render stage (g17 `fw::render_rt::RayQueryStage`): index 0 the +/// vertex (tiling) stage, 1 the fragment stage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct RayQueryStage { + pub(crate) intersection: IntersectionTables, + pub(crate) scratch: ScratchRequest, +} + +impl RayQueryStage { + /// Size of one `drm_asahi_render_ray_query_stage`. + pub(crate) const SIZE: usize = 56; + + #[allow(dead_code, reason = "The empty state of the host regressions.")] + pub(crate) const NONE: Self = Self { + intersection: IntersectionTables::NONE, + scratch: ScratchRequest::NONE, + }; + + fn parse(wire: &[u8; Self::SIZE]) -> Result { + let layout = u64::from_le_bytes([ + wire[0], wire[1], wire[2], wire[3], wire[4], wire[5], wire[6], wire[7], + ]); + let intersection = IntersectionTables::parse(&wire[8..])?; + let scratch = ScratchRequest::new(layout)?; + if scratch.enabled() != intersection.enabled() { + return Err(EINVAL); + } + Ok(Self { + intersection, + scratch, + }) + } + + /// Both stages from the render payload bytes after `prior_cdm`: shorter payloads are read + /// zero-filled, bytes past the two stages must be zero. + pub(crate) fn parse_pair(bytes: &[u8]) -> Result<[Self; 2]> { + if bytes + .get(2 * Self::SIZE..) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { + return Err(EINVAL); + } + let mut wire = [[0u8; Self::SIZE]; 2]; + for (index, stage) in wire.iter_mut().enumerate() { + let start = (index * Self::SIZE).min(bytes.len()); + let end = ((index + 1) * Self::SIZE).min(bytes.len()); + stage[..end - start].copy_from_slice(&bytes[start..end]); + } + Ok([Self::parse(&wire[0])?, Self::parse(&wire[1])?]) + } + + /// Whether the stage carries intersection tables. + pub(crate) fn traces(self) -> bool { + self.intersection.enabled() + } +} + +/// Only the explicit AS-build bit (bit 2) is accepted; reserved and unrelated compute flags +/// stay invalid on G16G, as on the M4 Pro (g17 `timeout::as_build`). +pub(crate) fn as_build(flags: u32) -> Option { + const AS_BUILD: u32 = 1 << 2; + if flags & !AS_BUILD != 0 { + None + } else { + Some(flags & AS_BUILD != 0) + } +} + +/// Whether a command needs the long execution allowance (g17 `timeout::select`): a compute +/// command with intersection tables, a render with tables in either stage, or an AS build. +pub(crate) fn select(compute_ray: bool, render_ray: [bool; 2], as_build: bool) -> bool { + compute_ray || render_ray.into_iter().any(|enabled| enabled) || as_build +} + +/// Freelist entries (4-KiB pages) of a UMA pool without SCS, the value G16G seeds today. +pub(crate) const BASE_SEEDS: u32 = 8192; +/// Records of a base UMA freelist: the capacity G16G's managers report at +0x1c for their +/// 0x20000-byte freelist (`UNK_1C_VALUE`). +pub(crate) const FREELIST_RECORDS: u32 = 16384; +/// Records of an SCS-capable pool's freelist: the +0x1c macOS 27.2 on the J773g writes on +/// every pool, over a 4-MiB freelist, whatever the pool's rows (20 to 108 seen). +pub(crate) const SCS_FREELIST_RECORDS: u32 = 0x80000; +/// Bytes of one freelist record, the 64-bit address of one 4-KiB seed. +pub(crate) const RECORD_BYTES: u64 = 8; +/// Bytes of one seed. +pub(crate) const SEED_BYTES: u64 = 0x1000; +/// Freelist entries of one 2-MiB pool-table row. +pub(crate) const SEEDS_PER_ROW: u32 = 512; +/// The most freelist entries of an SCS-capable UMA pool: the whole rows whose pool and +/// freelist fit one SCS pool window (62 rows, 124 MiB, and the 4-MiB freelist). The 256-row +/// pool table holds more. +pub(crate) const MAX_SCS_SEEDS: u32 = max_window_seeds(super::hw::client::SCS_POOL_WINDOW); +const _: () = assert!(BASE_SEEDS % SEEDS_PER_ROW == 0 && MAX_SCS_SEEDS % SEEDS_PER_ROW == 0); +const _: () = assert!(BASE_SEEDS < FREELIST_RECORDS && FREELIST_RECORDS < MAX_SCS_SEEDS); +const _: () = assert!(MAX_SCS_SEEDS < SCS_FREELIST_RECORDS); +const _: () = assert!(freelist_records(BASE_SEEDS) as u64 * RECORD_BYTES == 0x20000); + +/// The freelist records (+0x1c) of a UMA pool with `seeds` entries. +0x1c is the record count +/// of the freelist +0x14 points at. A base pool keeps the 16384 G16G has always written; an +/// SCS-capable pool (more than the base seeds) gets [`SCS_FREELIST_RECORDS`], as macOS 27.2 on +/// the J773g gives every pool. +pub(crate) const fn freelist_records(seeds: u32) -> u32 { + if seeds > BASE_SEEDS { + SCS_FREELIST_RECORDS + } else { + FREELIST_RECORDS + } +} + +/// Bytes of the freelist of a pool with `seeds` entries, in whole 16-KiB pages. +pub(crate) const fn freelist_bytes(seeds: u32) -> u64 { + (freelist_records(seeds) as u64 * RECORD_BYTES).next_multiple_of(0x4000) +} + +/// Bytes an SCS pool window needs for a pool of `seeds` entries and, after it, its freelist. +pub(crate) const fn window_bytes(seeds: u32) -> u64 { + seeds as u64 * SEED_BYTES + freelist_bytes(seeds) +} + +/// The most whole-row seeds whose pool and freelist fit `window` bytes. +const fn max_window_seeds(window: u64) -> u32 { + let mut seeds = (window / SEED_BYTES) as u32 / SEEDS_PER_ROW * SEEDS_PER_ROW; + while seeds != 0 && window_bytes(seeds) > window { + seeds -= SEEDS_PER_ROW; + } + seeds +} + +/// The 4-KiB pages one SCS request adds to a UMA pool for `active_cores` cores, as the M4 Pro +/// sizes its free list (g17 `fw::compute_pool::extra_bytes`): per core the request's pages, +/// their 1-MiB large-page inventory (pages / 256, rounded up) and eight tail pages. +pub(crate) fn extra_pages(active_cores: u32, scs_pages: u16) -> Result { + if active_cores == 0 { + return Err(EINVAL); + } + if scs_pages == 0 { + return Ok(0); + } + let small = u64::from(scs_pages); + small + .checked_add(small.div_ceil(256)) + .and_then(|pages| pages.checked_add(8)) + .and_then(|pages| pages.checked_mul(u64::from(active_cores))) + .ok_or(EOVERFLOW) +} + +/// Freelist entries a UMA pool needs to serve SCS requests of `pages` per stage at once (one +/// compute dispatch, or the two stages of one render): the base pool plus every stage's extra +/// pages, rounded up to whole pool-table rows. E2BIG beyond the largest SCS-capable pool +/// ([`MAX_SCS_SEEDS`]); without SCS it is [`BASE_SEEDS`]. +pub(crate) fn required_seeds(active_cores: u32, pages: &[u16]) -> Result { + let mut seeds = u64::from(BASE_SEEDS); + for &stage in pages { + seeds = seeds + .checked_add(extra_pages(active_cores, stage)?) + .ok_or(EOVERFLOW)?; + } + let row = u64::from(SEEDS_PER_ROW); + let seeds = seeds.checked_add(row - 1).ok_or(EOVERFLOW)? / row * row; + if seeds > u64::from(MAX_SCS_SEEDS) { + return Err(E2BIG); + } + u32::try_from(seeds).map_err(|_| E2BIG) +} + +/// The SCS-capable UMA pool a command runs on: one of at least `needed` freelist entries, or +/// if its VM has none yet, a new one of `pool` ([`pool_seeds`]). Both zero without scratch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ScsSeeds { + pub(crate) needed: u32, + pub(crate) pool: u32, +} + +impl ScsSeeds { + /// No scratch. + pub(crate) const NONE: Self = Self { needed: 0, pool: 0 }; +} + +/// Freelist entries of the SCS-capable pools created for requests of `pages` per stage (a +/// render's two stages, or a compute dispatch and zero). The pools serve every later job of the +/// VM and cannot grow once the hardware may hold them, so they hold two stages at the larger +/// one where a window holds that, otherwise the request itself; E2BIG if neither fits. +/// +/// - A render pool then takes a later queue that reserves the other stage too (Mesa replaces +/// its queue to add one). +/// - A compute pool gets two dispatches' extras. One is less than macOS provisions: for its +/// own ray-query kernel of 1703 pages per core, macOS 27.2 on the J773g grew the compute pool +/// to 108 rows, about 2.6 times the extras of [`extra_pages`]. +pub(crate) fn pool_seeds(active_cores: u32, pages: [u16; 2]) -> Result { + let largest = pages[0].max(pages[1]); + required_seeds(active_cores, &[largest, largest]) + .or_else(|_| required_seeds(active_cores, &pages)) +} diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index aa3d445a12bd8..8891434a0e52f 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -32,36 +32,139 @@ pub(crate) struct ComputeSlot { pub(crate) counter: Arc, pub(crate) context_store: Arc, pub(crate) aux: Arc, + /// Freelist entries of the unit's UMA pool, seeded once ([`init_uma_pool`]). + pub(crate) seeds: u32, /// VM-free firmware lease keeping `work` (containing the compute UMA manager at `+0xe00`) /// and `counter` mapped in context-0 UAT until a later compute retirement overwrites /// firmware `uma_mgr_table[1 + k]`. uma_lease: Arc, } +/// Where a compute unit lives and how large its UMA pool is. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Placement { + /// The VM's base units: a 32 MiB pool at the unit's original client addresses. + Base, + /// SCS-capable units (ray-query scratch): a pool of `seeds` 4-KiB entries + /// ([`super::rt::required_seeds`]) and its freelist in the unit's SCS pool window, the + /// other records at their own client addresses, sharing ledger index and UMA slot `1 + k` + /// with base unit k. + Scs { seeds: u32 }, +} + +impl Placement { + fn pool(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_pool(k), + Placement::Scs { .. } => client::scs_compute_pool(k), + } + } + /// The base of the unit's list, preempt, auxiliary and context records. + fn state(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_state(k), + Placement::Scs { .. } => client::scs_compute_records(k), + } + } + /// The unit's freelist: a base unit's at its state, an SCS unit's right after its pool. + fn freelist(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_state(k), + Placement::Scs { .. } => self.pool(k) + self.pool_bytes() as u64, + } + } + fn work(self, k: u64) -> u64 { + let index = match self { + Placement::Base => k, + Placement::Scs { .. } => sizes::COMPUTE_UNITS as u64 + k, + }; + client::WORK_PAGE + index * client::CWORK_STRIDE + } + /// Freelist entries of the unit's pool. + pub(crate) fn seeds(self) -> u32 { + match self { + Placement::Base => super::rt::BASE_SEEDS, + Placement::Scs { seeds } => seeds, + } + } + /// Bytes of the unit's pool: its seeds of 4 KiB. + pub(crate) fn pool_bytes(self) -> usize { + (u64::from(self.seeds()) * super::rt::SEED_BYTES) as usize + } + /// Bytes of the unit's freelist ([`super::rt::freelist_bytes`]). + pub(crate) fn freelist_bytes(self) -> usize { + super::rt::freelist_bytes(self.seeds()) as usize + } + /// An SCS unit's pool fits [`super::rt::MAX_SCS_SEEDS`] in whole rows, so it and its + /// freelist fit its window. + pub(crate) fn check(self) -> Result { + match self { + Placement::Base => Ok(()), + Placement::Scs { seeds } => { + if seeds == 0 + || seeds % super::rt::SEEDS_PER_ROW != 0 + || seeds > super::rt::MAX_SCS_SEEDS + { + Err(E2BIG) + } else { + Ok(()) + } + } + } + } +} +const _: () = assert!( + sizes::POOL_BYTES == super::rt::BASE_SEEDS as u64 * super::rt::SEED_BYTES + && super::rt::window_bytes(super::rt::MAX_SCS_SEEDS) <= client::SCS_POOL_WINDOW +); + /// Initializes the private pool exactly once, before it is exposed. Never called on reuse. -pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64) -> Result { - if pool & 0x3fff != 0 { +/// `seeds` 4-KiB freelist entries and their 2-MiB pool-table rows; 8192 is the 32 MiB pool +/// every unit had before SCS. The freelist `state` holds every seed, the pool table `list` +/// every row. +pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: u32) -> Result { + let seeds = seeds as usize; + let rows = seeds / super::rt::SEEDS_PER_ROW as usize; + if pool & 0x3fff != 0 + || seeds == 0 + || seeds % super::rt::SEEDS_PER_ROW as usize != 0 + || seeds * super::rt::RECORD_BYTES as usize > state.size + || rows * super::fw::buffer::uma_pools::POOL_TABLE_STRIDE > list.size + { return Err(EINVAL); } let mut chunk = [0u8; 512]; - for first in (0..8192).step_by(64) { + for first in (0..seeds).step_by(64) { for j in 0..64 { chunk[j * 8..j * 8 + 8] .copy_from_slice(&(pool + ((first + j) as u64) * 0x1000).to_le_bytes()); } state.write(first * 8, &chunk)?; } - for i in 0..16 { + for i in 0..rows { list.w64(i * 64, (1u64 << 61) | (pool + i as u64 * 0x200000))?; } Ok(()) } impl ComputeSlot { + #[allow(dead_code)] pub(crate) fn new(o: &mut Objects, fw_factory: &Factory, k: u64) -> Result { + Self::new_in(o, fw_factory, k, Placement::Base) + } + + /// Unit `k` at `placement`. + pub(crate) fn new_in( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + placement: Placement, + ) -> Result { + placement.check()?; let sh = Class::Shared; + let state = placement.state(k); let mut fw = fw_factory.fw_objects(); - let work = alloc_work(&mut fw, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?; + let work = alloc_work(&mut fw, 0x2000, placement.work(k), 0)?; let counter = alloc(&mut fw, 0x80, sh, None, 0, false)?; let uma_lease = FwLease::new(fw)?; let unit = Self { @@ -70,7 +173,7 @@ impl ComputeSlot { o, 0x4000, sh, - Client::nc(client::compute_preempt(k)), + Client::nc(state + client::COMPUTE_PREEMPT_OFF), 0, false, )?, @@ -86,42 +189,59 @@ impl ComputeSlot { false, )?, pool: o.alloc(super::object::Request { - size: 0x2000000, + size: placement.pool_bytes(), class: sh, placement: super::object::Placement::Anywhere, offset: 0, - client: Some((client::compute_pool(k), super::hw::pte::LEAF_NC)), + client: Some((placement.pool(k), super::hw::pte::LEAF_NC)), lower: None, cpu: false, })?, pool_state: alloc( o, - 0x20000, + placement.freelist_bytes(), + sh, + Client::nc(placement.freelist(k)), + 0, + false, + )?, + page_list: alloc( + o, + 0x4000, sh, - Client::nc(client::compute_state(k)), + Client::nc(state + client::COMPUTE_LIST_OFF), 0, false, )?, - page_list: alloc(o, 0x4000, sh, Client::nc(client::compute_list(k)), 0, false)?, counter, context_store: alloc( o, 0x40000, sh, - Client::nc(client::compute_context(k)), + Client::nc(state + client::COMPUTE_CONTEXT_OFF), 0, false, )?, - aux: alloc(o, 0x4000, sh, Client::nc(client::compute_aux(k)), 0, false)?, + aux: alloc( + o, + 0x4000, + sh, + Client::nc(state + client::COMPUTE_AUX_OFF), + 0, + false, + )?, + seeds: placement.seeds(), uma_lease, }; init_uma_pool( &unit.pool_state, &unit.page_list, unit.pool.gva.ok_or(EINVAL)?, + unit.seeds, )?; Ok(unit) } + /// VM-free firmware lease keeping this unit's `work` and `counter` mapped in context-0 UAT. pub(crate) fn uma_lease(&self) -> Arc { self.uma_lease.clone() @@ -1171,7 +1291,12 @@ impl Slots { let Some(k) = chosen else { return Ok(None); }; + let arena_changed = self.compute.arena[k] + .as_ref() + .zip(units.compute_arena(k).as_ref()) + .is_some_and(|(a, b)| !Arc::ptr_eq(a, b)); let full = self.compute.scrub_full[k] + || arena_changed || vm_id.is_none_or(|id| { self.compute.owner[k] .as_ref() diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index db053aef62278..0ffd1dd521987 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -329,7 +329,7 @@ enum drm_asahi_feature { DRM_ASAHI_FEATURE_COMPUTE_WIDE_VISIBILITY = (1UL) << 8, /* - * Bits 10 to 15 are reported only by the G17P runtime. + * Bits 10 to 16 are the HAL200/G16/G17P command-stream features. */ /** diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs index 62fb9222460f8..e0099ee4862e6 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs @@ -9,7 +9,10 @@ mod fw { } } #[allow(unused_imports)] -use fw::{graph::manager, work::compute}; +use fw::{ + graph::{manager, pools}, + work::compute, +}; mod uapi { #[derive(Default)] pub struct drm_asahi_cmd_compute {pub cdm_ctrl_stream_base:u64,pub cdm_ctrl_stream_end:u64} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py index 3d1e261e301bc..27093fdfdf1e7 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py @@ -67,7 +67,7 @@ assert 'fn cover(' not in command assert 'enum Resolved' not in command hardware = (SOURCE.parent / 'hw.rs').read_text() -capacities = '\n'.join(re.findall(r'pub\(crate\) const (?:TPC_SIZE|TILEMAP_SIZE): u64 = .*?;', hardware)) +capacities = '\n'.join(re.findall(r'pub\(crate\) const (?:TPC_SIZE|TILEMAP_SIZE|SCS_POOL_WINDOW): u64 = .*?;', hardware)) names = ['drm_asahi_cmd_header', 'drm_asahi_attachment', 'drm_asahi_cmd_render', 'drm_asahi_cmd_compute', 'drm_asahi_bg_eot', 'drm_asahi_zls_buffer', 'drm_asahi_timestamp', 'drm_asahi_timestamps', 'drm_asahi_helper_program', @@ -103,7 +103,7 @@ // The parser logs why it refuses a command; check the format arguments, print nothing. macro_rules! pr_warn { ($($arg:tt)*) => {{ let _ = format_args!($($arg)*); }}; } pub mod bindings { pub const EOPNOTSUPP:i32=95; } -pub mod prelude { pub type Result = core::result::Result; pub const E2BIG:i32=-7; } +pub mod prelude { pub type Result = core::result::Result; pub const EINVAL:i32=-22; pub const E2BIG:i32=-7; pub const EOVERFLOW:i32=-75; } pub(crate) mod timestamp { pub(crate) struct Destinations; impl Destinations { pub(crate) const fn empty() -> Self { Self } } @@ -132,6 +132,7 @@ #[path="FW_WORK"] pub mod work; } #[path="FULL_ENCODER"] mod encode; +#[path="RT_MOD"] mod rt; READER IMPLS PRODUCTION_CONSTANTS @@ -237,7 +238,7 @@ } #[test] fn ray_query_and_unknown_extension_bytes_are_refused() { - let mut r=render(); r.ray_query[0].scs_layout=1; + let mut r=render(); r.ray_query[0].scs_layout=0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_RENDER,&data(&r),[NONE;2]),false).is_err()); let mut raw=data(&compute()); raw.extend([0u8;8]); assert!(check_stream(&entry(CMD_COMPUTE,&raw,[NONE;2]),false).is_ok()); @@ -386,7 +387,7 @@ both.legacy.flags |= FRAGMENT_BARRIERS; assert!(check_stream(&entry(CMD_RENDER, &data(&both), [NONE; 2]), true).is_err()); let mut rq = m5; - rq.legacy.ray_query[0].scs_layout = 1; + rq.legacy.ray_query[0].scs_layout = 0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_RENDER, &data(&rq), [NONE; 2]), true).is_err()); // Without STAGE_PREFIXES, nonzero trailing bytes past 448 are rejected; zero tail is accepted. @@ -444,7 +445,7 @@ assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); } let mut c=compute(); - c.scs_layout=1; + c.scs_layout=0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); c.scs_layout=0; c.cdm_auxiliary_allocation=8; assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); @@ -696,6 +697,8 @@ pub(crate) struct Context<'a> { pub(crate) vm: &'a mmu::Vm, pub(crate) usc_base: u64, + pub(crate) active_cores: u32, + pub(crate) render_scs: [u16; 2], } use super::MAX_COMMANDS; RENDER_ADMISSION @@ -745,7 +748,7 @@ #[test] fn compressed_zls_1x_layered_and_2x_accepted() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; // 1x compressed D32F depth + stencil. let mut cmd = base_cmd(); cmd.zls_ctrl = Z_COMP | S_COMP; @@ -778,7 +781,7 @@ #[test] fn compressed_zls_invalid_ctrl_alignment_and_vm_spans_rejected() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; let valid = || { let mut cmd = base_cmd(); cmd.zls_ctrl = Z_COMP | S_COMP; @@ -835,7 +838,7 @@ #[test] fn submit_wide_span_batch_dedups_and_flushes_once_across_passes() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; let mut batch = SpanBatch::new(); for pass in 0..4u64 { let mut cmd = base_cmd(); @@ -875,7 +878,7 @@ #[test] fn few_primitives_flag_admitted_in_parse_and_render_check() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; let mut r = super::render(); r.flags = FEW_PRIMITIVES; assert!(super::check_stream( @@ -912,7 +915,7 @@ // First flush populates the proof for epoch 1. let mut batch = SpanBatch::new(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); assert_eq!(vm.batch_calls.get(), 1); @@ -958,7 +961,7 @@ vm.maps.remove(1); vm.epoch.set(Some(2)); let mut batch = SpanBatch::new(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); assert_eq!(batch.flush_with_proof(&vm, &mut proof), Err(ENOENT)); @@ -975,9 +978,11 @@ replacements = {'FULL_UAPI': str(BINDINGS), 'READER': reader, 'CAPACITIES': capacities, 'FW_GRAPH': str(SOURCE.parent/'fw/graph.rs'), 'FW_WORK': str(SOURCE.parent/'fw/work.rs'), 'FULL_ENCODER': str(SOURCE.parent/'encode.rs'), + 'RT_MOD': str(SOURCE.parent/'rt.rs'), 'IMPLS': '\n'.join('unsafe impl AnyBitPattern for uapi::' + name + ' {}' for name in names), - 'PRODUCTION_CONSTANTS': constants, 'PARSE_TYPES': parse_types, - 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), + 'PRODUCTION_CONSTANTS': constants, + 'PARSE_TYPES': parse_types.replace('super::rt::', 'rt::'), + 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::').replace('super::rt::', 'rt::'), 'INLINE_CONTAINERS': inline_containers.replace('crate::timestamp::', 'timestamp::'), 'RENDER_ADMISSION': render_admission.replace('super::vm::', 'vm::').replace('super::params::', 'params::'), 'G17_CONSTANTS': g17_constants, 'G17_PARSER': g17_parser} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index 0942af9db869a..8cc61598bf617 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -32,10 +32,12 @@ def function(text,name): macro_rules! dev_err{($($tt:tt)*)=>{};} struct Object(Cell);impl Object{fn r32(&self,_off:usize)->core::result::Result{Ok(self.0.get())}} struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;2],render:Render} -struct Flight{computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} +struct Job{long:bool} +impl Job{fn long(&self)->bool{self.long}} +struct Flight{job:Job,computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} struct Engine{flights:Vec,target:[u32;2],ta_target:u32,fs_target:u32,progress_flight:[u64;3],progress:[__TYPE__;4]} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} -struct Recovery{deadline_ns:u64,compute_deadline_ns:u64,warning_deadline_ns:[u64;2],long_commands:u64,receipt_fault:bool,failed:Option} +struct Recovery{deadlines:logic::Deadlines,warning_deadline_ns:[u64;2],long_commands:u64,receipt_fault:bool,failed:Option} struct Firmware{graph:Graph,engine:Engine,recovery:Recovery,render_renewed:u32,compute_renewed:u32,fail_stops:Vec} impl Firmware{ fn dev(&self){} @@ -45,13 +47,17 @@ def function(text,name): fn fail_stop(&mut self,error:Error,_done:&mut ()){self.recovery.failed=Some(error);self.fail_stops.push(error);} fn renew_render_deadline(&mut self){ let now=now_ns(); - self.recovery.deadline_ns=logic::renew(now,params::deadline_ms(),0).0; + let renewed=logic::Deadlines::renew(now,params::deadline_ms(),0); + self.recovery.deadlines.any=renewed.any; + self.recovery.deadlines.long_any=renewed.long_any; self.recovery.warning_deadline_ns[command::RENDER]=now.saturating_add(5_000_000_000); self.render_renewed+=1; } fn renew_compute_deadline(&mut self){ let now=now_ns(); - self.recovery.compute_deadline_ns=logic::renew(now,0,params::compute_deadline_ms()).1; + let renewed=logic::Deadlines::renew(now,0,params::compute_deadline_ms()); + self.recovery.deadlines.compute=renewed.compute; + self.recovery.deadlines.long_compute=renewed.long_compute; self.recovery.warning_deadline_ns[command::COMPUTE]=now.saturating_add(5_000_000_000); self.compute_renewed+=1; } @@ -62,8 +68,8 @@ def function(text,name): fn firmware(render:bool,target:u32,previous:u32)->Firmware{ set_now_ns(1_000_000_000); let mut f=Firmware{graph:Graph{compute:[Compute{fw_stamp:Object(Cell::new(previous))},Compute{fw_stamp:Object(Cell::new(previous))}],render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, - engine:Engine{flights:vec![Flight{computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:[target,0],ta_target:target,fs_target:target,progress_flight:[0;3],progress:[__ZERO__;4]}, - recovery:Recovery{deadline_ns:u64::MAX,compute_deadline_ns:u64::MAX,warning_deadline_ns:[u64::MAX;2],long_commands:0,receipt_fault:false,failed:None}, + engine:Engine{flights:vec![Flight{job:Job{long:false},computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:[target,0],ta_target:target,fs_target:target,progress_flight:[0;3],progress:[__ZERO__;4]}, + recovery:Recovery{deadlines:logic::Deadlines::EXPIRED,warning_deadline_ns:[u64::MAX;2],long_commands:0,receipt_fault:false,failed:None}, render_renewed:0,compute_renewed:0,fail_stops:vec![]}; f.renew_render_deadline();f.renew_compute_deadline();f.render_renewed=0;f.compute_renewed=0;f } @@ -89,7 +95,7 @@ def function(text,name): } #[test]fn concurrent_compute_and_render_renew_deadlines_independently(){ let mut f=firmware(true,0x200,0x100); - f.engine.flights.push(Flight{computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); f.engine.target[0]=0x300; f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,0)); f.graph.compute[0].fw_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); @@ -97,7 +103,7 @@ def function(text,name): } #[test]fn two_concurrent_compute_pipes_sample_progress_independently(){ let mut f=firmware(false,0x200,0x100); - f.engine.flights.push(Flight{computes:1,compute_pipe:1,renders:0,target:0x200,ta_target:0,fs_target:0,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:1,renders:0,target:0x200,ta_target:0,fs_target:0,published_ns:2}); f.engine.target=[0x200,0x200]; f.progress();assert_eq!(f.compute_renewed,0); // Pipe 1 advances while pipe 0 stays pending -> renews compute deadline once. @@ -110,7 +116,7 @@ def function(text,name): } #[test]fn stuck_render_times_out_while_compute_keeps_advancing_and_retiring(){ let mut f=firmware(true,0x200,0x100); - f.engine.flights.push(Flight{computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); f.engine.target[0]=0x300; let mut done=(); assert_eq!(f.check_hangs(&mut done),Ok(())); @@ -135,7 +141,7 @@ def function(text,name): } #[test]fn stuck_compute_times_out_while_render_keeps_advancing_and_retiring(){ let mut f=firmware(false,0x200,0x100); - f.engine.flights.push(Flight{computes:0,compute_pipe:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:0,compute_pipe:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); f.engine.ta_target=0x300;f.engine.fs_target=0x300; let mut done=(); assert_eq!(f.check_hangs(&mut done),Ok(())); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 269925c85b000..310c27495708a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -95,6 +95,7 @@ def item(declaration): __PUBLICATION_ERROR__ #[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } #[derive(Copy,Clone)]struct ComputeCommand { query_access: bool } +impl ComputeCommand { fn is_rt(&self) -> bool { false } } #[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(()) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} struct Vm { status:Status, slot:u32 } @@ -117,7 +118,7 @@ def item(declaration): fn count(&self)->u32{self.count} fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } -struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -128,8 +129,8 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,doomed:false,recovery_suspect:false,initbm:false}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,doomed:bool,recovery_suspect:bool,initbm:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,doomed:false,recovery_suspect:false,initbm:false}}} struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} impl Engine { __PICK__ @@ -162,11 +163,13 @@ def item(declaration): fn exhausted(&self)->bool{self.exhausted} fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} fn exhausted_for_within(&self,vm:&Vm,_limit:usize)->bool{self.exhausted_for(vm)} - fn exhausted_for_mask(&self,vm:&Vm,_mask:u32,_home:usize)->bool{self.exhausted_for(vm)} + fn exhausted_for_within_mode(&self,vm:&Vm,limit:usize,_scs:bool)->bool{self.exhausted_for_within(vm,limit)} + fn exhausted_for_mask_mode(&self,vm:&Vm,_mask:u32,_home:usize,_scs:bool)->bool{self.exhausted_for(vm)} fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} - fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks_mode(&self,vm:&Arc,limit:usize,min_blocks:u32,_scs:bool)->bool{self.can_pipeline_within_blocks(vm,limit,min_blocks)} + fn can_pipeline_in_mask_blocks_mode(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32,_scs:bool)->bool{self.can_pipeline(vm)} } mod encode { pub struct ComputeRefs{pub invalid:bool} @@ -727,7 +730,7 @@ def item(declaration): struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} struct QueueBehindGraph{render:QueueBehindRenderGraph} impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,flights:Vec} struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} impl QueueBehindSlots{ @@ -746,7 +749,8 @@ def item(declaration): fn can_pipeline(&self,vm:&Arc)->bool{self.can_pipeline&&self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} - fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks_mode(&self,vm:&Arc,limit:usize,min_blocks:u32,_scs:bool)->bool{self.can_pipeline_within_blocks(vm,limit,min_blocks)} + fn can_pipeline_in_mask_blocks_mode(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32,_scs:bool)->bool{self.can_pipeline(vm)} } struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { @@ -806,7 +810,7 @@ def item(declaration): let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -852,7 +856,7 @@ def item(declaration): let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -870,7 +874,7 @@ def item(declaration): }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -894,7 +898,7 @@ def item(declaration): let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -938,7 +942,7 @@ def item(declaration): let vm2_r=mk(3,vm2.clone(),q2.clone(),true); let vm2_c=mk(4,vm2.clone(),q2.clone(),false); let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ - job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0, + job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false, target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; @@ -983,8 +987,8 @@ def item(declaration): let p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, ]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, @@ -1020,7 +1024,7 @@ def item(declaration): let pm=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, ]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, @@ -1053,7 +1057,7 @@ def item(declaration): let host=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0, + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1099,7 +1103,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1110,7 +1114,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -1137,7 +1141,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1177,7 +1181,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1192,7 +1196,7 @@ def item(declaration): let mut cur_fs=[0u32;16]; cur_fs[0]=0x400; let cur=QueueBehindFlight{ - job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1214,7 +1218,7 @@ def item(declaration): let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; let cur_grp=QueueBehindFlight{ - job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1247,7 +1251,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:4,ta_target:0x400,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:4,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:4,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1292,7 +1296,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }]}, @@ -1638,27 +1642,29 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Empty engine uses next_compute_pipe (0), then balances onto pipe 1 while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 24), 0); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); host.engine.flights.push(QueueBehindFlight{ - job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe([None, None], 24), 1); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); + // RT/SCS compute stays pinned to pipe 0 even while pipe 0 is active. + assert_eq!(host.choose_compute_pipe([None, None], 24, true), 0); // A 2-unit base-only VM stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 2), 0); + assert_eq!(host.choose_compute_pipe([None, None], 2, false), 0); assert!(host.can_queue_behind(&c2)); // Add second concurrent flight on pipe 1: both pipes active, // tie-break uses next_compute_pipe, and cross-VM compute overlaps cleanly. host.engine.flights.push(QueueBehindFlight{ - job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,target:0x100, + job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe([None, None], 24), 1); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe([None, None], 24), 0); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); assert!(host.can_queue_behind(&c_vm2)); // Same-VM compute still pipelines without draining. assert!(host.can_queue_behind(&c2)); @@ -1681,12 +1687,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,target:0x200, + job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,target:0x200, cstamp:{let mut a=[0;16];a[0]=0x200;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1699,13 +1705,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w1, 24), 0); + assert_eq!(host.choose_compute_pipe(w1, 24, false), 0); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(w2, 24), 0); + assert_eq!(host.choose_compute_pipe(w2, 24, false), 0); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1716,7 +1722,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w2_ooo, 24), 0); + assert_eq!(host.choose_compute_pipe(w2_ooo, 24, false), 0); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -1760,12 +1766,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0, + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1776,7 +1782,7 @@ def item(declaration): // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(cw,24),0); + assert_eq!(host.choose_compute_pipe(cw,24,false),0); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py new file mode 100644 index 0000000000000..3b5c3dca9299d --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -0,0 +1,587 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host-check the G16G ray-tracing command set (RENDER_RAY_QUERY, BOUNDED_AS_BUILD). + +Compiles the production g16/rt.rs, recovery/logic.rs and the TA/FS/compute encoders, plus the +command admission and engine conversion functions copied verbatim from command.rs and +engine.rs, against CPU-only stand-ins. No GPU, firmware or Mesa is involved. + +Failure modes this guards against (written before the code): + + 1. A non-RT command changes bytes: the engine's conversion of an empty ray state is not the + disabled word set, or the disabled set differs from the words G16G always wrote (the frozen + golden fixtures then cover the rest). + 2. RT words land in the wrong register record, the register counts change, a gated register + (0x1a141, render 0x017d9) is written while its gate is off, or a ray-query compute item is + not bracketed by 0x017e1 = 1 first and 0x017d9 = 1 last, or its tail is not 0x2c, as macOS + 27.2 writes them on the J773g. + 3. The fragment window word loses bit 9; a render stage's tail word takes the auxiliary + intersection word (the M4 Pro's render programs use the scratch tail). + 4. SCS sizing differs from the M4 Pro's formula ((pages + pages/256 + 8) x cores pages), is not + rounded to whole 2-MiB rows, overflows silently, or admits a pool whose pages and freelist do + not fit an SCS pool window (E2BIG); zero cores is accepted. + 5. A render whose scratch exceeds its queue's reservation is accepted, or one within it + refused; an unmapped intersection pool or default program is accepted. + 6. The long allowance misses a ray/AS-build job, applies to plain work, re-enables a disabled + (zero) deadline, or shortens a deadline already longer than 10 s. + 7. A compute flag other than AS_BUILD is accepted; scratch alone counts as ray traversal. + 8. The feature word loses a bit or gains another than RENDER_RAY_QUERY and BOUNDED_AS_BUILD. + 9. A UMA manager image or compute descriptor reports seeds that are not whole rows inside the + freelist, a freelist (+0x1c) that does not hold its pool or is smaller than a base one, an + SCS pool's freelist other than macOS's 0x80000 records, or row words (+0x48) other than 8 + per valid row. +10. Mesa's G16G ray-query commands (layout 0x0130000060010070 on 10 cores, compute and either or + both render stages, and their QUEUE_CREATE reservations) are refused, which Mesa reports as + VK_ERROR_DEVICE_LOST; the render pools a queue creates cannot take a queue that later + reserves the other stage too; or a compute pool is created for fewer than two dispatches + where a window holds two. +""" +from common import kernel_root, output_dir, rustc, flat_bindings +import hashlib +import json +import os +import pathlib +import re +import shlex +import subprocess +import tempfile + +ROOT = kernel_root() +OUT = output_dir() +BACKEND = ROOT / 'drivers/gpu/drm/asahi/g16' +FLAT = flat_bindings() + + +def function(text, name): + marker = text.index('fn ' + name + '(') + start = text.rfind('\n', 0, marker) + 1 + at = text.index('{', marker) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +def block(text, declaration): + start = text.index(declaration) + at = text.index('{', start) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +command = (BACKEND / 'command.rs').read_text() +engine = (BACKEND / 'engine.rs').read_text() +admission = '\n'.join(function(command, name) for name in + ['check_intersection', 'check_render_ray', 'check_compute_ray']) +conversion = '\n'.join(function(engine, name) for name in ['compute_rt', 'stage_rt']) +# The client address map, which bounds SCS pools (SCS_POOL_WINDOW). +client = block((BACKEND / 'hw.rs').read_text(), 'pub(crate) mod client {') +long = block(command, 'impl Command {') +for text in ('admission', 'conversion', 'long'): + globals()[text] = globals()[text].replace('super::rt::', 'rt::') + +# The feature word: the bits params.rs adds, from the real header, plus the shared +# VM_STATUS and VM_STATUS_MIRROR of file.rs. +params = (BACKEND / 'params.rs').read_text() +statement = params[params.index('params.features |='):] +statement = statement[:statement.index(';')] +names = re.findall(r'drm_asahi_feature_(DRM_ASAHI_FEATURE_\w+)', statement) +with tempfile.TemporaryDirectory(prefix='m4-rt-features-') as name: + directory = pathlib.Path(name) + source = directory / 'features.c' + header = ROOT / 'include/uapi/drm/asahi_drm.h' + source.write_text('#include \n#include ' + json.dumps(str(header)) + '\nint main(void){printf("%#llx\\n",' + '(unsigned long long)(' + ' | '.join(names + ['DRM_ASAHI_FEATURE_VM_STATUS', + 'DRM_ASAHI_FEATURE_VM_STATUS_MIRROR']) + '));return 0;}\n') + binary = directory / 'features' + subprocess.run(shlex.split(os.environ.get('CC', 'cc')) + ['-std=gnu11', '-Wall', '-Werror', '-D__user=', + '-idirafter', str(header.parents[1]), str(source), '-o', str(binary)], check=True) + features = int(subprocess.run([str(binary)], check=True, capture_output=True, text=True).stdout, 16) +assert features == 0x4001fc02, hex(features) +assert sorted(names) == sorted(['DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS', 'DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS', + 'DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS', 'DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS', + 'DRM_ASAHI_FEATURE_FEW_PRIMITIVES', 'DRM_ASAHI_FEATURE_RENDER_RAY_QUERY', + 'DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD']), names +print(f'feature word {features:#x} (RENDER_RAY_QUERY | BOUNDED_AS_BUILD added to G16G features)') + +harness = r''' +#![allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals, unused_imports)] +extern crate self as kernel; +pub mod prelude { + pub type Result = core::result::Result; + pub const EINVAL: i32 = -22; pub const E2BIG: i32 = -7; pub const EOVERFLOW: i32 = -75; +} +use prelude::*; +const ENOENT: i32 = -2; +mod uapi { include!("@FLAT@"); } +mod hw { + pub mod engine { pub const COMPUTE_SEED: u32 = 0x100; } + pub mod sizes { pub const BASE_RENDER_SLOTS: usize = 2; } + @CLIENT@ +} +mod fw { + #[path = "@BACKEND@/fw/graph.rs"] pub mod graph; + #[path = "@BACKEND@/fw/work.rs"] pub mod work; +} +#[path = "@BACKEND@/encode.rs"] mod encode; +#[path = "@BACKEND@/rt.rs"] mod rt; +#[path = "@BACKEND@/recovery/logic.rs"] mod logic; +use encode::{ComputeRt, StageRt}; +use fw::work::{compute, fs, ta}; + +mod mmu { pub struct Vm { pub mapped: Vec<(u64, u64)> } } +/// Readable mappings only; the production span rules have their own tests. +fn cover(vm: &mmu::Vm, start: u64, end: u64, _read: bool, _write: bool) -> Result { + if vm.mapped.iter().any(|&(a, b)| a <= start && end <= b) { Ok(()) } else { Err(ENOENT) } +} +struct SpanBatch; +impl SpanBatch { + fn push(&mut self, vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { + cover(vm, start, end, read, write) + } +} +struct Context<'a> { vm: &'a mmu::Vm, usc_base: u64, active_cores: u32, render_scs: [u16; 2] } +@ADMISSION@ +@CONVERSION@ +type KBox = Box; +struct RenderCommand { ray_query: [rt::RayQueryStage; 2], scs: rt::ScsSeeds } +struct ComputeCommand { ray: rt::ComputeRay, scs: rt::ScsSeeds, as_build: bool } +enum Command { Render(KBox), Compute(KBox) } +@LONG@ + +// Mesa's three T1 layouts: depth 112, 96 cliques, driver 40, 88 and 304 bytes. +const LAYOUTS: [(u64, u16); 3] = [(0x0028000060000070, 791), (0x0058000060010070, 827), (0x0130000060010070, 989)]; +const POOL: u64 = 0x10000; +fn tables() -> rt::IntersectionTables { + rt::IntersectionTables::new(POOL, 0x4000, 1, 112, 0x10010020000, 0x16000000000).unwrap() +} +fn ray(layout: u64) -> rt::ComputeRay { + rt::ComputeRay::new(layout, 0, 0, POOL, 0x4000, 1, 112, 0x10010020000, 0x16000000000).unwrap() +} +fn stage(layout: u64) -> rt::RayQueryStage { + rt::RayQueryStage { intersection: tables(), scratch: rt::ScratchRequest::new(layout).unwrap() } +} +fn records(w: &[u8], at: usize, count: usize) -> Vec<(u32, u64)> { + (0..count).map(|i| { + let r = &w[at + i * 12..at + i * 12 + 12]; + (u32::from_le_bytes(r[..4].try_into().unwrap()), u64::from_le_bytes(r[4..].try_into().unwrap())) + }).collect() +} +fn u16_at(w: &[u8], at: usize) -> usize { u16::from_le_bytes([w[at], w[at + 1]]) as usize } +fn u32_at(w: &[u8], at: usize) -> u32 { u32::from_le_bytes(w[at..at + 4].try_into().unwrap()) } + +#[test] +fn empty_ray_state_converts_to_the_words_g16g_always_wrote() { + assert_eq!(compute_rt(&rt::ComputeRay::NONE, 8192), ComputeRt::DISABLED); + assert_eq!(stage_rt(&rt::RayQueryStage::NONE), StageRt::DISABLED); + // Payload-free layouts and table-less commands are the same empty state. + let quiet = rt::ComputeRay::new(0x0000_0000_6000_0070, 0, 0, 0, 0, 0, 0, 0, 0).unwrap(); + assert_eq!(compute_rt(&quiet, 8192), ComputeRt::DISABLED); + assert_eq!(StageRt::DISABLED.window | 1 << 9, 0xff0200); + assert!(!encode::compute_encoder_gate()); +} + +fn compute_refs() -> encode::ComputeRefs { + let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; + encode::ComputeRefs { + notifier: f + 0x600400, qinfo: f + 0x200000, user_stamp: f + 0x600648, fw_stamp: f + 0x600640, + work: f + 0x100000, work_gva: g + 0x100000, seq: f + 0x100900, preempt_gva: g + 0x200000, + its: f + 0x1008c0, stats_fw: f + 0x300000, auxiliary_fw: f + 0x400000, auxiliary_gva: g + 0x400000, + context_store_gva: g + 0x500000, counter_fw: f + 0x500000, pool_state_gva: g + 0x600000, + page_list_gva: g + 0x700000, usc_base: 1 << 40, record_fw: f + 0x700000, binding_generation: 1, + uma_slot: 1, event: compute::EVENT, command_id: 1, compute_index: 0, work_818: 0, target_stamp: 0x100, submitted: 1, + } +} + +fn encode_compute(layout: &compute::Layout, rt_words: &ComputeRt) -> core::result::Result<[u8; compute::WORK_SIZE], encode::ComputeEncodeError> { + let c = uapi::drm_asahi_cmd_compute { cdm_ctrl_stream_base: 0x1000300000, cdm_ctrl_stream_end: 0x1000300200, ..Default::default() }; + let mut w = [0xa5; compute::WORK_SIZE]; let mut q = [0xa5; compute::SEQ_SIZE]; + encode::encode_compute_rt(layout, &compute_refs(), &c, &[], &[0; 2], 1, 1, 1, rt_words, &mut w, &mut q)?; + Ok(w) +} + +#[test] +fn compute_rt_words_land_in_the_25f84_register_slots_only() { + for layout in [&compute::V25G83, &compute::V26B123] { + let plain = encode_compute(layout, &ComputeRt::DISABLED).unwrap(); + assert_eq!(u16_at(&plain, 0x728), 25); + let plain_regs = records(&plain, compute::REGS, 25); + let d = compute::DESCRIPTOR; + // A base unit's descriptor: 16384 records, 8192 seeds, 16 rows x 8. + assert_eq!((u32_at(&plain, d + 0x1c), u32_at(&plain, d + 0x24), u32_at(&plain, d + 0x2c), u32_at(&plain, d + 0x48)), + (16384, 8192, 8192, 128)); + for (layout_word, pages) in LAYOUTS { + let words = compute_rt(&ray(layout_word), 28672); + let w = encode_compute(layout, &words).unwrap(); + // macOS 27.2 on the J773g: 0x017e1 = 1 first, 0x017d9 = 1 last. + assert_eq!((u16_at(&w, 0x728), u16_at(&w, 0x72a)), (27, 27 * 12)); + let got = records(&w, compute::REGS, 27); + assert_eq!((got[0], got[26]), ((0x017e1, 1), (0x017d9, 1))); + assert!(got.iter().all(|&(sel, _)| sel != 0x1a141), "gated register"); + let expect = |sel: u32| got.iter().find(|r| r.0 == sel).unwrap().1; + let mib = u64::from(pages).div_ceil(256); + assert_eq!(expect(0x101d1), u64::from(pages) | mib << 16); + assert_eq!((expect(0xd479), expect(0x1a0e9), expect(0x107a1)), (0x2c, 112, 1 << 24 | 0x60 << 16)); + assert_eq!([expect(0x1a089), expect(0x1a091), expect(0x1a059), expect(0x1a061), expect(0x1a0b9), expect(0x1a0c1)], + [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]); + // An SCS pool's descriptor: the 0x80000-record freelist, 56 rows x 8. + assert_eq!((u32_at(&w, d + 0x1c), u32_at(&w, d + 0x24), u32_at(&w, d + 0x2c), u32_at(&w, d + 0x48)), + (0x80000, 28672, 28672, 448)); + // Between the two records the list is the plain one, only the ten RT words differ. + let rt_sels = [0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1, 0x101d1, 0xd479, 0x1a0e9, 0x107a1]; + for (&(sel, value), &(plain_sel, plain_value)) in got[1..26].iter().zip(plain_regs.iter()) { + assert_eq!(sel, plain_sel); + assert!(value == plain_value || rt_sels.contains(&sel), "{sel:#x}"); + } + // Nothing else moves: the register list, its count and the pool's descriptor words. + let regs = compute::REGS..compute::REGS + 27 * 12; + let pool_words = [0x1c, 0x24, 0x2c, 0x48]; + for (i, (a, b)) in plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!(regs.contains(&i) || (0x728..0x72c).contains(&i) + || pool_words.iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); + } + } + } + // Seeds are whole rows within the freelist, which is never smaller than a base one. + for seeds in [0, 8191, 8704 + 64, 16896] { + let words = ComputeRt { seeds, ..ComputeRt::DISABLED }; + assert!(encode_compute(layout, &words).is_err(), "seeds {seeds}"); + } + assert!(encode_compute(layout, &ComputeRt { seeds: 8704, ..ComputeRt::DISABLED }).is_ok()); + assert!(encode_compute(layout, &ComputeRt { seeds: 8192, records: 8192, ..ComputeRt::DISABLED }).is_err()); + // The pool's size moves only its seed counts and row words. + let small = encode_compute(layout, &compute_rt(&ray(LAYOUTS[2].0), 18432)).unwrap(); + let large = encode_compute(layout, &compute_rt(&ray(LAYOUTS[2].0), rt::MAX_SCS_SEEDS)).unwrap(); + assert_eq!((u32_at(&small, d + 0x1c), u32_at(&small, d + 0x2c), u32_at(&small, d + 0x48)), (0x80000, 18432, 288)); + assert_eq!((u32_at(&large, d + 0x1c), u32_at(&large, d + 0x2c), u32_at(&large, d + 0x48)), (0x80000, 31744, 496)); + for (i, (a, b)) in small.iter().zip(large.iter()).enumerate() { + if a != b { assert!([0x24, 0x2c, 0x48].iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); } + } + } +} + +fn render_refs() -> (encode::RenderRefs, encode::PassRefs, uapi::drm_asahi_cmd_render) { + let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; + let mut u = uapi::drm_asahi_cmd_render::default(); + u.width_px = 64; u.height_px = 64; u.layers = 1; u.samples = 1; u.utile_width_px = 32; u.utile_height_px = 32; + u.sample_size_B = 4; u.vdm_ctrl_stream_base = g + 0xa00000; u.isp_scissor_base = g + 0xb00000; + let r = encode::RenderRefs { + notifier: f + 0x800000, qinfo: [f + 0xf00000, f + 0x1000000], user_stamp: [f + 0x800620, f + 0x800630], + fw_stamp: [f + 0x4000000, f + 0x4004000], uma_mgr: [f + 0x300000; 2], uma_aux: [f + 0x300100, f + 0x300200], + uma_gpu: g + 0x6000000, pb_mgr: f + 0x3000000, scene_list: g + 0x500000, parameter_id: 1, generation: 1, + activity: [f + 0x900004, f + 0xa00008], counter: [2, 1], uma_submitted: 2, uuid: 0x123400, usc_base: 1 << 40, + ..Default::default() + }; + let p = encode::PassRefs { + ta_work: f + 0xb00000, ta_work_gva: g + 0x7000000, fs_work: f + 0xc00000, fs_work_gva: g + 0x8000000, + ta_seq: f + 0xd00000, fs_seq: f + 0xe00000, scene: f + 0x100000, tpc_gva: g + 0x200000, tpc_fw: f + 0x3200000, + tilemap_gva: g + 0x100000, heap_gva: g + 0x300000, scene_user_gva: g + 0x900000, scratch_fw: f + 0x200000, + pre_gva: [g + 0x600000, g + 0x700000, g + 0x800000], aux_gva: g + 0xb00000, ..Default::default() + }; + (r, p, u) +} + +#[test] +fn render_stage_words_land_in_the_ta_and_fs_register_slots_only() { + let (r, p, u) = render_refs(); + let geo = encode::Geometry::new(&u, p.heap_gva); + let ta_rt = |words: &StageRt, layout: &ta::Layout| { + let mut w = [0xa5; ta::WORK_SIZE]; let mut q = [0xa5; ta::SEQ_SIZE]; + encode::encode_ta_rt(layout, &r, &p, &u, &[0; 4], 1, 0x100, &geo, None, words, &mut w, &mut q); (w, q) + }; + let fs_rt = |words: &StageRt, layout: &fs::Layout| { + let mut w = [0xa5; fs::WORK_SIZE]; let mut q = [0xa5u8; fs::SEQ_SIZE]; + encode::encode_fs_rt(layout, &r, &p, &u, &[0; 4], 1, 1 << 40, 1, 0x100, &geo, words, &mut w, &mut q); (w, q) + }; + for (tl, fl) in [(&ta::V25G83, &fs::V25G83), (&ta::V26B123, &fs::V26B123)] { + let (ta_plain, taq_plain) = ta_rt(&StageRt::DISABLED, tl); + let (fs_plain, fsq_plain) = fs_rt(&StageRt::DISABLED, fl); + for (layout_word, pages) in LAYOUTS { + let mut s = stage(layout_word); + // The auxiliary word is validated, not written: the tail stays the scratch tail. + let mut wire = [0u8; 48]; + wire[0..4].copy_from_slice(&16u32.to_le_bytes()); + wire[8..16].copy_from_slice(&POOL.to_le_bytes()); wire[16..24].copy_from_slice(&0x4000u64.to_le_bytes()); + wire[24..28].copy_from_slice(&1u32.to_le_bytes()); wire[28..32].copy_from_slice(&112u32.to_le_bytes()); + wire[32..40].copy_from_slice(&0x10010020000u64.to_le_bytes()); wire[40..48].copy_from_slice(&0x16000000000u64.to_le_bytes()); + s.intersection = rt::IntersectionTables::parse(&wire).unwrap(); + let words = stage_rt(&s); + let size = u64::from(pages) | u64::from(pages).div_ceil(256) << 16; + let window = 1 << 24 | 0x60 << 16; + let ift = [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]; + let (w, q) = ta_rt(&words, tl); + assert_eq!(q, taq_plain); + assert_eq!((u16_at(&w, 0x748), u16_at(&w, 0x74a)), (68, 68 * 12)); + let ta_plain_regs = records(&ta_plain, ta::REGS, 66); + let got = records(&w, ta::REGS, 68); + assert_eq!((got[0], got[67]), ((0x017e1, 1), (0x017d9, 1))); + let value = |got: &Vec<(u32, u64)>, sel: u32| got.iter().find(|r| r.0 == sel).unwrap().1; + let ta_rt_sels = [0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799]; + assert_eq!([0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1].map(|s| value(&got, s)), ift); + assert_eq!([0x101c9, 0xd471, 0x1a0f1, 0x10799].map(|s| value(&got, s)), [size, 0x2c, 112, window]); + for (&(sel, val), &(psel, pval)) in got[1..67].iter().zip(ta_plain_regs.iter()) { + assert_eq!(sel, psel); + assert!(val == pval || ta_rt_sels.contains(&sel), "TA {sel:#x}"); + } + for (i, (a, b)) in ta_plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!((ta::REGS..ta::REGS + 68 * 12).contains(&i) || (0x748..0x74c).contains(&i), "TA byte {i:#x}"); + } + } + let (w, q) = fs_rt(&words, fl); + assert_eq!(q, fsq_plain); + assert_eq!((u16_at(&w, 0x788), u16_at(&w, 0x78a)), (84, 84 * 12)); + let fs_plain_regs = records(&fs_plain, fs::REGS, 82); + let got = records(&w, fs::REGS, 84); + assert_eq!((got[0].0, got[1], got[83]), (0x1739, (0x017e1, 1), (0x017d9, 1))); + let fs_rt_sels = [0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, 0x1a0d9, 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0x10791]; + assert_eq!([0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, 0x1a0d9, 0x1a0e1].map(|s| value(&got, s)), ift); + assert_eq!([0x101c1, 0xd469, 0x1a0f9, 0x10791].map(|s| value(&got, s)), [size, 0x2c, 112, window | 1 << 9]); + assert_eq!(got[0], fs_plain_regs[0]); + for (&(sel, val), &(psel, pval)) in got[2..83].iter().zip(fs_plain_regs[1..].iter()) { + assert_eq!(sel, psel); + assert!(val == pval || fs_rt_sels.contains(&sel), "FS {sel:#x}"); + } + for (i, (a, b)) in fs_plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!((fs::REGS..fs::REGS + 84 * 12).contains(&i) || (0x788..0x78c).contains(&i), "FS byte {i:#x}"); + } + } + } + } +} + +#[test] +fn scratch_requests_follow_the_gen1_section_model() { + for (layout, pages) in LAYOUTS { + let s = rt::ScratchRequest::new(layout).unwrap(); + assert_eq!(s.pages(), pages); + assert_eq!((s.tail_word(), s.stack_word(), s.window_word(), s.driver_word()), (0x2c, 112, 0x1600000, 0)); + // Both compute and render stages use macOS 27.2's J773g 0x2c tail reservation. + assert_eq!(s.compute_tail_word(), 0x2c); + } + assert_eq!(rt::ScratchRequest::NONE.compute_tail_word(), 0); + // Payload-free: no scratch even with depth and cliques. + assert_eq!(rt::ScratchRequest::new(0x0000_0000_ff00_ffff).unwrap(), rt::ScratchRequest::NONE); + // The smallest request is Apple's 89-page floor plus the guard page. + assert_eq!(rt::ScratchRequest::new(1 << 32).unwrap().pages(), 89); + // More than 2^16 pages, and a stack word that overflows, are refused. + assert_eq!(rt::ScratchRequest::new(0xffff_0000_ff00_ffff), Err(EINVAL)); + assert_eq!(rt::ScratchRequest::new(0x0000_ffff_ff00_0000), Err(EINVAL)); +} + +#[test] +fn scs_sizing_is_the_m4_pro_formula_in_whole_rows() { + // Per core: pages + ceil(pages / 256) + 8. + assert_eq!(rt::extra_pages(10, 791), Ok(10 * (791 + 4 + 8))); + assert_eq!(rt::extra_pages(10, 256), Ok(10 * (256 + 1 + 8))); + assert_eq!(rt::extra_pages(10, 257), Ok(10 * (257 + 2 + 8))); + assert_eq!(rt::extra_pages(10, 0), Ok(0)); + assert_eq!(rt::extra_pages(0, 791), Err(EINVAL)); + assert_eq!(rt::required_seeds(10, &[]), Ok(8192)); + assert_eq!(rt::required_seeds(10, &[0, 0]), Ok(8192)); + // Mesa's three T1 layouts on a 10-core M4: base 8192 + 10 x (pages + pages/256 + 8). + assert_eq!(rt::required_seeds(10, &[791]), Ok(16384)); + assert_eq!(rt::required_seeds(10, &[827]), Ok(16896)); + assert_eq!(rt::required_seeds(10, &[989]), Ok(18432)); + assert_eq!(rt::required_seeds(8, &[827]), Ok(15360)); + assert_eq!(rt::required_seeds(1, &[89]), Ok(8704)); + // Both stages of one render add up. + assert_eq!(rt::required_seeds(10, &[89, 89]), Ok(8192 + 2048)); + assert_eq!(rt::required_seeds(10, &[791, 89]), Ok(17408)); + assert_eq!(rt::required_seeds(10, &[989, 989]), Ok(28672)); + // Freelists: a base pool keeps 16384 records over 0x20000 bytes; an SCS pool gets the + // 0x80000 records over 4 MiB that macOS 27.2 writes on the J773g. + assert_eq!((rt::freelist_records(8192), rt::freelist_bytes(8192)), (16384, 0x20000)); + for seeds in [8704, 16384, 28672, rt::MAX_SCS_SEEDS] { + assert_eq!((rt::freelist_records(seeds), rt::freelist_bytes(seeds)), (0x80000, 0x400000)); + } + // The largest pool: 62 2-MiB rows, whose 124 MiB and 4-MiB freelist fill a 128 MiB window + // (63 rows and their freelist would not). + assert_eq!(rt::MAX_SCS_SEEDS, 62 * 512); + assert!(rt::window_bytes(rt::MAX_SCS_SEEDS) <= hw::client::SCS_POOL_WINDOW); + assert!(rt::window_bytes(rt::MAX_SCS_SEEDS + 512) > hw::client::SCS_POOL_WINDOW); + assert_eq!(rt::required_seeds(10, &[2337]), Ok(31744)); + assert_eq!(rt::required_seeds(10, &[2338]), Err(E2BIG)); + assert_eq!(rt::required_seeds(10, &[1164, 1164]), Ok(31744)); + assert_eq!(rt::required_seeds(10, &[1165, 1165]), Err(E2BIG)); + // Pools are created for two stages at the larger request, or the request if two do not fit. + assert_eq!(rt::pool_seeds(10, [791, 0]), Ok(24576)); + assert_eq!(rt::pool_seeds(10, [827, 0]), Ok(25088)); + assert_eq!(rt::pool_seeds(10, [0, 989]), rt::required_seeds(10, &[989, 989])); + assert_eq!(rt::pool_seeds(10, [2000, 0]), rt::required_seeds(10, &[2000])); + assert_eq!(rt::pool_seeds(10, [2338, 0]), Err(E2BIG)); + assert_eq!(rt::pool_seeds(10, [0, 0]), Ok(8192)); + // Extremes: refused, never wrapped (overflow checks are on). + assert_eq!(rt::required_seeds(u32::MAX, &[u16::MAX, u16::MAX]), Err(E2BIG)); + assert_eq!(rt::required_seeds(u32::MAX, &[u16::MAX; 64]), Err(E2BIG)); + assert_eq!(rt::required_seeds(0, &[1]), Err(EINVAL)); + for cores in 1..=10 { for pages in [89u16, 200, 500, 791, 1000] { + if let Ok(seeds) = rt::required_seeds(cores, &[pages]) { + assert_eq!(seeds % rt::SEEDS_PER_ROW, 0); + assert!(u64::from(seeds) >= 8192 + rt::extra_pages(cores, pages).unwrap() && seeds <= rt::MAX_SCS_SEEDS); + } + }} +} + +#[test] +fn ray_and_as_build_admission() { + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000), (0x10010020000, 0x10010020040)] }; + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [791, 0] }; + let scs = |needed, pool| rt::ScsSeeds { needed, pool }; + let mut b = SpanBatch; + // Admission returns the pool the command needs, and the one created for it: compute for two + // dispatches. + assert_eq!(check_compute_ray(&mut b, &context, &ray(LAYOUTS[0].0)), Ok(scs(16384, 24576))); + assert_eq!(check_compute_ray(&mut b, &context, &ray(LAYOUTS[1].0)), Ok(scs(16896, 25088))); + // 4 KiB of driver bytes per thread: 3833 pages per core, more than a window holds. + let huge = 0x1000_0000_6000_0070; + assert_eq!(rt::ScratchRequest::new(huge).unwrap().pages(), 3833); + assert_eq!(check_compute_ray(&mut b, &context, &ray(huge)), Err(E2BIG)); + let unmapped = mmu::Vm { mapped: vec![(POOL, POOL + 0x3000), (0x10010020000, 0x10010020040)] }; + let narrow = Context { vm: &unmapped, ..context }; + assert_eq!(check_compute_ray(&mut b, &narrow, &ray(LAYOUTS[0].0)), Err(ENOENT)); + let no_program = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000)] }; + assert_eq!(check_compute_ray(&mut b, &Context { vm: &no_program, ..context }, &ray(LAYOUTS[0].0)), Err(ENOENT)); + let tables_only = rt::ComputeRay::new(0, 0, 0, POOL, 0x4000, 1, 112, 0, 0).unwrap(); + assert_eq!(check_compute_ray(&mut b, &Context { vm: &no_program, ..context }, &tables_only), Ok(rt::ScsSeeds::NONE)); + // Renders: within the queue's reservation, either stage; beyond it EINVAL. The pool created + // for them holds two stages of the reservation's larger one. + let none = rt::RayQueryStage::NONE; + let small = stage(1 << 32 | 0x6000_0000); + assert_eq!(check_render_ray(&mut b, &context, &[stage(LAYOUTS[0].0), none]), Ok(scs(16384, 24576))); + assert_eq!(check_render_ray(&mut b, &context, &[none, small]), Ok(scs(9216, 24576))); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [0, 0], ..context }, &[none, small]), Err(EINVAL)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [89, 89], ..context }, &[small, small]), Ok(scs(10240, 10240))); + assert_eq!(check_render_ray(&mut b, &context, &[stage(LAYOUTS[1].0), none]), Err(EINVAL)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [3833, 0], ..context }, &[stage(huge), none]), Err(E2BIG)); + assert_eq!(check_render_ray(&mut b, &Context { vm: &unmapped, ..context }, &[stage(LAYOUTS[0].0), none]), Err(ENOENT)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [0, 0], ..context }, &[none, none]), Ok(rt::ScsSeeds::NONE)); + // Flags: AS_BUILD alone. + assert_eq!(rt::as_build(0), Some(false)); assert_eq!(rt::as_build(4), Some(true)); + for flag in [1, 2, 8, 1 << 16, 1 << 17, 1 << 20, 5, 6] { assert_eq!(rt::as_build(flag), None); } +} + +// The commands Mesa's G16G ray-query path (ASAHI_MESA_DEBUG=g16grt, mesa 3ff3d359) submits on a +// 10-core M4: hk_gen1_ray_query_scs_layout() is 0x0130000060010070 with the candidate profile, +// the intersection pool is one 16-KiB IFT (first 1, count 112), the default program +// 0x10010020000 with control 0x16000000000. dEQP-VK.ray_query.* compute, chit/ahit and +// dynamic-indexing cases submit the compute shape; .vert/.frag/.tesc cases reserve the render +// stage at QUEUE_CREATE (hk_queue_ensure_drm) and submit a render with it. Before SCS pools were +// sized from the request, every one of them was refused with E2BIG, which Mesa reports as +// VK_ERROR_DEVICE_LOST at vkQueueSubmit. +#[test] +fn mesa_g16grt_ray_query_commands_are_admitted() { + let mesa = LAYOUTS[2].0; + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000), (0x10010020000, 0x10010020040)] }; + let pages = rt::ScratchRequest::new(mesa).unwrap().pages(); + assert_eq!(pages, 989); + // QUEUE_CREATE render_scs_layout: the vertex stage, the fragment stage, or both. The VM's + // SCS render pools a queue creates hold both stages, so a queue Mesa replaces to add the + // other stage still fits them. + for reservation in [[pages, 0], [0, pages], [pages, pages]] { + assert!(rt::required_seeds(10, &reservation).is_ok(), "QUEUE_CREATE {reservation:?}"); + assert_eq!(rt::pool_seeds(10, reservation), Ok(28672), "{reservation:?}"); + } + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [pages, pages] }; + let scs = |needed, pool| rt::ScsSeeds { needed, pool }; + let mut b = SpanBatch; + // Compute: 18432 for one dispatch, a 56-row pool for two. + assert_eq!(check_compute_ray(&mut b, &context, &ray(mesa)), Ok(scs(18432, 28672))); + let none = rt::RayQueryStage::NONE; + for (stages, needed) in [([stage(mesa), none], 18432), ([none, stage(mesa)], 18432), ([stage(mesa), stage(mesa)], 28672)] { + assert_eq!(check_render_ray(&mut b, &context, &stages), Ok(scs(needed, 28672))); + // A queue that reserved one stage creates pools that take both. + let one = Context { render_scs: [pages, 0], ..context }; + assert_eq!(check_render_ray(&mut b, &one, &[stage(mesa), none]).map(|s| s.pool), Ok(28672)); + } + // Their pools fit an SCS window, freelist included. + assert_eq!(rt::freelist_records(28672), 0x80000); + assert!(rt::window_bytes(28672) <= hw::client::SCS_POOL_WINDOW); +} + +#[test] +fn long_allowance_follows_g17_select_per_job() { + let render = |stages: [rt::RayQueryStage; 2]| Command::Render(Box::new(RenderCommand { ray_query: stages, scs: rt::ScsSeeds::NONE })); + let compute = |ray: rt::ComputeRay, as_build: bool| Command::Compute(Box::new(ComputeCommand { ray, scs: rt::ScsSeeds::NONE, as_build })); + let none = rt::RayQueryStage::NONE; + assert!(render([stage(LAYOUTS[0].0), none]).long() && render([none, stage(LAYOUTS[0].0)]).long()); + assert!(!render([none, none]).long() && render([none, none]).scs() == rt::ScsSeeds::NONE); + assert!(compute(ray(LAYOUTS[0].0), false).long() && compute(rt::ComputeRay::NONE, true).long()); + assert!(!compute(rt::ComputeRay::NONE, false).long()); + // Scratch alone is not traversal (as on the M4 Pro), but it needs an SCS pool; tables + // alone do not. + let scratch = rt::ComputeRay::new(LAYOUTS[0].0, 0, 0, 0, 0, 0, 0, 0, 0).unwrap(); + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000)] }; + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [0, 0] }; + let admitted = rt::ScsSeeds { needed: 16384, pool: 24576 }; + let mut b = SpanBatch; + assert!(!compute(scratch, false).long() && check_compute_ray(&mut b, &context, &scratch) == Ok(admitted)); + let tables = rt::ComputeRay::new(0, 0, 0, POOL, 0x4000, 1, 112, 0, 0).unwrap(); + assert_eq!(check_compute_ray(&mut b, &context, &tables), Ok(rt::ScsSeeds::NONE)); + // A command's SCS pool is what admission recorded. + let command = Command::Compute(Box::new(ComputeCommand { ray: scratch, scs: admitted, as_build: false })); + assert_eq!((command.scs(), compute(rt::ComputeRay::NONE, false).scs()), (admitted, rt::ScsSeeds::NONE)); + // Deadlines: at least ten seconds for a long job, never re-enabling a disabled one. + assert_eq!(logic::long_deadline_ms(5000), 10_000); + assert_eq!(logic::long_deadline_ms(10_000), 10_000); + assert_eq!(logic::long_deadline_ms(30_000), 30_000); + assert_eq!(logic::long_deadline_ms(0), 0); + assert_eq!(logic::long_deadline_ms(1), 10_000); + let now = 1_000_000_000; + let d = logic::Deadlines::renew(now, 5000, 5000); + assert_eq!((d.select(false, false), d.select(true, false)), (now + 5_000_000_000, now + 5_000_000_000)); + assert_eq!((d.select(false, true), d.select(true, true)), (now + 10_000_000_000, now + 10_000_000_000)); + let d = logic::Deadlines::renew(now, 5000, 0); + assert_eq!((d.select(true, false), d.select(true, true)), (u64::MAX, u64::MAX)); + assert_eq!(d.select(false, true), now + 10_000_000_000); + let d = logic::Deadlines::renew(u64::MAX - 1, 20_000, 50); + assert_eq!((d.select(false, true), d.select(true, false), d.select(true, true)), (u64::MAX, u64::MAX, u64::MAX)); + let d = logic::Deadlines::renew(now, 50, 50); + assert_eq!((d.select(false, false), d.select(true, true)), (now + 100_000_000, now + 10_000_000_000)); + assert_eq!(logic::Deadlines::EXPIRED.select(true, true), logic::EXPIRED); +} +''' +encode_source = (BACKEND / 'encode.rs').read_text() +# The compute encoder's gates, visible to this harness only through a tiny accessor. +gates = '\npub(crate) fn compute_encoder_gate() -> bool { compute_encoder::COMPUTE_SCS_DRIVER_WORD }\n' \ + 'pub(crate) fn render_encoder_gate() -> bool { render_encoder::RENDER_SCS_ENABLE }\n' +with tempfile.TemporaryDirectory(prefix='m4-rust-rt-') as name: + directory = pathlib.Path(name) + staged = directory / 'g16' + staged.mkdir() + # Stage the encoder with the gate accessors appended; the other modules come from the tree. + (staged / 'encode').mkdir() + for part in ['compute.rs', 'render.rs']: + (staged / 'encode' / part).write_text((BACKEND / 'encode' / part).read_text()) + (staged / 'encode.rs').write_text(encode_source + gates) + source = harness + for key, value in {'@FLAT@': str(FLAT), '@ADMISSION@': admission, '@CONVERSION@': conversion, + '@LONG@': long, '@CLIENT@': client}.items(): + source = source.replace(key, value) + source = source.replace('#[path = "@BACKEND@/encode.rs"]', '#[path = "' + str(staged / 'encode.rs') + '"]') + source = source.replace('@BACKEND@', str(BACKEND)) + source += '\n#[test] fn render_gate_is_on() { assert!(encode::render_encoder_gate()); }\n' + test = directory / 'test.rs' + test.write_text(source) + (OUT / 'ray-tracing-host.rs').write_text(source) + binary = directory / 'test' + subprocess.run(rustc() + ['--edition=2021', '-C', 'overflow-checks=yes', '--test', str(test), '-o', str(binary)], check=True) + result = subprocess.run([str(binary), '--nocapture'], text=True, capture_output=True) + print(result.stdout + result.stderr, end='') + (OUT / 'ray-tracing-host.log').write_text(result.stdout + result.stderr) + result.check_returncode() + tests = int(re.search(r'test result: ok\. (\d+) passed;', result.stdout)[1]) +(OUT / 'ray-tracing-host.json').write_text(json.dumps({ + 'result': 'pass', 'tests': tests, 'feature_word': hex(features), + 'scope': 'Production rt.rs, recovery/logic.rs and TA/FS/compute encoders, with command.rs admission and ' + 'engine.rs conversion copied verbatim; VM spans mocked. No GPU, firmware or Mesa.', + 'source_sha256': {name: hashlib.sha256((BACKEND / name).read_bytes()).hexdigest() for name in + ['rt.rs', 'recovery/logic.rs', 'command.rs', 'engine.rs', 'params.rs', 'encode.rs', 'hw.rs', + 'encode/compute.rs', 'encode/render.rs']}, +}, indent=2) + '\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 69138f4dd1135..f80781e1b20ae 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -232,6 +232,7 @@ def module(text, name): pub struct Events{pub grow:crate::KVec<[u32;18]>} pub struct Firmware{pub pools:pools::Pools,pub events:Events} pub mod budget{__BUDGET__} + #[path="__ROOT__/rt.rs"]pub mod rt; #[path="__ROOT__/slots.rs"]pub mod slots; #[path="__ROOT__/pools.rs"]pub mod pools; } @@ -653,7 +654,7 @@ def module(text, name): for idx in 0..g16::hw::sizes::EXT_PB_SLOTS { let local=(g16::hw::sizes::BASE_PB_SLOTS+idx) as u64; let hw_slot=(g16::hw::sizes::WARM_PB_SLOTS+idx) as u32; - let ext=g16::pools::Allocator::new_at(&mut o,&g16::object::Factory,local,hw_slot,pools.heap()).unwrap(); + let ext=g16::pools::Allocator::new_at(&mut o,&g16::object::Factory,local,hw_slot,pools.heap(),g16::slots::Placement::Base).unwrap(); assert_eq!(ext.refs().unwrap().parameter_id,hw_slot); } for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { @@ -753,13 +754,17 @@ def module(text, name): let pools=PoolSet::new_with_slots(&mut o,&f,[7,8]).unwrap(); assert_eq!(pools.unit(0).unwrap().id(),7); assert_eq!(pools.unit(1).unwrap().id(),8); + let scs=pools.scs(&mut o,&f,g16::hw::sizes::FREELIST_SEED + 512).unwrap(); + assert_eq!(scs.unit(0).unwrap().id(),7); + assert_eq!(scs.unit(1).unwrap().id(),8); assert_eq!( g16::pools::Allocator::new_at( &mut o, &f, g16::hw::sizes::MAX_VM_PB_SLOTS as u64, 0, - pools.heap() + pools.heap(), + g16::slots::Placement::Base ).err(), Some(EINVAL) ); @@ -769,14 +774,15 @@ def module(text, name): &f, 0, g16::hw::sizes::PB_SLOTS as u32, - pools.heap() + pools.heap(), + g16::slots::Placement::Base ).err(), Some(EINVAL) ); let mut uma_slots=Vec::new(); for k in 0..g16::hw::sizes::PB_SLOTS { let local=(k % g16::hw::sizes::MAX_VM_PB_SLOTS) as u64; - let alloc=g16::pools::Allocator::new_at(&mut o,&f,local,k as u32,pools.heap()).unwrap(); + let alloc=g16::pools::Allocator::new_at(&mut o,&f,local,k as u32,pools.heap(),g16::slots::Placement::Base).unwrap(); let refs=alloc.prepare_in_flight(1,false).unwrap(); assert_eq!(refs.parameter_id,k as u32); let desc=find_va(refs.uma_mgr[0]); @@ -906,33 +912,33 @@ def module(text, name): // and keeps 2 healthy slots (18, 19) for cross-VM switching. let vm_mask:u32=(1u32<<0)|(1u32<<1)|(((1u32< 1, "quarantined leases stay retained"); } + + #[test]fn dual_pipe_closed_compute_vms_pin_only_one_unit_per_pipe(){ + use g16::hw::sizes::COMPUTE_UNITS; + use g16::resources::{COMPUTE_OWNER_ARENAS, ComputeArena}; + use g16::slots::ComputeSlot; + + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); + } + let prep = ComputeArena { compute: compute_slots, render: None }; + + // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas + // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). + let mut vms = Vec::new(); + let mut vm_unit_arenas: Vec>> = Vec::new(); + for i in 0..8usize { + let v = vm(800 + i as u64); + let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); + for _ in 0..COMPUTE_UNITS { + per_unit.push( + sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), + ); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(v.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = None); + vms.push(v); + vm_unit_arenas.push(per_unit); + } + + // Close all 8 VMs and reclaim displaced leases: + // - Pipe 0 and pipe 1 each retain 1 undisplaced last-retired unit -> reusable == 22. + // - Out of 8 * 24 = 192 per-unit arenas, ONLY those 2 undisplaced units remain pinned + // (strong_count == 2); all 190 other units (including the other 23 units of each + // last-retired VM) drop immediately (strong_count == 1). + for v in &vms { + v.vm.close(); + } + assert!(s.reclaim_closed(), "two undisplaced dual-pipe units remain"); + assert_eq!(s.lifetime_counts()[0].reusable, (COMPUTE_UNITS - 2) as u32); + let pinned_units: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_units, 2, "must pin exactly 1 unit per CDM pipe, never a whole VM set"); + for (i, units) in vm_unit_arenas.iter().enumerate() { + let vm_pinned = units.iter().filter(|a| sync::Arc::strong_count(a) > 1).count(); + if i == 7 { + assert_eq!(vm_pinned, 2, "last VM holds only its 2 undisplaced units"); + } else { + assert_eq!(vm_pinned, 0, "displaced closed VM {i} holds 0 units"); + assert_eq!(sync::Arc::strong_count(&vms[i]), 1, "closed VM {i} fully released"); + } + } + + // Displace pipe 0 and pipe 1 with a live VM -> all 8 closed VMs and 192 units release. + let live = vm(900); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(live.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &live, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + assert!(!s.reclaim_closed(), "both dual-pipe closed leases displaced and reclaimed"); + let pinned_after: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_after, 0); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); + } + } + #[test]fn closed_vm_reclaim_retains_firmware_pb_and_uma_leases_until_overwritten(){ use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; @@ -2459,90 +2558,6 @@ def module(text, name): let _ = WARM_PB_SLOTS; } - #[test]fn dual_pipe_closed_compute_vms_pin_only_one_unit_per_pipe(){ - use g16::hw::sizes::COMPUTE_UNITS; - use g16::resources::{COMPUTE_OWNER_ARENAS, ComputeArena}; - use g16::slots::ComputeSlot; - - let mut o = Objects::new(); - let mut s = Slots::new().unwrap(); - let mut compute_slots = KVec::new(); - for k in 0..COMPUTE_UNITS { - compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); - } - let prep = ComputeArena { compute: compute_slots, render: None }; - - // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas - // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). - let mut vms = Vec::new(); - let mut vm_unit_arenas: Vec>> = Vec::new(); - for i in 0..8usize { - let v = vm(800 + i as u64); - let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); - for _ in 0..COMPUTE_UNITS { - per_unit.push( - sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), - ); - } - COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); - for pipe in [0usize, 1usize] { - let mut c = Claims::new(); - let k = s.claim_compute_for_pipe(&prep, &mut c, Some(v.id), pipe).unwrap().unwrap(); - s.hold_compute_slot(k, &v, &prep).unwrap(); - s.publish(&mut c).unwrap(); - s.retire(&mut c).unwrap(); - } - COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = None); - vms.push(v); - vm_unit_arenas.push(per_unit); - } - - // Close all 8 VMs and reclaim displaced leases: - // - Pipe 0 and pipe 1 each retain 1 undisplaced last-retired unit -> reusable == 22. - // - Out of 8 * 24 = 192 per-unit arenas, ONLY those 2 undisplaced units remain pinned - // (strong_count == 2); all 190 other units (including the other 23 units of each - // last-retired VM) drop immediately (strong_count == 1). - for v in &vms { - v.vm.close(); - } - assert!(s.reclaim_closed(), "two undisplaced dual-pipe units remain"); - assert_eq!(s.lifetime_counts()[0].reusable, (COMPUTE_UNITS - 2) as u32); - let pinned_units: usize = vm_unit_arenas - .iter() - .flat_map(|units| units.iter()) - .filter(|arena| sync::Arc::strong_count(arena) > 1) - .count(); - assert_eq!(pinned_units, 2, "must pin exactly 1 unit per CDM pipe, never a whole VM set"); - for (i, units) in vm_unit_arenas.iter().enumerate() { - let vm_pinned = units.iter().filter(|a| sync::Arc::strong_count(a) > 1).count(); - if i == 7 { - assert_eq!(vm_pinned, 2, "last VM holds only its 2 undisplaced units"); - } else { - assert_eq!(vm_pinned, 0, "displaced closed VM {i} holds 0 units"); - assert_eq!(sync::Arc::strong_count(&vms[i]), 1, "closed VM {i} fully released"); - } - } - - // Displace pipe 0 and pipe 1 with a live VM -> all 8 closed VMs and 192 units release. - let live = vm(900); - for pipe in [0usize, 1usize] { - let mut c = Claims::new(); - let k = s.claim_compute_for_pipe(&prep, &mut c, Some(live.id), pipe).unwrap().unwrap(); - s.hold_compute_slot(k, &live, &prep).unwrap(); - s.publish(&mut c).unwrap(); - s.retire(&mut c).unwrap(); - } - assert!(!s.reclaim_closed(), "both dual-pipe closed leases displaced and reclaimed"); - let pinned_after: usize = vm_unit_arenas - .iter() - .flat_map(|units| units.iter()) - .filter(|arena| sync::Arc::strong_count(arena) > 1) - .count(); - assert_eq!(pinned_after, 0); - for (i, v) in vms.iter().enumerate() { - assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); - } - } // A closed VM's PB slot 3 is displaced by slot 4 and reclaimed. pb_mgr_table[3] still names // its epoch's manager; gPM_SP(0) wrote that manager's page list (DYNAMIC, 0x704000cb40) @@ -2593,7 +2608,7 @@ def module(text, name): // A new VM's InitBM epoch rebinds slot 3. The old binding stays intact while that // render is in flight and goes only with its full retirement. let z = vm(48); - assert_eq!(p.pick_slot_in_mask_blocks(&z, false, 0b11000, 3, 512), Some(3)); + assert_eq!(p.pick_slot_in_mask_blocks_mode(&z, false, 0b11000, 3, 512, false), Some(3)); let ez = epoch(&z, 3); let bz = p.bind(3, false); p.hold_alloc(3, &z, None, None).unwrap(); @@ -2655,7 +2670,7 @@ def module(text, name): source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() assert 'pub(crate) struct ComputeUnitSet {' in resources_source, 'resources.rs must split compute units into per-unit ComputeArenas' -assert 'ComputeArena::new(factory, bind, vm, live, k)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' +assert 'ComputeArena::new(factory, bind, vm, live, k, placement)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' assert 'compute_ext: Option>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' assert 'base.arena(k)' in resources_source and 'ext.arena(k - base.len())' in resources_source, 'Prepared::compute_arena must return the per-unit ComputeArena' ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') From b2a65d203ce372d2b7f9478ba62e34b96ec7df2b Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 15:50:14 -0500 Subject: [PATCH 2/7] drm/asahi: g16: route SCS compute and base PB slots around quarantined slots After a firmware compute recovery permanently quarantines compute unit 0, brand-new VMs using the 2-unit SCS compute layout previously pinned themselves to hardware slots 0..2. Their first compute submission claimed and retired on unit 1 (the sole healthy slot in 0..2), leaving unit 1 as pipe 0's undisplaced latest retired lease so the second compute submission saw compute_exhausted_within(2) == true and immediately failed with ECANCELED, poisoning every subsequent fresh process. Track the live quarantined compute mask in Shared::quarantined_compute_mask and route ComputeUnitSet::new_scs onto two healthy hardware slots, preferring the pipe-0-reserved 0..PIPE1_COMPUTE_START range so pipe 1 cannot pin an undisplaced lease on SCS slots, then falling back across the remaining units. Apply the matching quarantined-slot skip when picking base warm PB slots for new render arenas. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 33 ++-- drivers/gpu/drm/asahi/g16/hw.rs | 12 +- drivers/gpu/drm/asahi/g16/mod.rs | 3 + drivers/gpu/drm/asahi/g16/poll.rs | 3 + drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 25 +++ drivers/gpu/drm/asahi/g16/queue.rs | 1 + drivers/gpu/drm/asahi/g16/resources.rs | 160 ++++++++++++++-- drivers/gpu/drm/asahi/g16/slots.rs | 116 +++++++++--- .../drivers/gpu/asahi-m4/test-publication.py | 34 ++-- .../drivers/gpu/asahi-m4/test-resources.py | 176 ++++++++++++++---- 10 files changed, 451 insertions(+), 112 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 26009c05701a5..64467a397408a 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1114,8 +1114,8 @@ impl Firmware { && matches!(command(&job, job.progress.sent()), Some(Command::Compute(_))) && job .resources - .compute_units() - .is_ok_and(|n| self.slots.compute_exhausted_within(n)) + .compute_slot_mask() + .is_ok_and(|mask| self.slots.compute_exhausted_in_mask(mask)) { self.engine.unpend(&job); let _ = job.mark_terminal_retired(); @@ -1351,8 +1351,8 @@ impl Firmware { && (compute_count >= params::compute_flights() || job .resources - .compute_units() - .is_ok_and(|units| !self.slots.compute_available(units))) + .compute_slot_mask() + .is_ok_and(|mask| !self.slots.compute_available_in_mask(mask))) } Some(Command::Render(_)) => { let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); @@ -1490,8 +1490,8 @@ impl Firmware { && super::recovery::logic::next_ordinal(e.ordinal).is_some() && job .resources - .compute_units() - .is_ok_and(|units| self.slots.compute_available(units)) + .compute_slot_mask() + .is_ok_and(|mask| self.slots.compute_available_in_mask(mask)) } Some(Command::Render(_)) => { let cross_vm_compute = e @@ -1796,8 +1796,9 @@ impl Firmware { } /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command: - /// - Base-only VMs (`units <= BASE_COMPUTE_UNITS`) or states where pipe 1 has no available - /// extension unit stay on pipe 0 so base units `0..2` never split across two pipes. + /// - Base-only/SCS VMs (bits strictly in `0..PIPE1_COMPUTE_START`) or states where pipe 1 + /// has no available unit in `slot_mask` stay on pipe 0 so `0..PIPE1_COMPUTE_START` never + /// split across two pipes. /// - If the command waits only on one pipe, reuse that pipe (in-order ring, zero `c2c` /// barrier). /// - If barrier-free (`[None, None]`) or waiting on both pipes (`[Some, Some]`), pick the @@ -1805,7 +1806,7 @@ impl Firmware { fn choose_compute_pipe( &self, waits: [Option; sizes::COMPUTE_PIPES], - units: usize, + slot_mask: u32, rt_compute: bool, ) -> usize { if rt_compute @@ -1814,8 +1815,7 @@ impl Firmware { .flights .iter() .any(|fl| fl.computes != 0 && fl.rt_compute) - || units <= super::resources::BASE_COMPUTE_UNITS - || !self.slots.compute_available_for_pipe(units, 1) + || !self.slots.compute_available_in_mask_for_pipe(slot_mask, 1) { return 0; } @@ -1823,7 +1823,7 @@ impl Firmware { [Some(_), None] => 0, [None, Some(_)] => 1, _ => { - if !self.slots.compute_available_for_pipe(units, 0) { + if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { return 1; } let mut active = [0usize; sizes::COMPUTE_PIPES]; @@ -2059,7 +2059,7 @@ impl Firmware { let (compute_pipe, c_waits) = if render { (0usize, [None; sizes::COMPUTE_PIPES]) } else { - let units = job.resources.compute_units()?; + let slot_mask = job.resources.compute_slot_mask()?; let rt_compute = job.resources.compute_scs() || matches!(cmd, Command::Compute(c) if c.is_rt()); let waits = self.wait_compute_stamps_for( @@ -2067,7 +2067,7 @@ impl Firmware { job.command_order(index) .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; - (self.choose_compute_pipe(waits, units, rt_compute), waits) + (self.choose_compute_pipe(waits, slot_mask, rt_compute), waits) }; let pipe_behind = !render && self @@ -2172,10 +2172,11 @@ impl Firmware { false, )?; let mut last_seq = job.command_order(index).map(|o| o.sequence); - let vm_units = job.resources.compute_units()?.min(sizes::COMPUTE_UNITS); + let slot_mask = job.resources.compute_slot_mask()?; let free_c = self .slots - .free_compute_in_for_pipe(vm_units, compute_pipe) as usize; + .free_compute_in_mask_for_pipe(slot_mask, compute_pipe) + as usize; let mut active_pipe = [0usize; sizes::COMPUTE_PIPES]; for fl in &self.engine.flights { if fl.computes != 0 { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 1e80e2303466c..d556b290062e5 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -847,9 +847,17 @@ pub(crate) mod sizes { super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) <= super::engine::RENDER_UMA_SLOT ); - /// SCS-capable compute units per VM, which share ledger indices (and UMA slots) with the - /// first base units. + /// SCS-capable compute units per VM, bound dynamically to healthy compute ledger indices + /// (and UMA slots) preferring pipe-0-exclusive indices `0..PIPE1_COMPUTE_START`. pub(crate) const SCS_COMPUTE_UNITS: usize = 2; + /// First hardware compute ledger index usable by secondary compute pipes (`pipe >= 1`). + /// Keeping `0..PIPE1_COMPUTE_START` exclusive to pipe 0 guarantees that pipe 1 never holds + /// an undisplaced lease on those units, so 2-unit base-only and SCS compute VMs always have + /// at least one claimable unit across up to `PIPE1_COMPUTE_START - 2` permanent quarantines. + pub(crate) const PIPE1_COMPUTE_START: usize = 6; + const _: () = assert!( + PIPE1_COMPUTE_START >= SCS_COMPUTE_UNITS && PIPE1_COMPUTE_START + 2 <= COMPUTE_UNITS + ); /// Bytes of a base UMA pool (its seeds of 4 KiB). pub(crate) const POOL_BYTES: u64 = 0x2000000; const _: () = assert!( diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 0c870a79c49c0..31e267b32760e 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -294,6 +294,8 @@ pub(crate) struct Shared { pub(crate) recovering: AtomicBool, /// Whether any base compute unit (`0..BASE_COMPUTE_UNITS`) has been quarantined. pub(crate) base_compute_quarantined: AtomicBool, + /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). + pub(crate) quarantined_compute_mask: AtomicU32, /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) has been quarantined. pub(crate) base_render_quarantined: AtomicBool, /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). @@ -666,6 +668,7 @@ impl Gpu { sleeping: AtomicBool::new(false), recovering: AtomicBool::new(false), base_compute_quarantined: AtomicBool::new(false), + quarantined_compute_mask: AtomicU32::new(0), base_render_quarantined: AtomicBool::new(false), quarantined_pb_mask: AtomicU32::new(0), next_pb_slot: AtomicU32::new(0), diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e3252e36b2799..2fca6c71513e6 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1379,6 +1379,9 @@ impl Firmware { shared .base_compute_quarantined .store(self.slots.base_compute_quarantined(), Ordering::Release); + shared + .quarantined_compute_mask + .store(self.slots.quarantined_compute_mask(), Ordering::Release); shared .base_render_quarantined .store(self.slots.base_render_quarantined(), Ordering::Release); diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 15e77396fcf7a..d3cf6caf6084d 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -118,6 +118,31 @@ impl Lifetime { .iter() .any(|u| matches!(u.state, State::Preparing | State::Published)) } + /// [`Self::exhausted`] restricted to owners selected by `mask` (bit `k` -> owner `k`). + pub(crate) fn exhausted_in_mask(&self, mask: u32) -> bool { + let mut rem = mask; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < N && self.available(k) { + return false; + } + } + !self + .units + .iter() + .any(|u| matches!(u.state, State::Preparing | State::Published)) + } + /// Bitmask of permanently quarantined owners in `0..N.min(32)`. + pub(crate) fn quarantined_mask(&self) -> u32 { + let mut mask = 0u32; + for k in 0..N.min(32) { + if self.units[k].state == State::Quarantined { + mask |= 1u32 << k; + } + } + mask + } /// Whether any owner in `0..n` is permanently quarantined. pub(crate) fn any_quarantined_within(&self, n: usize) -> bool { (0..n.min(N)).any(|k| self.units[k].state == State::Quarantined) diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 0b83aef27f1dc..319232fd46334 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -276,6 +276,7 @@ impl Queue { // No GPU completion lock is held; reclaim can wait for earlier hardware work. let hints = super::resources::PrepareHints { expand_compute_ext: self.shared.base_compute_quarantined.load(Ordering::Acquire), + quarantined_compute_mask: self.shared.quarantined_compute_mask.load(Ordering::Acquire), expand_render_ext: self.shared.base_render_quarantined.load(Ordering::Acquire), quarantined_pb_mask: self.shared.quarantined_pb_mask.load(Ordering::Acquire), next_pb_slot: &self.shared.next_pb_slot, diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 84d5623728910..a599515ffc0a9 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -91,6 +91,9 @@ impl ComputeArena { /// CDM pipe retains one undisplaced last-retired unit until displacement. pub(crate) struct ComputeUnitSet { units: KVec>, + /// Device-wide compute ledger indices bound to local SCS units `0..SCS_COMPUTE_UNITS`, or + /// `None` for contiguous base/extension sets whose local index equals the ledger index. + hw_slots: Option<[usize; super::hw::sizes::SCS_COMPUTE_UNITS]>, } impl ComputeUnitSet { /// Units `range` (each index and `placement` fix its client addresses; the index fixes its @@ -110,7 +113,38 @@ impl ComputeUnitSet { GFP_KERNEL, )?; } - Ok(Arc::new(Self { units }, GFP_KERNEL)?) + Ok(Arc::new( + Self { + units, + hw_slots: None, + }, + GFP_KERNEL, + )?) + } + /// SCS-capable compute units mapped at local VA indices `0..SCS_COMPUTE_UNITS` and bound to + /// device-wide healthy compute ledger indices `hw_slots`. + fn new_scs( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + hw_slots: [usize; super::hw::sizes::SCS_COMPUTE_UNITS], + seeds: u32, + ) -> Result> { + let mut units = KVec::with_capacity(super::hw::sizes::SCS_COMPUTE_UNITS, GFP_KERNEL)?; + for local in 0..super::hw::sizes::SCS_COMPUTE_UNITS { + units.push( + ComputeArena::new(factory, bind, vm, live, local, Placement::Scs { seeds })?, + GFP_KERNEL, + )?; + } + Ok(Arc::new( + Self { + units, + hw_slots: Some(hw_slots), + }, + GFP_KERNEL, + )?) } fn len(&self) -> usize { self.units.len() @@ -176,6 +210,8 @@ const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; pub(crate) struct PrepareHints<'a> { /// A base compute unit (`0..BASE_COMPUTE_UNITS`) is quarantined: allocate extension units. pub(crate) expand_compute_ext: bool, + /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). + pub(crate) quarantined_compute_mask: u32, /// A base render pass slot (`0..BASE_RENDER_SLOTS`) is quarantined: allocate extension slots. pub(crate) expand_render_ext: bool, /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). @@ -186,6 +222,81 @@ pub(crate) struct PrepareHints<'a> { pub(crate) active_render_vms: &'a Arc, } +/// Selects `SCS_COMPUTE_UNITS` distinct hardware compute ledger indices for a VM's SCS compute +/// set, skipping permanently quarantined units in `quarantined_mask`. Scans from `0` up so +/// pipe-0-exclusive units (`0..PIPE1_COMPUTE_START`) are preferred before falling back to +/// `PIPE1_COMPUTE_START..max_units`. +fn pick_scs_compute_slots( + quarantined_mask: u32, + max_units: usize, +) -> [usize; super::hw::sizes::SCS_COMPUTE_UNITS] { + let limit = max_units + .min(super::hw::sizes::COMPUTE_UNITS) + .max(super::hw::sizes::SCS_COMPUTE_UNITS); + let mut out = [0usize; super::hw::sizes::SCS_COMPUTE_UNITS]; + let mut found = 0usize; + for k in 0..limit { + if (quarantined_mask & (1u32 << k)) == 0 { + out[found] = k; + found += 1; + if found == out.len() { + return out; + } + } + } + for k in 0..limit { + if !out[..found].contains(&k) { + out[found] = k; + found += 1; + if found == out.len() { + return out; + } + } + } + out +} + +/// Selects `[home, alt]` distinct physical PB/UMA allocator slots for a new `RenderArena`, +/// starting round-robin from `start % WARM_PB_SLOTS` and skipping permanently quarantined slots +/// in `quarantined_mask`. Scans `0..WARM_PB_SLOTS` first, then `WARM_PB_SLOTS..PB_SLOTS`, so +/// both base and `render_scs` VMs always start with two healthy PB slots after recovery. +fn pick_base_pb_slots(start: usize, quarantined_mask: u32) -> [usize; BASE_PB_SLOTS] { + let warm = super::hw::sizes::WARM_PB_SLOTS; + let total = super::hw::sizes::PB_SLOTS; + let mut out = [0usize; BASE_PB_SLOTS]; + let mut found = 0usize; + for i in 0..warm { + let slot = (start + i) % warm; + if (quarantined_mask & (1u32 << slot)) == 0 { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + for slot in warm..total { + if (quarantined_mask & (1u32 << slot)) == 0 { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + for i in 0..total { + let slot = (start + i) % total; + if !out[..found].contains(&slot) { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + out +} + /// Updates the consecutive-compute burst counter and reports whether this submission /// qualifies to allocate extension compute units (`compute_ext`). /// @@ -889,15 +1000,17 @@ impl Cache { if compute_scs { match ready.compute_scs.as_ref().map(|set| set.seeds()) { None => { - ready.compute_scs = Some(ComputeUnitSet::new( + let hw_slots = pick_scs_compute_slots( + hints.quarantined_compute_mask, + super::params::compute_units(), + ); + ready.compute_scs = Some(ComputeUnitSet::new_scs( &self.factory, &self.bind, &vm.vm, &self.live, - 0..super::hw::sizes::SCS_COMPUTE_UNITS, - Placement::Scs { - seeds: compute_seeds.pool, - }, + hw_slots, + compute_seeds.pool, )?); } // The units cannot grow once the hardware may hold them. @@ -932,15 +1045,14 @@ impl Cache { } } if render && ready.render.is_none() { - let home = (hints.next_pb_slot.fetch_add(1, Ordering::Relaxed) as usize) - % super::hw::sizes::WARM_PB_SLOTS; - let alt = (home + 1) % super::hw::sizes::WARM_PB_SLOTS; + let start = hints.next_pb_slot.fetch_add(1, Ordering::Relaxed) as usize; + let base_pb_slots = pick_base_pb_slots(start, hints.quarantined_pb_mask); ready.render = Some(RenderArena::new( &self.factory, &self.bind, &vm.vm, &self.live, - [home, alt], + base_pb_slots, )?); if ready.render_vm_counter.is_none() { hints.active_render_vms.fetch_add(1, Ordering::AcqRel); @@ -1258,12 +1370,34 @@ impl Prepared { self.compute.as_deref().ok_or(EINVAL) } /// Compute units this job can use. + #[allow(dead_code)] pub(crate) fn compute_units(&self) -> Result { Ok(self.compute()?.len() + self.compute_ext.as_deref().map_or(0, ComputeUnitSet::len)) } + /// Hardware compute ledger bitmask (bit `k` -> unit `k`) this job can use. + pub(crate) fn compute_slot_mask(&self) -> Result { + let base = self.compute()?; + if let Some(slots) = base.hw_slots { + let mut mask = 0u32; + for slot in slots { + mask |= 1u32 << slot; + } + return Ok(mask); + } + let total = self.compute_units()?.min(super::hw::sizes::COMPUTE_UNITS); + Ok(if total >= 32 { + u32::MAX + } else { + (1u32 << total) - 1 + }) + } /// The per-unit arena holding compute unit `k`. pub(crate) fn compute_arena(&self, k: usize) -> Option> { let base = self.compute.as_ref()?; + if let Some(slots) = base.hw_slots { + let local = slots.iter().position(|&slot| slot == k)?; + return base.arena(local); + } if k < base.len() { base.arena(k) } else { @@ -1454,9 +1588,13 @@ impl Prepared { .map(|(tier, _)| PassOwnerArena::Ext(tier.clone())) } } - /// Compute unit `k`: the VM's base units, then its extension units. + /// Compute unit `k`: the VM's base/SCS units, then its extension units. pub(crate) fn compute_unit(&self, k: usize) -> Result<&ComputeSlot> { let base = self.compute()?; + if let Some(slots) = base.hw_slots { + let local = slots.iter().position(|&slot| slot == k).ok_or(EINVAL)?; + return base.unit(local).ok_or(EINVAL); + } match base.unit(k) { Some(unit) => Ok(unit), None => self diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 8891434a0e52f..22a83b59b690f 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -923,9 +923,18 @@ impl Slots { .exhausted_within(super::params::compute_units()) } /// Whether none of the first `n` compute units (a VM's own) can ever be claimed again. + #[allow(dead_code)] pub(crate) fn compute_exhausted_within(&self, n: usize) -> bool { self.compute.lifetime.exhausted_within(n) } + /// Whether none of the compute units in `mask` (bit `k` -> unit `k`) can ever be claimed. + pub(crate) fn compute_exhausted_in_mask(&self, mask: u32) -> bool { + self.compute.lifetime.exhausted_in_mask(mask) + } + /// Bitmask of permanently quarantined compute units (`0..COMPUTE_UNITS`). + pub(crate) fn quarantined_compute_mask(&self) -> u32 { + self.compute.lifetime.quarantined_mask() + } pub(crate) fn render_exhausted(&self) -> bool { self.render.lifetime.exhausted() } @@ -949,20 +958,44 @@ impl Slots { [self.compute.lifetime.counts(), self.render.lifetime.counts()] } /// Whether one of the first `n` compute units can be claimed now. + #[allow(dead_code)] pub(crate) fn compute_available(&self, n: usize) -> bool { (0..n.min(sizes::COMPUTE_UNITS)).any(|k| self.compute.lifetime.available(k)) } + /// Whether any compute unit in `mask` can be claimed now. + pub(crate) fn compute_available_in_mask(&self, mask: u32) -> bool { + let mut rem = mask; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < sizes::COMPUTE_UNITS && self.compute.lifetime.available(k) { + return true; + } + } + false + } + /// Whether any compute unit in `mask` eligible for `pipe` can be claimed now. + /// Pipe 0 may claim any bit in `mask`; secondary pipes stay in + /// `PIPE1_COMPUTE_START..COMPUTE_UNITS` so `0..PIPE1_COMPUTE_START` only ever hold pipe-0 + /// leases. + pub(crate) fn compute_available_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> bool { + let allowed = if pipe == 0 { + mask + } else { + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + self.compute_available_in_mask(allowed) + } /// Whether one of the first `n` compute units eligible for `pipe` can be claimed now. - /// Pipe 0 may claim `0..n`; secondary pipes stay in `BASE_COMPUTE_UNITS..n` so a 2-unit - /// base-only VM can never see both base units undisplaced across two pipes. + #[allow(dead_code)] pub(crate) fn compute_available_for_pipe(&self, n: usize, pipe: usize) -> bool { let limit = n.min(sizes::COMPUTE_UNITS); - let start = if pipe == 0 { - 0 + let mask = if limit >= 32 { + u32::MAX } else { - super::resources::BASE_COMPUTE_UNITS.min(limit) + (1u32 << limit) - 1 }; - (start..limit).any(|k| self.compute.lifetime.available(k)) + self.compute_available_in_mask_for_pipe(mask, pipe) } /// Whether one of the first `n` render pass slots can be claimed now. #[allow(dead_code)] @@ -1161,20 +1194,37 @@ impl Slots { self.free_compute_in(super::params::compute_units()) } /// Available compute units within the first `n` units (a VM's prepared count). + #[allow(dead_code)] pub(crate) fn free_compute_in(&self, n: usize) -> u32 { self.free_compute_in_for_pipe(n, 0) } + /// Available compute units in `mask` eligible for `pipe`. + pub(crate) fn free_compute_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> u32 { + let mut rem = if pipe == 0 { + mask + } else { + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + let mut count = 0u32; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < sizes::COMPUTE_UNITS && self.compute.lifetime.available(k) { + count += 1; + } + } + count + } /// Available compute units within the first `n` units eligible for `pipe`. + #[allow(dead_code)] pub(crate) fn free_compute_in_for_pipe(&self, n: usize, pipe: usize) -> u32 { let limit = n.min(sizes::COMPUTE_UNITS); - let start = if pipe == 0 { - 0 + let mask = if limit >= 32 { + u32::MAX } else { - super::resources::BASE_COMPUTE_UNITS.min(limit) + (1u32 << limit) - 1 }; - (start..limit) - .filter(|&k| self.compute.lifetime.available(k)) - .count() as u32 + self.free_compute_in_mask_for_pipe(mask, pipe) } /// Forces a full scrub on the next claim of every slot (after firmware recovery). #[allow(dead_code)] @@ -1241,25 +1291,26 @@ impl Slots { return Ok(None); } // Prefer a warm unit already owned by `vm_id` (`!scrub_full`), then an unowned unit, - // before falling back to round-robin over `start..n`: pipe 0 spans `0..n`, while - // secondary pipes stay in `BASE_COMPUTE_UNITS..n` so base units `0..2` only ever hold - // pipe-0 leases and a 2-unit VM can never hit `compute_exhausted_within(2)`. - let n = units.compute_units()?.min(sizes::COMPUTE_UNITS); - let start = if pipe == 0 { - 0 + // before falling back to round-robin over `allowed`: pipe 0 spans `mask`, while + // secondary pipes stay in `PIPE1_COMPUTE_START..COMPUTE_UNITS` so `0..PIPE1_COMPUTE_START` + // only ever hold pipe-0 leases and 2-unit base/SCS VMs never split across two pipes. + let mask = units.compute_slot_mask()?; + let allowed = if pipe == 0 { + mask } else { - super::resources::BASE_COMPUTE_UNITS + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) }; - if start >= n { + if allowed == 0 { return Ok(None); } - let span = n - start; - let base_cursor = (self.cursor as usize).saturating_sub(start) % span; + let n = sizes::COMPUTE_UNITS; + let base_cursor = (self.cursor as usize) % n; let mut chosen = None; if let Some(id) = vm_id { - for i in 0..span { - let k = start + (base_cursor + i) % span; - if !self.compute.scrub_full[k] + for i in 0..n { + let k = (base_cursor + i) % n; + if (allowed & (1u32 << k)) != 0 + && !self.compute.scrub_full[k] && self.compute.owner[k] .as_ref() .is_some_and(|prev| prev.id == id) @@ -1270,9 +1321,12 @@ impl Slots { } } if chosen.is_none() { - for i in 0..span { - let k = start + (base_cursor + i) % span; - if self.compute.owner[k].is_none() && self.compute.lifetime.claim(k) { + for i in 0..n { + let k = (base_cursor + i) % n; + if (allowed & (1u32 << k)) != 0 + && self.compute.owner[k].is_none() + && self.compute.lifetime.claim(k) + { chosen = Some(k); break; } @@ -1280,9 +1334,9 @@ impl Slots { } } if chosen.is_none() { - for i in 0..span { - let k = start + (base_cursor + i) % span; - if self.compute.lifetime.claim(k) { + for i in 0..n { + let k = (base_cursor + i) % n; + if (allowed & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { chosen = Some(k); break; } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 310c27495708a..8c32b1ff744a3 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -118,7 +118,7 @@ def item(declaration): fn count(&self)->u32{self.count} fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } -struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn compute_slot_mask(&self)->Result{Ok(0b11)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -153,7 +153,7 @@ def item(declaration): impl Slots{ fn compute_exhausted(&self)->bool{self.compute_exhausted} fn render_exhausted(&self)->bool{self.render_exhausted} - fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted} + fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted}fn compute_exhausted_in_mask(&self,_mask:u32)->bool{self.compute_exhausted} fn render_exhausted_within(&self,_passes:usize)->bool{self.render_exhausted} fn release(&mut self,_claims:&mut Claims){self.releases+=1;} fn quarantine(&mut self,_claims:&mut Claims){self.quarantines+=1;} @@ -177,7 +177,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; pub const PIPE1_COMPUTE_START:usize=6; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -737,8 +737,13 @@ def item(declaration): fn compute_exhausted(&self)->bool{self.compute_exhausted} fn render_exhausted(&self)->bool{self.render_exhausted} fn compute_available(&self,_n:usize)->bool{self.compute_available} + fn compute_available_in_mask(&self,_mask:u32)->bool{self.compute_available} + fn compute_available_in_mask_for_pipe(&self,mask:u32,pipe:usize)->bool{ + let allowed = if pipe == 0 { mask } else { mask & !((1u32 << hw::sizes::PIPE1_COMPUTE_START) - 1) }; + self.compute_available && allowed != 0 + } fn compute_available_for_pipe(&self,n:usize,pipe:usize)->bool{ - self.compute_available && (pipe == 0 || n > resources::BASE_COMPUTE_UNITS) + self.compute_available && (pipe == 0 || n > hw::sizes::PIPE1_COMPUTE_START) } fn pass_available(&self,_n:usize)->bool{self.pass_available} } @@ -1642,17 +1647,18 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Empty engine uses next_compute_pipe (0), then balances onto pipe 1 while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); host.engine.flights.push(QueueBehindFlight{ job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); // RT/SCS compute stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 24, true), 0); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, true), 0); // A 2-unit base-only VM stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 2, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], 0b11, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], 0b110, false), 0); assert!(host.can_queue_behind(&c2)); // Add second concurrent flight on pipe 1: both pipes active, // tie-break uses next_compute_pipe, and cross-VM compute overlaps cleanly. @@ -1662,9 +1668,9 @@ def item(declaration): has_timestamps:false,doomed:false,recovery_suspect:false, }); host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); assert!(host.can_queue_behind(&c_vm2)); // Same-VM compute still pipelines without draining. assert!(host.can_queue_behind(&c2)); @@ -1705,13 +1711,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w1, 24, false), 0); + assert_eq!(host.choose_compute_pipe(w1, (1u32 << 24) - 1, false), 0); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(w2, 24, false), 0); + assert_eq!(host.choose_compute_pipe(w2, (1u32 << 24) - 1, false), 0); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1722,7 +1728,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w2_ooo, 24, false), 0); + assert_eq!(host.choose_compute_pipe(w2_ooo, (1u32 << 24) - 1, false), 0); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -1782,7 +1788,7 @@ def item(declaration): // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(cw,24,false),0); + assert_eq!(host.choose_compute_pipe(cw,(1u32<<24)-1,false),0); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index f80781e1b20ae..ee0fc783e7036 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -176,7 +176,7 @@ def module(text, name): pub mod resources { use core::sync::atomic::{AtomicU64,Ordering};use crate::*; pub struct PassDirty<'a>{pub tpc:&'a AtomicU64,pub tilemap:&'a AtomicU64,pub tilemap_last:&'a AtomicU64,pub tilemap_clean:&'a AtomicU64,pub heap:&'a AtomicU64} - pub struct ComputeArena{pub compute:KVec,pub render:Option>} + pub struct ComputeArena{pub compute:KVec,pub render:Option>,pub hw_slots:Option<[usize;super::hw::sizes::SCS_COMPUTE_UNITS]>} // A job's compute units; here one arena. pub type Prepared=ComputeArena; #[derive(Clone)] @@ -199,10 +199,28 @@ def module(text, name): } impl ComputeArena{ pub fn compute_units(&self)->Result{Ok(self.compute.len())} - pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{self.compute.get(k).ok_or(EINVAL)} + pub fn compute_slot_mask(&self)->Result{ + if let Some(slots)=self.hw_slots { + let mut mask=0u32; + for slot in slots { mask |= 1u32 << slot; } + return Ok(mask); + } + let n=self.compute.len().min(super::hw::sizes::COMPUTE_UNITS); + Ok(if n>=32 { u32::MAX } else { (1u32 << n) - 1 }) + } + pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{ + if let Some(slots)=self.hw_slots { + let local=slots.iter().position(|&s|s==k).ok_or(EINVAL)?; + return self.compute.get(local).ok_or(EINVAL); + } + self.compute.get(k).ok_or(EINVAL) + } pub fn compute_arena(&self,k:usize)->Option>{ + let idx=if let Some(slots)=self.hw_slots { + slots.iter().position(|&s|s==k)? + } else { k }; COMPUTE_OWNER_ARENAS - .with(|a|a.borrow().as_ref().and_then(|v|v.get(k).cloned())) + .with(|a|a.borrow().as_ref().and_then(|v|v.get(idx).cloned())) .or_else(||COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone())) } pub fn render_arena(&self)->Option>{self.render.clone()} @@ -216,6 +234,7 @@ def module(text, name): impl RenderArena{ __SET_DIRTY__ } pub(crate) const BASE_COMPUTE_UNITS: usize = 2; pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; + const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; __RENDER_BURST__ } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} @@ -256,7 +275,7 @@ def module(text, name): let mut compute=KVec::new();let mut passes=KVec::new(); let f=g16::object::Factory; for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} - Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:render_arena(passes)} + Arenas{compute:g16::resources::ComputeArena{compute,render:None,hw_slots:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<bool{let mut q=g16::slots::ScrubQueue::new();q.push_batch(batch);let mut wake=false;while let Some(mut item)=q.pop(){wake|=item.run_one();}wake} @@ -1062,7 +1081,7 @@ def module(text, name): #[test]fn offlock_scrub_cleans_displaced_slot_and_skips_sync_scrub_on_same_vm_claim(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1); let geo=g16::encode::Geometry{tpc_bytes:0x2000,tilemap_bytes:0x4000}; // Publish and retire slot 0: not displaced yet, so nothing is staged. @@ -1113,7 +1132,7 @@ def module(text, name): #[test]fn offlock_scrub_falls_back_on_error_drop_recovery_and_cross_vm(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1);let b=vm(2); // Prime and displace slot 0. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; @@ -1164,7 +1183,7 @@ def module(text, name): #[test]fn post_publish_scrub_staging_does_not_block_immediate_slot_reuse(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1); let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; // Prime slot 0, then displace it by retiring slot 1; record retirement without staging yet. @@ -1206,7 +1225,7 @@ def module(text, name): for k in 0..hw::sizes::COMPUTE_UNITS { units.push(ComputeSlot::new(&mut o,&g16::object::Factory,k as u64).unwrap(),0).unwrap(); } - let prep=ComputeArena{compute:units,render:None}; + let prep=ComputeArena{compute:units,render:None,hw_slots:None}; let a=Arc::new( vm::VmState{id:1,slot:1,generation:1,vm:vm::MockVm::new()},0, ).unwrap(); @@ -1246,7 +1265,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; let a=vm(1); // Wrapped submission order [46, 47, 0]: retiring in order leaves slot 0 as last_retired // while high slots 46 and 47 (bits above 31) are displaced and reusable immediately. @@ -1308,7 +1327,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; let a=vm(1);let b=vm(2); // Per-unit compute hold_compute_slot + verify_held + note_published. @@ -1474,7 +1493,7 @@ def module(text, name): for k in 0..4u64 { units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep_full=g16::resources::ComputeArena{compute:units,render:None}; + let prep_full=g16::resources::ComputeArena{compute:units,render:None,hw_slots:None}; let a=vm(1);let b=vm(2); // Retire base unit 0, then hang and quarantine base unit 1 (or vice versa): // unit 0 is now retired-undisplaced and unit 1 is quarantined -> base [0..2] exhausted. @@ -1501,37 +1520,38 @@ def module(text, name): for k in 0..2u64 { base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None,hw_slots:None}; assert_eq!(s.claim_compute_for(&prep_base,&mut c,Some(b.id)).unwrap(),Some(0)); s.release(&mut c); } #[test]fn two_pipe_compute_out_of_order_retire_and_base_unit_isolation(){ let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let p1_start = g16::hw::sizes::PIPE1_COMPUTE_START; let mut units=KVec::new(); - for k in 0..4u64 { + for k in 0..(p1_start + 2) as u64 { units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep=g16::resources::ComputeArena{compute:units,render:None}; + let prep=g16::resources::ComputeArena{compute:units,render:None,hw_slots:None}; let a=vm(1);let b=vm(2); - // Pipe 0 claims unit 0; pipe 1 stays out of base units 0..2 and claims unit 2. + // Pipe 0 claims unit 0; pipe 1 stays out of 0..PIPE1_COMPUTE_START and claims PIPE1_COMPUTE_START. let mut c0=Claims::new(); let mut c1=Claims::new(); assert_eq!(s.claim_compute_for_pipe(&prep,&mut c0,Some(a.id),0).unwrap(),Some(0)); assert_eq!(c0.compute_pipe,0); s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap(); - assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1,Some(a.id),1).unwrap(),Some(2)); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1,Some(a.id),1).unwrap(),Some(p1_start)); assert_eq!(c1.compute_pipe,1); s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap(); // Pipe 1 finishes ahead of still-running pipe 0: retire must succeed (no EINVAL). assert_eq!(s.retire(&mut c1),Ok(())); - // Second pipe-1 flight claims unit 3 and retires, displacing unit 2 on pipe 1. + // Second pipe-1 flight claims PIPE1_COMPUTE_START + 1 and retires, displacing PIPE1_COMPUTE_START. let mut c1b=Claims::new(); - assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1b,Some(a.id),1).unwrap(),Some(3)); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1b,Some(a.id),1).unwrap(),Some(p1_start + 1)); s.hold_vm(&c1b,&a).unwrap();s.publish(&mut c1b).unwrap(); assert_eq!(s.retire(&mut c1b),Ok(())); - assert!(s.compute_available_for_pipe(4,1)); - // Now pipe 0's unit 0 retires: pipe 1's newer unit 3 must NOT mark unit 0 reusable, + assert!(s.compute_available_for_pipe(p1_start + 2,1)); + // Now pipe 0's unit 0 retires: pipe 1's newer retirement must NOT mark unit 0 reusable, // while base unit 1 remains fresh so a 2-unit base-only VM is never exhausted! assert_eq!(s.retire(&mut c0),Ok(())); assert!(!s.compute_exhausted_within(2)); @@ -1544,20 +1564,89 @@ def module(text, name): assert!(!s.compute_exhausted_within(2)); assert!(s.compute_available(2)); // A 2-unit base-only VM can claim displaced base unit 0 on pipe 0, while pipe 1 - // reclaims displaced extension unit 2 on the 4-unit VM without touching base units 0..2. + // reclaims displaced extension unit PIPE1_COMPUTE_START without touching 0..PIPE1_COMPUTE_START. let mut base_units=KVec::new(); for k in 0..2u64 { base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None,hw_slots:None}; let mut c0c=Claims::new(); assert_eq!(s.claim_compute_for_pipe(&prep_base,&mut c0c,Some(b.id),0).unwrap(),Some(0)); let mut c1c=Claims::new(); - assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1c,Some(b.id),1).unwrap(),Some(2)); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1c,Some(b.id),1).unwrap(),Some(p1_start)); s.release(&mut c0c); s.release(&mut c1c); } + #[test]fn scs_compute_and_base_pb_route_around_quarantined_slots(){ + use crate::g16::resources::{pick_base_pb_slots, pick_scs_compute_slots}; + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let p1_start = g16::hw::sizes::PIPE1_COMPUTE_START; + let mut full_units=KVec::new(); + for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { + full_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); + } + let prep_full=g16::resources::ComputeArena{compute:full_units,render:None,hw_slots:None}; + let bad=vm(1);let fresh=vm(2);let other=vm(3); + // Exact dcp102b sequence: a prior process hangs and permanently quarantines compute unit 0. + let mut c=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c,Some(bad.id),0).unwrap(),Some(0)); + s.hold_vm(&c,&bad).unwrap();s.publish(&mut c).unwrap();s.quarantine(&mut c); + assert_eq!(s.quarantined_compute_mask(), 1u32 << 0); + // Pipe 1 runs concurrent non-SCS compute on PIPE1_COMPUTE_START..COMPUTE_UNITS. + let mut c_p1=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c_p1,Some(other.id),1).unwrap(),Some(p1_start)); + s.hold_vm(&c_p1,&other).unwrap();s.publish(&mut c_p1).unwrap();s.retire(&mut c_p1).unwrap(); + // Brand-new SCS compute VM skips quarantined unit 0 and binds [1, 2] (mask 0b110), both < PIPE1_COMPUTE_START. + let scs_slots = pick_scs_compute_slots(s.quarantined_compute_mask(), g16::hw::sizes::COMPUTE_UNITS); + assert_eq!(scs_slots, [1, 2]); + let mut scs_units=KVec::new(); + for local in 0..g16::hw::sizes::SCS_COMPUTE_UNITS as u64 { + scs_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,local).unwrap(),0).unwrap(); + } + let prep_scs=g16::resources::ComputeArena{compute:scs_units,render:None,hw_slots:Some(scs_slots)}; + let scs_mask = prep_scs.compute_slot_mask().unwrap(); + assert_eq!(scs_mask, (1u32 << 1) | (1u32 << 2)); + // Execute two back-to-back SCS compute commands (e.g. rt.scene p_rt + p_comp) repeatedly: + // must never hit compute_exhausted_in_mask and must ping-pong cleanly across [1, 2]. + for expected in [1usize, 2, 1, 2] { + assert!(!s.compute_exhausted_in_mask(scs_mask)); + assert!(s.compute_available_in_mask(scs_mask)); + let mut cs=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_scs,&mut cs,Some(fresh.id),0).unwrap(),Some(expected)); + s.hold_vm(&cs,&fresh).unwrap();s.publish(&mut cs).unwrap();s.retire(&mut cs).unwrap(); + } + // Up to 4 quarantines in 0..PIPE1_COMPUTE_START stay inside pipe-0-exclusive 0..6; beyond that falls back cleanly. + assert_eq!(pick_scs_compute_slots(0b001111, g16::hw::sizes::COMPUTE_UNITS), [4, 5]); + assert_eq!(pick_scs_compute_slots(0b111111, g16::hw::sizes::COMPUTE_UNITS), [6, 7]); + // Twin fix: pick_base_pb_slots skips quarantined warm PB slots and falls back to EXT_PB_SLOTS. + assert_eq!(pick_base_pb_slots(0, 0), [0, 1]); + assert_eq!(pick_base_pb_slots(3, 1u32 << 3), [4, 5]); + assert_eq!(pick_base_pb_slots(3, (1u32 << 3) | (1u32 << 4)), [5, 6]); + let all_warm_but_one = ((1u32 << g16::hw::sizes::WARM_PB_SLOTS) - 1) & !(1u32 << 7); + assert_eq!(pick_base_pb_slots(0, all_warm_but_one), [7, g16::hw::sizes::WARM_PB_SLOTS]); + // Confirm Pools::exhausted_for_mask_mode stays false for render_scs with picked healthy slots. + let mut pools = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let bad_vm = vm(10); + let good_vm = vm(11); + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let ep = g16::pools::PbEpoch::new( + &factory, + &bad_vm, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ) + .unwrap(); + ep.prepare(3, 0x70c0000000, 2048).unwrap(); + ep.expose(); + pools.publish_flight(3); + pools.quarantine_flight(3, Some(ep)); + let picked = pick_base_pb_slots(3, pools.quarantined_mask()); + assert_eq!(picked, [4, 5]); + let pb_mask = (1u32 << picked[0]) | (1u32 << picked[1]); + assert!(!pools.exhausted_for_mask_mode(&good_vm, pb_mask, picked[0], true)); + } + #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ use crate::g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots}; let mut o=Objects::new();let mut s=Slots::new().unwrap(); @@ -1566,7 +1655,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render)}; + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render),hw_slots:None}; let a=vm(1);let b=vm(2); let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x1000}; // Retire base pass slot 0, then hang and quarantine base pass slot 1 -> base [0..2] exhausted. @@ -1598,7 +1687,7 @@ def module(text, name): use crate::g16::slots::ScrubQueue; let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1); let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; // Prime and displace slot 0. @@ -1659,7 +1748,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone()),hw_slots:None}; let a=vm(1);let b=vm(2); let pub_retire=|s:&mut Slots,k:usize,vm:&sync::Arc|{ let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1u64< = (0..16u64).map(|i| vm(200 + i)).collect(); @@ -2096,7 +2186,7 @@ def module(text, name): for k in 0..18 { passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); } - let shared_prep_compute = ComputeArena { compute: compute_slots, render: None }; + let shared_prep_compute = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; let mut vms = Vec::new(); @@ -2114,9 +2204,9 @@ def module(text, name): r_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); } let r_arena = sync::Arc::new(render_arena(r_passes), 0).unwrap(); - let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()) }; + let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()), hw_slots: None }; let c_arena = sync::Arc::new( - ComputeArena { compute: KVec::new(), render: None }, 0, + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, 0, ).unwrap(); // 1) PB warm slot i @@ -2205,7 +2295,7 @@ def module(text, name): // Live VM 17 runs 1 render + 1 compute, displacing slot 15 everywhere. let live = vm(500); let live_r_arena = sync::Arc::new(render_arena(passes), 0).unwrap(); - let live_r_prep = ComputeArena { compute: KVec::new(), render: Some(live_r_arena.clone()) }; + let live_r_prep = ComputeArena { compute: KVec::new(), render: Some(live_r_arena.clone()), hw_slots: None }; let live_slot = p .pick_slot_in_mask_blocks_mode(&live, false, 0b11, 0, 512, false) .unwrap(); @@ -2281,7 +2371,7 @@ def module(text, name): sc_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); } let sc_arena = sync::Arc::new(render_arena(sc_passes), 0).unwrap(); - let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()) }; + let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()), hw_slots: None }; let va = vm(600); let vb = vm(601); for (k, owner) in [(0usize, &va), (1usize, &vb)] { @@ -2341,7 +2431,7 @@ def module(text, name): for k in 0..COMPUTE_UNITS { compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); } - let prep = ComputeArena { compute: compute_slots, render: None }; + let prep = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). @@ -2352,7 +2442,11 @@ def module(text, name): let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); for _ in 0..COMPUTE_UNITS { per_unit.push( - sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), + sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, + 0, + ) + .unwrap(), ); } COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); @@ -2468,8 +2562,12 @@ def module(text, name): units1.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); } let c_uma1 = units1[0].uma_lease(); - let prep1 = ComputeArena { compute: units1, render: None }; - let c_arena1 = sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(); + let prep1 = ComputeArena { compute: units1, render: None, hw_slots: None }; + let c_arena1 = sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, + 0, + ) + .unwrap(); let mut cc1 = Claims::new(); assert_eq!(s.claim_compute_for(&prep1, &mut cc1, Some(vm1.id)).unwrap(), Some(0)); COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena1.clone())); @@ -2482,7 +2580,7 @@ def module(text, name): for k in 0..COMPUTE_UNITS { units2.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); } - let prep2 = ComputeArena { compute: units2, render: None }; + let prep2 = ComputeArena { compute: units2, render: None, hw_slots: None }; let mut cc2 = Claims::new(); assert_eq!(s.claim_compute_for(&prep2, &mut cc2, Some(vm2.id)).unwrap(), Some(1)); s.hold_compute_slot(1, &vm2, &prep2).unwrap(); @@ -2492,7 +2590,7 @@ def module(text, name): let mut units3 = KVec::new(); units3.push(ComputeSlot::new(&mut o, &factory, 0).unwrap(), 0).unwrap(); let c_uma3 = units3[0].uma_lease(); - let prep3 = ComputeArena { compute: units3, render: None }; + let prep3 = ComputeArena { compute: units3, render: None, hw_slots: None }; // Drop local arena/epoch/pool handles for VM1 and close VM1. drop(e1); @@ -2682,6 +2780,8 @@ def module(text, name): line for line in resources_source.splitlines() if line.startswith(('const BURST_SUBMITS:', 'const BURST_GAP_NS:', 'const BURST_COMMANDS:', 'const RENDER_BURST_COMMANDS:')) ) + + '\npub(crate) ' + item(resources_source, 'fn pick_scs_compute_slots(') + + '\npub(crate) ' + item(resources_source, 'fn pick_base_pb_slots(') + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') + '\npub(crate) ' + item(resources_source, 'fn target_render_slots_for(') From 1bbf487c22ad6afc353730d894874818ab5c6cf1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:11 -0500 Subject: [PATCH 3/7] selftests: asahi-m4: verify render-only PB slot routing stability Commit 7a8472835197 ("drm/asahi: g16: route SCS compute and base PB slots around quarantined slots") replaced the [home, home + 1] warm PB pair of a new render arena with a quarantine-aware picker. Verify that with nothing quarantined the picker returns the contiguous [home, home + 1] pair for every start, and that sixteen render-only VMs use every warm slot once as home and once as alternate regardless of earlier round-robin cursor motion. Signed-off-by: Diljit Singh --- .../drivers/gpu/asahi-m4/test-resources.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index ee0fc783e7036..9e5331c254c9f 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1647,6 +1647,32 @@ def module(text, name): assert!(!pools.exhausted_for_mask_mode(&good_vm, pb_mask, picked[0], true)); } + #[test]fn render_only_pb_routing_without_quarantine_matches_v29_for_any_boot_history(){ + use crate::g16::resources::pick_base_pb_slots; + let warm = g16::hw::sizes::WARM_PB_SLOTS; + // v29 (4310e041) gave a new render arena [start % WARM_PB_SLOTS, home + 1]. With nothing + // quarantined the quarantine-aware picker must be that exact pair for every start. + for start in 0..(4 * warm) { + assert_eq!(pick_base_pb_slots(start, 0), [start % warm, (start + 1) % warm]); + } + // render.light [procs] d=16 (dcp103a, dcp103b) makes WARM_PB_SLOTS render-only VMs. Earlier + // work in the same boot only moves `next_pb_slot`: whatever the start, every warm slot is + // the home of exactly one of them and the alternate of exactly one other. + for start in [0usize, 1, 7, 15, 16, 39, 1000] { + let mut home = [0u32; 32]; + let mut alt = [0u32; 32]; + for vm in 0..warm { + let [h, a] = pick_base_pb_slots(start + vm, 0); + assert_ne!(h, a); + home[h] += 1; + alt[a] += 1; + } + assert!(home[..warm].iter().all(|&n| n == 1), "start {start}: {home:?}"); + assert!(alt[..warm].iter().all(|&n| n == 1), "start {start}: {alt:?}"); + assert!(home[warm..].iter().chain(&alt[warm..]).all(|&n| n == 0)); + } + } + #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ use crate::g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots}; let mut o=Objects::new();let mut s=Slots::new().unwrap(); From 37d7d7e938689dcc822d436da8edd506b7479519 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:11 -0500 Subject: [PATCH 4/7] drm/asahi: g16: mark SCS stages in StartCompute, StartTA and StartFS The 26B123 G16G firmware learns which slots run shader-context scratch (SCS) work from a u32 in each start command: StartCompute +0x40, StartTA +0x60 and StartFS +0x78. It ORs the slot into a per-engine SCS mask, appends 0x017d9 = 1 to that kick's register list for masked slots, and when its scheduler goes idle it tears the SCS state down (0x017e0 = 0, the compute and TA windows 0x107a0/0x10798 = 0xff0000, 0x100e8/0x100f0/0x10408/0x10410 = 0x100) unless a masked slot is still busy. The G16 encoders always left the three words zero, so the teardown ran at the first idle after every ray-query kick, while the dispatch was still executing. Compute and ray-generation ray queries then lost traversal mid-dispatch and returned misses without a fault, and fragment and tiling ray queries stalled their stage until the firmware recovered it (events 0x71 and 0x70). macOS 27.2 on Apple M4 sets StartCompute +0x40 on every compute item whose register list opens with 0x017e1 and leaves it clear on all others. This is the M4 counterpart of the G17P kick header's SCS bit (bit 61), which g17 sets for compute and per render stage. Set each word exactly when the stage's register list enables SCS. Non-ray-tracing work is byte-identical. The host check now also requires the flag on ray-query compute, TA and FS sequences and nothing else to change there. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/encode/compute.rs | 1 + drivers/gpu/drm/asahi/g16/encode/render.rs | 2 ++ drivers/gpu/drm/asahi/g16/fw/work.rs | 6 +++++ drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 5 ++++ drivers/gpu/drm/asahi/g16/rt.rs | 7 ++++-- .../drivers/gpu/asahi-m4/test-ray-tracing.py | 25 +++++++++++++++---- 6 files changed, 39 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 71191ebabfc35..78c972ac4c9df 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -476,6 +476,7 @@ pub(crate) fn encode_compute_rt( put32(q, 0x30, u32::from(fault_mask != 0)); put32(q, 0x38, r.compute_index); put32(q, 0x3c, r.work_818); + put32(q, compute::START_SCS, u32::from(rt.scs)); put64(q, 0x44, r.work + 0x76c); put32(q, 0x50, 1); for (i, a) in att.iter().enumerate() { diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index 647ce05126453..ebf2e03a68269 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -378,6 +378,7 @@ pub(crate) fn encode_ta_rt( put64(q, 0x64, work + 0x784); put64(q, 0x6c, work + 0x8a8); put32(q, 0x7c, r.uuid); + put32(q, ta::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); // TA attachments are filled by render_attachments before publication. inline_uma(q, 0x190, r, 0); timestamps( @@ -657,6 +658,7 @@ pub(crate) fn encode_fs_rt( put64(q, 0x7c, work + 0xa58); put64(q, 0x84, work + 0xbf0); put32(q, 0xa0, r.uuid); + put32(q, fs::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); inline_uma(q, 0x1b0, r, 1); timestamps( q, diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index f50fc22164d4c..5b1220b301e3f 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -80,6 +80,9 @@ pub(crate) mod ta { pub(crate) const TS_END: usize = 0x21c; pub(crate) const FINALIZE: usize = 0x268; pub(crate) const END: usize = 0x2fc; + /// u32 of the StartTA command: nonzero when the stage's register list enables SCS + /// (`compute::START_SCS`). + pub(crate) const START_SCS: usize = 0x60; /// The binding generation. pub(crate) const GENERATION: usize = 0x917; @@ -142,6 +145,9 @@ pub(crate) mod fs { pub(crate) const TS_END: usize = 0x23c; pub(crate) const FINALIZE: usize = 0x288; pub(crate) const END: usize = 0x344; + /// u32 of the StartFS command: nonzero when the stage's register list enables SCS + /// (`compute::START_SCS`). + pub(crate) const START_SCS: usize = 0x78; /// The binding generation. pub(crate) const GENERATION: usize = 0xc5f; diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index bb5ccf0ccc846..85daf5876aec3 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -36,6 +36,11 @@ pub(crate) const CONTEXT_STORE_SIZE: usize = 0x40000; pub(crate) const POOL_SIZE: usize = 0x2000000; pub(crate) const POOL_STATE_SIZE: usize = 0x20000; pub(crate) const PAGE_LIST_SIZE: usize = 0x4000; +/// u32 of the StartCompute command: nonzero when the work's register list enables shader-context +/// scratch (SCS). The firmware then records the work's slot as an SCS user, appends +/// `0x017d9 = 1` to the kick's register list, and keeps the SCS state (`0x017e0`, the compute +/// and TA windows) through its idle teardown while the slot is busy. +pub(crate) const START_SCS: usize = 0x40; pub(crate) const EVENT: u32 = 15; /// Firmware completion events for concurrent compute pipes `0..COMPUTE_PIPES`. pub(crate) const EVENTS: [u32; 2] = [EVENT, 16]; diff --git a/drivers/gpu/drm/asahi/g16/rt.rs b/drivers/gpu/drm/asahi/g16/rt.rs index 4119afade7c23..5b42e6f2d1dcf 100644 --- a/drivers/gpu/drm/asahi/g16/rt.rs +++ b/drivers/gpu/drm/asahi/g16/rt.rs @@ -19,8 +19,11 @@ //! ray queries has been traced. //! - 0x1a141 (SCS driver word), `COMPUTE_SCS_DRIVER_WORD` (T1): macOS's ray-query compute //! items on the J773g do not write it. -//! - An SCS-enable bit in the work or microsequence, as g17's kick header has (T6): none is -//! known, so nothing is written. +//! - The SCS-enable bit (T6, g17's kick header bit 61) is a u32 of each start command: +//! StartCompute +0x40, StartTA +0x60, StartFS +0x78 (`fw::work`'s `START_SCS`). macOS 27.2 on +//! the J773g sets it on every compute item whose list opens with 0x017e1 and on no other. A +//! slot without it is not protected from the firmware's idle SCS teardown (0x017e0 = 0, +//! compute and TA windows 0xff0000), which runs while its dispatch is still executing. //! - A traversal exclusion between clients (T8): the A18 Pro needs one (`g17::traversal`), the //! M4 Pro's variants do not set it; G16G adds none. //! - How macOS sizes the SCS pool for a given request (T3): it grows its compute pool beyond diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py index 3b5c3dca9299d..bfc62d7c4c9ef 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -14,7 +14,9 @@ 2. RT words land in the wrong register record, the register counts change, a gated register (0x1a141, render 0x017d9) is written while its gate is off, or a ray-query compute item is not bracketed by 0x017e1 = 1 first and 0x017d9 = 1 last, or its tail is not 0x2c, as macOS - 27.2 writes them on the J773g. + 27.2 writes them on the J773g; or a start command's SCS flag (StartCompute +0x40, StartTA + +0x60, StartFS +0x78) differs from whether the item's register list enables SCS, which + leaves a running ray-query dispatch exposed to the firmware's idle SCS teardown. 3. The fragment window word loses bit 9; a render stage's tail word takes the auxiliary intersection word (the M4 Pro's render programs use the scratch tail). 4. SCS sizing differs from the M4 Pro's formula ((pages + pages/256 + 8) x cores pages), is not @@ -237,12 +239,17 @@ def block(text, declaration): assert_eq!(sel, plain_sel); assert!(value == plain_value || rt_sels.contains(&sel), "{sel:#x}"); } - // Nothing else moves: the register list, its count and the pool's descriptor words. + // The embedded StartCompute marks the slot as an SCS user, as macOS 27.2 does on + // every J773g compute item that opens with 0x017e1 (and on no other). + let flag = compute::SEQ_EMBEDDED + compute::START_SCS; + assert_eq!((u32_at(&plain, flag), u32_at(&w, flag)), (0, 1)); + // Nothing else moves: the register list, its count, the pool's descriptor words and + // the start command's SCS flag. let regs = compute::REGS..compute::REGS + 27 * 12; let pool_words = [0x1c, 0x24, 0x2c, 0x48]; for (i, (a, b)) in plain.iter().zip(w.iter()).enumerate() { if a != b { - assert!(regs.contains(&i) || (0x728..0x72c).contains(&i) + assert!(regs.contains(&i) || (0x728..0x72c).contains(&i) || (flag..flag + 4).contains(&i) || pool_words.iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); } } @@ -315,7 +322,11 @@ def block(text, declaration): let window = 1 << 24 | 0x60 << 16; let ift = [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]; let (w, q) = ta_rt(&words, tl); - assert_eq!(q, taq_plain); + // StartTA marks the slot as an SCS user; nothing else in the sequence moves. + assert_eq!((u32_at(&taq_plain, ta::START_SCS), u32_at(&q, ta::START_SCS)), (0, 1)); + for (i, (a, b)) in taq_plain.iter().zip(q.iter()).enumerate() { + assert!(a == b || (ta::START_SCS..ta::START_SCS + 4).contains(&i), "TA seq byte {i:#x}"); + } assert_eq!((u16_at(&w, 0x748), u16_at(&w, 0x74a)), (68, 68 * 12)); let ta_plain_regs = records(&ta_plain, ta::REGS, 66); let got = records(&w, ta::REGS, 68); @@ -334,7 +345,11 @@ def block(text, declaration): } } let (w, q) = fs_rt(&words, fl); - assert_eq!(q, fsq_plain); + // StartFS marks the slot as an SCS user; nothing else in the sequence moves. + assert_eq!((u32_at(&fsq_plain, fs::START_SCS), u32_at(&q, fs::START_SCS)), (0, 1)); + for (i, (a, b)) in fsq_plain.iter().zip(q.iter()).enumerate() { + assert!(a == b || (fs::START_SCS..fs::START_SCS + 4).contains(&i), "FS seq byte {i:#x}"); + } assert_eq!((u16_at(&w, 0x788), u16_at(&w, 0x78a)), (84, 84 * 12)); let fs_plain_regs = records(&fs_plain, fs::REGS, 82); let got = records(&w, fs::REGS, 84); From 2412db2bdf80eb964dbf2f843de5bf34ee7094bb Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:13 -0500 Subject: [PATCH 5/7] drm/asahi: g16: share device-lifetime firmware-cached render records A render pass slot index is device-global and claimed by one flight at a time, so render microsequences and barrier records need not be allocated per VM. Mapping them with firmware-cached leaf 0x443 inside a per-VM render arena is unsafe on client teardown because KernelMapping::drop() fail-stops an ASC-cached M4 mapping that has no qualified teardown. Allocate render microsequences and barrier records once per pass slot index, on first use, from a device-lifetime allocator that is never dropped (resources::RenderCmds, reached through Factory), and let every VM's PassSlot of that index share them. Each microsequence keeps its own page and the barrier records share one page, matching compute unit barriers: 48 KiB per index (at most 2.25 MiB per boot) instead of 128 KiB per pass slot of every VM. Class::FwCoherent (firmware leaf 0x443 behind a cacheable host mapping, matching macOS 26B123 per-queue command objects) is accepted only by this device-lifetime allocator and never with a client or lower alias. Per-VM arenas and the session allocator reject it, so closing a client can never drop a firmware-cached mapping. Extend the host resource tests to verify that two VMs' pass slot k share one set, no VM arena owns a firmware-cached object, dropping a VM retains the set, and other allocators reject Class::FwCoherent. Pass slot backing drops from 608 to 480 KiB of metadata per VM. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 7 +- drivers/gpu/drm/asahi/g16/object.rs | 75 ++++++++++- drivers/gpu/drm/asahi/g16/resources.rs | 83 ++++++++++-- drivers/gpu/drm/asahi/g16/slots.rs | 85 ++++++++---- .../drivers/gpu/asahi-m4/test-resources.py | 122 ++++++++++++++---- 5 files changed, 300 insertions(+), 72 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 31e267b32760e..2dedd2d48c3b6 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -754,10 +754,11 @@ impl Firmware { let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; + let render_cmds = resources::RenderCmds::new()?; let slot = KBox::::new_uninit(GFP_KERNEL)?; - Ok((graph, slots, pools, vms, engine, slot)) + Ok((graph, slots, pools, vms, engine, render_cmds, slot)) })(); - let (graph, slots, pools, vms, engine, slot) = match backend { + let (graph, slots, pools, vms, engine, render_cmds, slot) = match backend { Ok(backend) => backend, Err(error) => { dev_err!( @@ -777,7 +778,7 @@ impl Firmware { events, .. } = KBox::into_inner(booted); - let private_factory = objects.private_factory(); + let private_factory = objects.private_factory(render_cmds); let mut firmware = slot .write_init(init!(Firmware { session, diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 4c94bfb15c44e..e5329887c1e9c 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -46,6 +46,13 @@ pub(crate) enum Class { Shared, /// Firmware and GPU, ASC-cached. SharedCached, + /// Firmware-only, ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS + /// 26B123 gives its per-queue command objects and the G13-G15 private-allocator contract + /// (`PROT_FW_PRIV_RW` behind `gem::new_kernel_object`). Only for records the host writes + /// before publication and the firmware only reads, with no client or lower alias, and only + /// from device-lifetime allocators ([`Factory::persistent_objects`]): an ASC-cached M4 + /// mapping has no qualified teardown, so its owner is never dropped. + FwCoherent, /// Firmware device mapping. #[allow(dead_code)] Mmio, @@ -59,6 +66,7 @@ impl Class { Class::FwCached => pte::FW_CACHED, Class::Shared => pte::SHARED, Class::SharedCached => pte::SHARED_CACHED, + Class::FwCoherent => pte::FW_CACHED, Class::Mmio => pte::MMIO, } } @@ -325,6 +333,7 @@ pub(crate) struct Factory { uat: Arc, window: Arc>, firmware: core::ops::Range, + render_cmds: Arc, } impl Factory { @@ -339,6 +348,7 @@ impl Factory { pending: None, }), sealed: false, + persistent: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -360,6 +370,7 @@ impl Factory { pending: None, }), sealed: false, + persistent: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -368,6 +379,36 @@ impl Factory { pages: 0, } } + + /// Allocates the only objects that may hold [`Class::FwCoherent`] records: firmware-only, + /// with no client VM binding. The caller owns them for the device lifetime and never drops + /// them ([`super::resources::RenderCmds`]). + pub(crate) fn persistent_objects(&self) -> Objects { + Objects { + dev: self.dev.clone(), + uat: self.uat.clone(), + window: self.window.clone(), + private: Some(Private { + vm: None, + firmware: self.firmware.clone(), + pending: None, + }), + sealed: false, + persistent: true, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + pages: 0, + } + } + + /// The device-lifetime render microsequences and barrier records of pass slot `k`, shared by + /// every VM's [`super::slots::PassSlot`] `k`. + pub(crate) fn pass_cmds(&self, k: usize) -> Result { + self.render_cmds.get(self, k) + } } /// The firmware object allocator and the set of retained objects. @@ -378,6 +419,8 @@ pub(crate) struct Objects { pub(crate) window: Arc>, private: Option, sealed: bool, + /// A device-lifetime allocator that may map [`Class::FwCoherent`] records. + persistent: bool, /// Next free VA of the firmware allocator window. fw_next: u64, /// Every object owned by this session or private arena. @@ -406,6 +449,7 @@ impl Objects { window: Arc::pin_init(new_mutex!(window, "g16::Objects::window"), GFP_KERNEL)?, private: None, sealed: false, + persistent: false, fw_next: hw::va::FW_ALLOC.start, retained: KVec::new(), clients: KVec::new(), @@ -416,19 +460,24 @@ impl Objects { } /// Freeze the session allocation boundary before making any private arenas. - pub(crate) fn private_factory(&mut self) -> Factory { + pub(crate) fn private_factory( + &mut self, + render_cmds: Arc, + ) -> Factory { self.sealed = true; Factory { dev: self.dev.clone(), uat: self.uat.clone(), window: self.window.clone(), firmware: self.fw_next..hw::va::FW_ALLOC.end, + render_cmds, } } /// Maps private backing into one client and unique kernel/firmware apertures. Mapping /// owners retain the GEM independently, including every partial construction failure. - /// All reclaimable objects are NC from creation; there is no ASC cache transition. + /// All reclaimable objects are NC from creation; there is no ASC cache transition. Only a + /// device-lifetime allocator maps [`Class::FwCoherent`] records, never reclaimed. fn alloc_private(&mut self, req: Request) -> Result> { self.alloc_private_in(req, None) } @@ -454,7 +503,12 @@ impl Objects { client_range: Option>, ) -> Result> { if !matches!(req.placement, Placement::Anywhere) - || !matches!(req.class, Class::Fw | Class::Shared) + || !matches!(req.class, Class::Fw | Class::Shared | Class::FwCoherent) + || (req.class == Class::FwCoherent + && (!self.persistent + || req.client.is_some() + || req.lower.is_some() + || client_range.is_some())) || req.size == 0 || req.offset >= hw::PAGE as usize { @@ -469,14 +523,21 @@ impl Objects { & !(hw::PAGE as usize - 1); self.retained.reserve(1, GFP_KERNEL)?; self.mappings.reserve(3, GFP_KERNEL)?; - let mut backing = gem::new_kernel_object_wc(&self.dev, bytes)?; + // A firmware-cached record needs a cacheable host view of the same pages (the host and + // firmware caches are coherent, as for G13-G15 private objects); every other private + // class keeps its write-combined view. + let mut backing = if req.class == Class::FwCoherent { + gem::new_kernel_object(&self.dev, bytes)? + } else { + gem::new_kernel_object_wc(&self.dev, bytes)? + }; let registered = self.dev.registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); gem::prepare_new_object(&backing.gem, parent.as_ref())?; let cpu = if req.cpu { let vmap = backing.vmap()?; let pointer = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; - // SAFETY: Fresh private WC mapping spans bytes and has not been exposed. + // SAFETY: Fresh private mapping spans bytes and has not been exposed. unsafe { core::ptr::write_bytes(pointer.as_ptr(), 0, bytes) }; Some(pointer) } else { @@ -619,6 +680,10 @@ impl Objects { } return self.alloc_private(req); } + // Session objects are write-combined: they never give the firmware a cached record. + if req.class == Class::FwCoherent { + return Err(EINVAL); + } if self.sealed { return Err(EBUSY); } diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index a599515ffc0a9..761b6bac29c19 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -9,7 +9,7 @@ use super::{ command::Command, object::{Factory, Objects}, pools::{PbEpoch, PoolSet}, - slots::{ComputeSlot, PassSlot, Placement}, + slots::{ComputeSlot, PassCmds, PassSlot, Placement}, vm::VmState, }; use crate::mmu; @@ -20,6 +20,60 @@ use kernel::{ sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SetOnce, SpinLockIrq}, }; +/// One pass slot index's device-lifetime render command records and the allocator that maps +/// them. The allocator is never dropped: an ASC-cached M4 mapping has no qualified teardown +/// (`mmu::KernelMapping::drop` refuses it), so even a failed construction keeps its mappings. +struct PersistentPassCmds { + objects: core::mem::ManuallyDrop, + cmds: Option, +} + +/// The firmware-cached render microsequences and barrier records of every pass slot index +/// (`0..RENDER_SLOTS`), created on first use and kept until reboot. A pass slot index is +/// device-global and claimed by one flight at a time, so every VM's [`PassSlot`] of an index +/// shares its records, and closing a VM drops no firmware-cached mapping. +#[pin_data] +pub(crate) struct RenderCmds { + #[pin] + sets: Mutex<[Option>; super::hw::sizes::RENDER_SLOTS]>, +} + +impl RenderCmds { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + sets <- new_mutex!( + [const { None }; super::hw::sizes::RENDER_SLOTS], + "g16::render_cmds" + ), + }), + GFP_KERNEL, + ) + } + + /// The records of pass slot index `k`, allocated from `factory` on first use. + pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result { + let mut sets = self.sets.lock(); + let entry = sets.get_mut(k).ok_or(EINVAL)?; + if let Some(cmds) = entry.as_ref().and_then(|set| set.cmds.as_ref()) { + return Ok(cmds.clone()); + } + let mut set = KBox::new( + PersistentPassCmds { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + cmds: None, + }, + GFP_KERNEL, + )?; + // From here on a failure leaks the allocator with whatever it mapped. + let cmds = PassCmds::new(&mut set.objects)?; + set.objects.finish_private()?; + set.cmds = Some(cmds.clone()); + *entry = Some(set); + Ok(cmds) + } +} + /// Never-exposed PB epochs an open VM keeps on standby after bursts drain. /// /// With PB epoch reuse most renders never expose a fresh epoch; keeping a @@ -167,14 +221,15 @@ impl ComputeUnitSet { pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; /// Demand-grown extension render pass slot tiers (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`). /// -/// Each extension `PassSlot` backs 3.59 MiB (2 MiB TPC + 1 MiB tilemap + 608 KiB metadata, -/// scratch, and barriers). Growing in four bounded chunks keeps compositor and shallow desktop -/// VMs on Tier 0 (~21.6 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, -/// and keeps every tier's client-object batch well below `MAX_CLIENT` (512): -/// - Tier 0 (`2..8`, 6 slots, +21.56 MiB / 21.56 MiB cum): compositors, 2-6 pass frames. -/// - Tier 1 (`8..18`, 10 slots, +35.94 MiB / 57.50 MiB cum): moderate multi-pass bursts. -/// - Tier 2 (`18..32`, 14 slots, +50.31 MiB / 107.81 MiB cum): 20-31 pass pipelined frames. -/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +57.50 MiB / 165.31 MiB cum at 48 slots): deep +/// Each extension `PassSlot` backs 3.47 MiB (2 MiB TPC + 1 MiB tilemap + 480 KiB metadata and +/// scratch; its microsequences and barriers are the device-lifetime [`RenderCmds`] of its index). +/// Growing in four bounded chunks keeps compositor and shallow desktop VMs on Tier 0 +/// (~20.8 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, and keeps +/// every tier's client-object batch well below `MAX_CLIENT` (512): +/// - Tier 0 (`2..8`, 6 slots, +20.81 MiB / 20.81 MiB cum): compositors, 2-6 pass frames. +/// - Tier 1 (`8..18`, 10 slots, +34.69 MiB / 55.50 MiB cum): moderate multi-pass bursts. +/// - Tier 2 (`18..32`, 14 slots, +48.56 MiB / 104.06 MiB cum): 20-31 pass pipelined frames. +/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +55.50 MiB / 159.56 MiB cum at 48 slots): deep /// multi-pass bursts (160 client mappings <= `MAX_CLIENT`). pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 4] = [ (BASE_RENDER_SLOTS, 8), @@ -324,8 +379,8 @@ fn should_expand_compute_ext( /// /// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives /// (`active_passes == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay -/// on the two base pass slots (~49.2 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, -/// +21.6 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, +/// on the two base pass slots (~48.9 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, +/// +20.8 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, /// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a /// sub-2 ms back-to-back burst; higher tiers allocate only when live passes plus this submission /// and one displacement slot exceed the currently backed capacity. @@ -467,7 +522,8 @@ impl RenderArena { let mut objects = factory.objects(vm); let mut passes = KVec::with_capacity(BASE_RENDER_SLOTS, GFP_KERNEL)?; for k in 0..BASE_RENDER_SLOTS { - passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; + let cmds = factory.pass_cmds(k)?; + passes.push(PassSlot::new(&mut objects, k as u64, 1, &cmds)?, GFP_KERNEL)?; } let pools = PoolSet::new_with_slots(&mut objects, factory, base_pb_slots)?; objects.finish_private()?; @@ -565,7 +621,8 @@ impl RenderExtArena { let mut tilemap_clean = KVec::with_capacity(count, GFP_KERNEL)?; let mut heap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; for k in slots.clone() { - passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; + let cmds = factory.pass_cmds(k)?; + passes.push(PassSlot::new(&mut objects, k as u64, 1, &cmds)?, GFP_KERNEL)?; tpc_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; tilemap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; tilemap_last.push(AtomicU64::new(0), GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 22a83b59b690f..711bcdae9a025 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -264,6 +264,56 @@ impl ComputeSlot { } } +/// The render microsequences and barrier records of one pass slot index, shared by every VM's +/// [`PassSlot`] of that index: the index is device-global and claimed by one flight at a time. +/// They are written by the host before publication and only read by the firmware, so they take +/// the firmware-cached [`Class::FwCoherent`] view macOS 26B123 gives its per-queue command +/// objects. Each microsequence keeps its own page; the barrier records share one page, as the +/// compute unit's barriers do. +#[derive(Clone)] +pub(crate) struct PassCmds { + pub(crate) ta_seq: Arc, + pub(crate) fs_seq: Arc, + pub(crate) own_barrier: Arc, + pub(crate) prev_barrier: Arc, + pub(crate) ta_fs_barrier: Arc, + pub(crate) fs_dep: Arc, + pub(crate) compute_barrier: Arc, + pub(crate) fs_compute_barrier: Arc, +} + +impl PassCmds { + /// Barrier records in the shared page: own, prev, TA->FS, FS dependency (one record each), + /// then the per-pipe compute and FS-compute barriers. + const OWN: usize = 0; + const PREV: usize = barrier::SIZE; + const TA_FS: usize = 2 * barrier::SIZE; + const FS_DEP: usize = 3 * barrier::SIZE; + const COMPUTE: usize = 4 * barrier::SIZE; + const FS_COMPUTE: usize = Self::COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; + const BARRIERS: usize = Self::FS_COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; + + /// Allocates one pass slot index's set from a device-lifetime allocator + /// ([`Factory::persistent_objects`]), which the caller never drops. + pub(crate) fn new(o: &mut Objects) -> Result { + let coherent = Class::FwCoherent; + let barriers = alloc(o, Self::BARRIERS, coherent, None, 0, false)?; + let record = |offset, size| FwObject::view(&barriers, offset, size); + Ok(Self { + ta_seq: alloc(o, ta::SEQ_OBJECT, coherent, None, 0, false)?, + fs_seq: alloc(o, fs::SEQ_OBJECT, coherent, None, 0, false)?, + own_barrier: record(Self::OWN, barrier::SIZE)?, + prev_barrier: record(Self::PREV, barrier::SIZE)?, + ta_fs_barrier: record(Self::TA_FS, barrier::SIZE)?, + fs_dep: record(Self::FS_DEP, barrier::SIZE)?, + compute_barrier: record(Self::COMPUTE, barrier::SIZE * sizes::COMPUTE_PIPES)?, + fs_compute_barrier: record(Self::FS_COMPUTE, barrier::SIZE * sizes::COMPUTE_PIPES)?, + }) + } +} + +const _: () = assert!(PassCmds::BARRIERS <= super::hw::PAGE as usize); + /// One render pass slot. pub(crate) struct PassSlot { pub(crate) aux: Arc, @@ -292,8 +342,9 @@ pub(crate) struct PassSlot { } impl PassSlot { - /// Allocates pass slot `i`'s objects, with their client leaf classes. - pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32) -> Result { + /// Allocates pass slot `i`'s objects, with their client leaf classes, around the + /// device-lifetime microsequences and barrier records `cmds` of index `i`. + pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32, cmds: &PassCmds) -> Result { let sh = Class::Shared; let off = client::pass_off(i); let tpc = if i >= sizes::BASE_RENDER_SLOTS as u64 { @@ -393,33 +444,19 @@ impl PassSlot { fs_scratch, fs_work, ta_work, - ta_seq: alloc(o, ta::SEQ_OBJECT, cmd_fw(), None, 0, false)?, - fs_seq: alloc(o, fs::SEQ_OBJECT, cmd_fw(), None, 0, false)?, + ta_seq: cmds.ta_seq.clone(), + fs_seq: cmds.fs_seq.clone(), ta_scratch: alloc(o, 0x10000, sh, None, 0, false)?, scene: alloc(o, super::fw::work::scene::SIZE, sh, None, 0, false)?, // Internal TA start/end, FS start/end; legacy user cells likewise. its: alloc(o, 32, sh, None, 0, false)?, _uts: alloc(o, 32, Class::Fw, None, 0, false)?, - own_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - prev_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - ta_fs_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - fs_dep: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - compute_barrier: alloc( - o, - barrier::SIZE * sizes::COMPUTE_PIPES, - cmd_fw(), - None, - 0, - false, - )?, - fs_compute_barrier: alloc( - o, - barrier::SIZE * sizes::COMPUTE_PIPES, - cmd_fw(), - None, - 0, - false, - )?, + own_barrier: cmds.own_barrier.clone(), + prev_barrier: cmds.prev_barrier.clone(), + ta_fs_barrier: cmds.ta_fs_barrier.clone(), + fs_dep: cmds.fs_dep.clone(), + compute_barrier: cmds.compute_barrier.clone(), + fs_compute_barrier: cmds.fs_compute_barrier.clone(), }) } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 9e5331c254c9f..64f7305725f5b 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -94,7 +94,7 @@ def module(text, name): } pub mod object { use crate::*;use crate::sync::Arc; - #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,Mmio} + #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,FwCoherent,Mmio} pub enum Placement{Anywhere} pub struct Request{pub size:usize,pub class:Class,pub placement:Placement,pub offset:usize,pub client:Option<(u64,u64)>,pub lower:Option,pub cpu:bool} pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool,pub write_bytes:std::sync::atomic::AtomicUsize} @@ -118,15 +118,28 @@ def module(text, name): impl Factory{ pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} pub fn fw_objects(&self)->Objects{Objects::new()} + pub fn persistent_objects(&self)->Objects{Objects::persistent()} } pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} - pub struct Objects{pub objects:Vec>} + pub struct Objects{pub objects:Vec>,pub persistent:bool} + // Device-lifetime render records of each pass slot index, per test thread (the + // production table is resources::RenderCmds): one never-dropped allocator owns them. + std::thread_local!{ + pub static PERSISTENT:std::cell::RefCell>=const{std::cell::RefCell::new(None)}; + pub static PASS_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; + } + pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ + if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent)).unwrap()}); + PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c + } impl Objects{ - pub fn new()->Self{Self{objects:vec![]}} + pub fn new()->Self{Self{objects:vec![],persistent:false}} + pub fn persistent()->Self{Self{objects:vec![],persistent:true}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()||r.lower.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -274,7 +287,7 @@ def module(text, name): fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); let f=g16::object::Factory; - for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} + for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap();} Arenas{compute:g16::resources::ComputeArena{compute,render:None,hw_slots:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<,lower:Option|Request{size:0x40,class,placement:Placement::Anywhere,offset:0,client,lower,cpu:true}; + // A per-VM arena cannot map a firmware-cached record (its teardown would unmap it), and + // a device-lifetime allocator cannot give one a client or lower alias. + let mut vm=Objects::new(); + assert!(matches!(vm.alloc(req(Class::FwCoherent,None,None)),Err(EINVAL))); + let mut dev=Objects::persistent(); + assert!(matches!(dev.alloc(req(Class::FwCoherent,Some((0x7040000000,g16::hw::pte::LEAF_NC)),None)),Err(EINVAL))); + assert!(matches!(dev.alloc(req(Class::FwCoherent,None,Some(0x70f1000000))),Err(EINVAL))); + // Two VMs' pass slot 3 share index 3's records; neither VM arena owns any of them. + let (mut a,mut b)=(Objects::new(),Objects::new()); + let pa=g16::slots::PassSlot::new(&mut a,3,1,&crate::g16::object::test_cmds(3)).unwrap(); + let pb=g16::slots::PassSlot::new(&mut b,3,1,&crate::g16::object::test_cmds(3)).unwrap(); + let records=|p:&g16::slots::PassSlot|[p.ta_seq.clone(),p.fs_seq.clone(),p.own_barrier.clone(),p.prev_barrier.clone(),p.ta_fs_barrier.clone(),p.fs_dep.clone(),p.compute_barrier.clone(),p.fs_compute_barrier.clone()]; + let (ra,rb)=(records(&pa),records(&pb)); + for (x,y) in ra.iter().zip(rb.iter()){ + assert!(crate::sync::Arc::ptr_eq(x,y)); + assert_eq!(x.class,Class::FwCoherent); + assert_eq!((x.gva,x.lower_gva,x.client_leaf),(None,None,None)); + } + assert!(a.objects.iter().chain(b.objects.iter()).all(|o|o.class!=Class::FwCoherent)); + assert!(a.objects.iter().chain(b.objects.iter()).all(|o|ra.iter().all(|r|!crate::sync::Arc::ptr_eq(o,r)))); + let pc=g16::slots::PassSlot::new(&mut b,4,1,&crate::g16::object::test_cmds(4)).unwrap(); + assert!(!crate::sync::Arc::ptr_eq(&pc.ta_seq,&pa.ta_seq)&&!crate::sync::Arc::ptr_eq(&pc.own_barrier,&pa.own_barrier)); + // Microsequences keep whole pages; the barrier records are disjoint 0x40-aligned + // records of one page; the encoders name the shared records. + assert_eq!((pa.ta_seq.va&0x3fff,pa.fs_seq.va&0x3fff),(0,0)); + let page=ra[2].va&!0x3fff; + let mut spans:Vec<(u64,u64)>=ra[2..].iter().map(|o|(o.va,o.va+o.size as u64)).collect(); + spans.sort(); + assert!(spans.windows(2).all(|w|w[0].1<=w[1].0)); + assert!(ra[2..].iter().all(|o|o.va&!0x3fff==page&&o.va%0x40==0&&o.va+o.size as u64<=page+0x4000)); + assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pb.refs().ta_seq,pb.refs().fs_seq)); + assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pa.ta_seq.va,pa.fs_seq.va)); + // Closing VM a drops its arena and pass slot: the device table still owns and hands + // out the same records, mapped by its never-dropped allocator. + drop(pa);drop(a); + let again=crate::g16::object::test_cmds(3); + assert!(crate::sync::Arc::ptr_eq(&again.ta_seq,&rb[0])&&crate::sync::Arc::ptr_eq(&again.fs_dep,&rb[5])); + crate::g16::object::PERSISTENT.with(|p|{ + let p=p.borrow();let owned=&p.as_ref().unwrap().objects; + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[0]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[1]))); + assert!(owned.iter().all(|o|o.class==Class::FwCoherent)); + }); + drop(pb);drop(pc);drop(b); + } #[test]fn work_has_kernel_lower_alias_without_application_alias(){ let mut o=Objects::new();let slots=Slots::new().unwrap();let arena=arenas(&mut o); let work=arena.compute.compute.iter().map(|s|&s.work) @@ -682,7 +743,7 @@ def module(text, name): let mut scene_lists=Vec::new(); let count_client=|objs:&Objects|objs.objects.iter().filter(|a|a.gva.is_some()).count(); for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { - let pass=g16::slots::PassSlot::new(&mut o,k,1).unwrap(); + let pass=g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(); let va=pass.refs().scene_list; assert_ne!(va,0); assert!(!scene_lists.contains(&va),"each pass slot must own a distinct scene_list"); @@ -692,7 +753,7 @@ def module(text, name): for &(start, end) in &g16::resources::EXT_RENDER_TIERS { let mut ot = Objects::new(); for k in start..end { - g16::slots::PassSlot::new(&mut ot, k as u64, 1).unwrap(); + g16::slots::PassSlot::new(&mut ot, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(); } let tier_maps = count_client(&ot); assert!( @@ -1023,7 +1084,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut passes=KVec::new(); for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { - let pass=g16::slots::PassSlot::new(&mut o,k,1).unwrap(); + let pass=g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(); if k < g16::hw::sizes::BASE_RENDER_SLOTS as u64 { assert_eq!(pass.tpc.size as u64, g16::hw::client::TPC_SIZE); assert_eq!(pass.tilemap.size as u64, g16::hw::client::TILEMAP_SIZE); @@ -1129,6 +1190,7 @@ def module(text, name): assert_eq!(render.passes[0].pre[0].fills.lock().unwrap().len(),pre0_before); } + #[test]fn offlock_scrub_falls_back_on_error_drop_recovery_and_cross_vm(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); @@ -1262,7 +1324,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let mut passes=KVec::new(); for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { - passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; @@ -1324,7 +1386,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let mut passes=KVec::new(); for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { - passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; @@ -1470,20 +1532,26 @@ def module(text, name): // Verify exact per-slot mapped backing bytes for Base vs Ext slots. let mut o_base = Objects::new(); - g16::slots::PassSlot::new(&mut o_base, 0, 1).unwrap(); + g16::slots::PassSlot::new(&mut o_base, 0, 1, &crate::g16::object::test_cmds((0) as u64)).unwrap(); let base_slot_bytes: usize = o_base.objects.iter().map(|obj| obj.mapped).sum(); - assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 608) * 1024); + // Microsequences and barrier records are the device-lifetime records of the index. + assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 480) * 1024); let mut o_ext = Objects::new(); - g16::slots::PassSlot::new(&mut o_ext, 2, 1).unwrap(); + g16::slots::PassSlot::new(&mut o_ext, 2, 1, &crate::g16::object::test_cmds((2) as u64)).unwrap(); let ext_slot_bytes: usize = o_ext.objects.iter().map(|obj| obj.mapped).sum(); - assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 608) * 1024); + assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 480) * 1024); + // Each index's device-lifetime records: two microsequence pages and one barrier page. + let indices = crate::g16::object::PASS_CMDS.with(|p| p.borrow().len()); + let device_bytes: usize = crate::g16::object::PERSISTENT + .with(|p| p.borrow().as_ref().unwrap().objects.iter().map(|obj| obj.mapped).sum()); + assert_eq!((indices, device_bytes), (2, 2 * 3 * 16 * 1024)); // Cumulative extension backing across the 4 demand-grown tiers: - // Tier 0 (6 ext): 21.5625 MiB, Tier 1 (16 ext): 57.50 MiB, - // Tier 2 (30 ext): 107.8125 MiB, Tier 3 (46 ext): 165.3125 MiB. - assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 22_080 * 1024); - assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 58_880 * 1024); - assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 110_400 * 1024); - assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 169_280 * 1024); + // Tier 0 (6 ext): 20.8125 MiB, Tier 1 (16 ext): 55.50 MiB, + // Tier 2 (30 ext): 104.0625 MiB, Tier 3 (46 ext): 159.5625 MiB. + assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 21_312 * 1024); + assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 56_832 * 1024); + assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 106_560 * 1024); + assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 163_392 * 1024); } #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ @@ -1678,7 +1746,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut passes=KVec::new(); for k in 0..4u64 { - passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render),hw_slots:None}; @@ -1771,7 +1839,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut passes=KVec::new(); for k in 0..3u64 { - passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone()),hw_slots:None}; @@ -2116,7 +2184,7 @@ def module(text, name): let mut s = Slots::new().unwrap(); let mut passes = KVec::new(); for k in 0..EXT_RENDER_TIERS[1].1 { - passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let render = sync::Arc::new(render_arena(passes), 0).unwrap(); let prep = g16::resources::ComputeArena { @@ -2210,7 +2278,7 @@ def module(text, name): } let mut passes = KVec::new(); for k in 0..18 { - passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let shared_prep_compute = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; @@ -2227,7 +2295,7 @@ def module(text, name): let pb_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); let mut r_passes = KVec::new(); for k in 0..18 { - r_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + r_passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let r_arena = sync::Arc::new(render_arena(r_passes), 0).unwrap(); let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()), hw_slots: None }; @@ -2394,7 +2462,7 @@ def module(text, name): let mut s2 = Slots::new().unwrap(); let mut sc_passes = KVec::new(); for k in 0..2 { - sc_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + sc_passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let sc_arena = sync::Arc::new(render_arena(sc_passes), 0).unwrap(); let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()), hw_slots: None }; @@ -2828,7 +2896,7 @@ def module(text, name): ).replace('fn new(', 'pub(crate) fn new(').replace('fn init(', 'pub(crate) fn init(') source = source.replace('__GRAPH_TYPES__', graph_types) source = source.replace('__ALLOC__',item(graph_source,'pub(crate) fn alloc(')).replace('__ALLOC_WORK__',item(graph_source,'pub(crate) fn alloc_work(')) -source = source.replace('__HW__','\n'.join(module(hw,n) for n in ('client','sizes','engine','tuning','pte'))).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) +source = source.replace('__HW__','\n'.join([module(hw,n) for n in ('client','sizes','engine','tuning','pte')] + [l for l in hw.splitlines() if l.startswith('pub(crate) const PAGE: u64')])).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) (out/'check-resources.rs').write_text(source) log = '' for command in [ From e6d8e0ae150098e05a149131f1c7227c5aacbbc0 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:14 -0500 Subject: [PATCH 6/7] drm/asahi: g16: share device-lifetime firmware-cached render work images Move the TA and FS work images, the larger part of what the firmware reads per render, into the per-index device-lifetime RenderCmds records. macOS 26B123 maps its per-queue command objects, work items included, with the firmware-cached leaf 0x443 and maps the same pages into GPU context 0 with the uncached leaf 0xc8b. The work images keep that uncached kernel GPU task lower alias. Because the host writes to the work images through a cacheable mapping while the GPU reads their register lists through the uncached alias, FwObject cleans each store to such an object to the point of coherency (dc cvac, then dsb sy). Only a firmware-cached object with a lower alias performs this clean; the microsequences and barriers, which only the firmware reads, are unchanged. Each pass slot index now holds five device-lifetime pages (80 KiB, at most 3.75 MiB per boot) and every VM pass slot sheds two more pages (448 KiB of metadata). Compute command objects are unchanged because the host reads firmware-written descriptor counters from the compute work image. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/object.rs | 44 +++++++++---- drivers/gpu/drm/asahi/g16/resources.rs | 31 +++++----- drivers/gpu/drm/asahi/g16/slots.rs | 62 ++++++++++++------- .../drivers/gpu/asahi-m4/test-resources.py | 56 +++++++++++------ 4 files changed, 125 insertions(+), 68 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index e5329887c1e9c..c4c42d1dd1290 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -46,12 +46,14 @@ pub(crate) enum Class { Shared, /// Firmware and GPU, ASC-cached. SharedCached, - /// Firmware-only, ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS - /// 26B123 gives its per-queue command objects and the G13-G15 private-allocator contract - /// (`PROT_FW_PRIV_RW` behind `gem::new_kernel_object`). Only for records the host writes - /// before publication and the firmware only reads, with no client or lower alias, and only + /// ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS 26B123 gives its + /// per-queue command objects and the G13-G15 private-allocator contract (`PROT_FW_PRIV_RW` + /// behind `gem::new_kernel_object`). Only for command records the host writes before + /// publication and never reads back what the firmware writes, with no client alias, and only /// from device-lifetime allocators ([`Factory::persistent_objects`]): an ASC-cached M4 - /// mapping has no qualified teardown, so its owner is never dropped. + /// mapping has no qualified teardown, so its owner is never dropped. A kernel GPU task lower + /// alias stays uncached, as macOS maps its work items for the GPU; host stores to such an + /// object are cleaned to the point of coherency for it ([`FwObject::write`]). FwCoherent, /// Firmware device mapping. #[allow(dead_code)] @@ -108,6 +110,9 @@ pub(crate) struct FwObject { // Subrecords retain the owning WC vmap as well as their GEM. _parent: Option>, limit: Option, + /// Host stores go through a cacheable view the GPU reads through its uncached lower alias: + /// each store is cleaned to the point of coherency. + clean: bool, } // SAFETY: The object only refers to kernel memory shared with the firmware; every host access @@ -156,17 +161,27 @@ impl FwObject { backing: gem::ObjectRef::new(object.gem()), _parent: Some(object.clone()), limit: Some(size), + clean: object.clean, }, GFP_KERNEL, )?) } + /// Makes host stores to `len` bytes at `p` visible to an uncached GPU alias. + fn stored(&self, p: *const u8, len: usize) { + if self.clean { + crate::pgtable::clean_poc(p, len); + crate::pgtable::poc_barrier(); + } + } + /// Copies bytes into the object before it is published, or into host-owned words. pub(crate) fn write(&self, offset: usize, bytes: &[u8]) -> Result { let p = self.ptr(offset, bytes.len())?; // SAFETY: `p` is valid for `bytes.len()` bytes of the object's mapping, which no Rust // reference aliases. unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()) }; + self.stored(p, bytes.len()); Ok(()) } @@ -175,6 +190,7 @@ impl FwObject { let p = self.ptr(offset, len)?; // SAFETY: As for `write`. unsafe { core::ptr::write_bytes(p, value, len) }; + self.stored(p, len); Ok(()) } @@ -184,6 +200,7 @@ impl FwObject { if p as usize % 4 == 0 { // SAFETY: `p` is valid and aligned for a u32. unsafe { p.cast::().write_volatile(value.to_le()) }; + self.stored(p, 4); Ok(()) } else { self.write(offset, &value.to_le_bytes()) @@ -196,6 +213,7 @@ impl FwObject { if p as usize % 8 == 0 { // SAFETY: `p` is valid and aligned for a u64. unsafe { p.cast::().write_volatile(value.to_le()) }; + self.stored(p, 8); Ok(()) } else { self.write(offset, &value.to_le_bytes()) @@ -404,8 +422,8 @@ impl Factory { } } - /// The device-lifetime render microsequences and barrier records of pass slot `k`, shared by - /// every VM's [`super::slots::PassSlot`] `k`. + /// The device-lifetime render command records of pass slot `k`, shared by every VM's + /// [`super::slots::PassSlot`] `k`. pub(crate) fn pass_cmds(&self, k: usize) -> Result { self.render_cmds.get(self, k) } @@ -505,10 +523,7 @@ impl Objects { if !matches!(req.placement, Placement::Anywhere) || !matches!(req.class, Class::Fw | Class::Shared | Class::FwCoherent) || (req.class == Class::FwCoherent - && (!self.persistent - || req.client.is_some() - || req.lower.is_some() - || client_range.is_some())) + && (!self.persistent || req.client.is_some() || client_range.is_some())) || req.size == 0 || req.offset >= hw::PAGE as usize { @@ -534,11 +549,16 @@ impl Objects { let registered = self.dev.registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); gem::prepare_new_object(&backing.gem, parent.as_ref())?; + let clean = req.class == Class::FwCoherent && req.lower.is_some(); let cpu = if req.cpu { let vmap = backing.vmap()?; let pointer = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; // SAFETY: Fresh private mapping spans bytes and has not been exposed. unsafe { core::ptr::write_bytes(pointer.as_ptr(), 0, bytes) }; + if clean { + crate::pgtable::clean_poc(pointer.as_ptr(), bytes); + crate::pgtable::poc_barrier(); + } Some(pointer) } else { None @@ -622,6 +642,7 @@ impl Objects { backing, _parent: None, limit: None, + clean, }, GFP_KERNEL, )?; @@ -777,6 +798,7 @@ impl Objects { backing, _parent: None, limit: None, + clean: false, }) .into(); self.retained.push(object.clone(), GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 761b6bac29c19..25b0d609a3d2a 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -28,10 +28,11 @@ struct PersistentPassCmds { cmds: Option, } -/// The firmware-cached render microsequences and barrier records of every pass slot index -/// (`0..RENDER_SLOTS`), created on first use and kept until reboot. A pass slot index is -/// device-global and claimed by one flight at a time, so every VM's [`PassSlot`] of an index -/// shares its records, and closing a VM drops no firmware-cached mapping. +/// The firmware-cached render command records (work images, microsequences and barrier records) +/// of every pass slot index (`0..RENDER_SLOTS`), created on first use and kept until reboot. A +/// pass slot index is device-global and claimed by one flight at a time, so every VM's +/// [`PassSlot`] of an index shares its records, and closing a VM drops no firmware-cached +/// mapping. #[pin_data] pub(crate) struct RenderCmds { #[pin] @@ -66,7 +67,7 @@ impl RenderCmds { GFP_KERNEL, )?; // From here on a failure leaks the allocator with whatever it mapped. - let cmds = PassCmds::new(&mut set.objects)?; + let cmds = PassCmds::new(&mut set.objects, k as u64)?; set.objects.finish_private()?; set.cmds = Some(cmds.clone()); *entry = Some(set); @@ -221,15 +222,15 @@ impl ComputeUnitSet { pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; /// Demand-grown extension render pass slot tiers (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`). /// -/// Each extension `PassSlot` backs 3.47 MiB (2 MiB TPC + 1 MiB tilemap + 480 KiB metadata and -/// scratch; its microsequences and barriers are the device-lifetime [`RenderCmds`] of its index). -/// Growing in four bounded chunks keeps compositor and shallow desktop VMs on Tier 0 -/// (~20.8 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, and keeps -/// every tier's client-object batch well below `MAX_CLIENT` (512): -/// - Tier 0 (`2..8`, 6 slots, +20.81 MiB / 20.81 MiB cum): compositors, 2-6 pass frames. -/// - Tier 1 (`8..18`, 10 slots, +34.69 MiB / 55.50 MiB cum): moderate multi-pass bursts. -/// - Tier 2 (`18..32`, 14 slots, +48.56 MiB / 104.06 MiB cum): 20-31 pass pipelined frames. -/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +55.50 MiB / 159.56 MiB cum at 48 slots): deep +/// Each extension `PassSlot` backs 3.44 MiB (2 MiB TPC + 1 MiB tilemap + 448 KiB metadata and +/// scratch; its work images, microsequences and barriers are the device-lifetime [`RenderCmds`] +/// of its index). Growing in four bounded chunks keeps compositor and shallow desktop VMs on +/// Tier 0 (~20.6 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, and +/// keeps every tier's client-object batch well below `MAX_CLIENT` (512): +/// - Tier 0 (`2..8`, 6 slots, +20.63 MiB / 20.63 MiB cum): compositors, 2-6 pass frames. +/// - Tier 1 (`8..18`, 10 slots, +34.38 MiB / 55.00 MiB cum): moderate multi-pass bursts. +/// - Tier 2 (`18..32`, 14 slots, +48.13 MiB / 103.13 MiB cum): 20-31 pass pipelined frames. +/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +55.00 MiB / 158.13 MiB cum at 48 slots): deep /// multi-pass bursts (160 client mappings <= `MAX_CLIENT`). pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 4] = [ (BASE_RENDER_SLOTS, 8), @@ -380,7 +381,7 @@ fn should_expand_compute_ext( /// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives /// (`active_passes == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay /// on the two base pass slots (~48.9 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, -/// +20.8 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, +/// +20.6 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, /// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a /// sub-2 ms back-to-back burst; higher tiers allocate only when live passes plus this submission /// and one displacement slot exceed the currently backed capacity. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 711bcdae9a025..f6952828e1eca 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -264,14 +264,18 @@ impl ComputeSlot { } } -/// The render microsequences and barrier records of one pass slot index, shared by every VM's -/// [`PassSlot`] of that index: the index is device-global and claimed by one flight at a time. -/// They are written by the host before publication and only read by the firmware, so they take -/// the firmware-cached [`Class::FwCoherent`] view macOS 26B123 gives its per-queue command -/// objects. Each microsequence keeps its own page; the barrier records share one page, as the -/// compute unit's barriers do. +/// The render command records of one pass slot index (TA and FS work images, microsequences and +/// barrier records), shared by every VM's [`PassSlot`] of that index: the index is device-global +/// and claimed by one flight at a time. The host writes them before publication and never reads +/// back what the firmware writes, so they take the firmware-cached [`Class::FwCoherent`] view +/// macOS 26B123 gives its per-queue command objects. The work images keep their uncached kernel +/// GPU task lower alias, as macOS maps its work items for the GPU. Each work image and +/// microsequence keeps its own page; the barrier records share one page, as the compute unit's +/// barriers do. #[derive(Clone)] pub(crate) struct PassCmds { + pub(crate) ta_work: Arc, + pub(crate) fs_work: Arc, pub(crate) ta_seq: Arc, pub(crate) fs_seq: Arc, pub(crate) own_barrier: Arc, @@ -293,13 +297,37 @@ impl PassCmds { const FS_COMPUTE: usize = Self::COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; const BARRIERS: usize = Self::FS_COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; - /// Allocates one pass slot index's set from a device-lifetime allocator + /// Allocates pass slot index `i`'s set from a device-lifetime allocator /// ([`Factory::persistent_objects`]), which the caller never drops. - pub(crate) fn new(o: &mut Objects) -> Result { + pub(crate) fn new(o: &mut Objects, i: u64) -> Result { let coherent = Class::FwCoherent; + let off = client::pass_off(i); + let mut work = |size, page, offset| { + o.alloc(super::object::Request { + size, + class: coherent, + placement: super::object::Placement::Anywhere, + offset, + client: None, + lower: Some(page), + cpu: true, + }) + }; + let fs_work = work( + fs::WORK_SIZE, + client::FS_WORK_PAGE + off, + client::FS_WORK_OFF as usize, + )?; + let ta_work = work( + ta::WORK_SIZE, + client::TA_WORK_PAGE + off, + client::TA_WORK_OFF as usize, + )?; let barriers = alloc(o, Self::BARRIERS, coherent, None, 0, false)?; let record = |offset, size| FwObject::view(&barriers, offset, size); Ok(Self { + ta_work, + fs_work, ta_seq: alloc(o, ta::SEQ_OBJECT, coherent, None, 0, false)?, fs_seq: alloc(o, fs::SEQ_OBJECT, coherent, None, 0, false)?, own_barrier: record(Self::OWN, barrier::SIZE)?, @@ -343,7 +371,7 @@ pub(crate) struct PassSlot { impl PassSlot { /// Allocates pass slot `i`'s objects, with their client leaf classes, around the - /// device-lifetime microsequences and barrier records `cmds` of index `i`. + /// device-lifetime command records `cmds` of index `i`. pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32, cmds: &PassCmds) -> Result { let sh = Class::Shared; let off = client::pass_off(i); @@ -421,18 +449,6 @@ impl PassSlot { 0, false, )?; - let fs_work = alloc_work( - o, - fs::WORK_SIZE, - client::FS_WORK_PAGE + off, - client::FS_WORK_OFF as usize, - )?; - let ta_work = alloc_work( - o, - ta::WORK_SIZE, - client::TA_WORK_PAGE + off, - client::TA_WORK_OFF as usize, - )?; Ok(Self { aux, pre, @@ -442,8 +458,8 @@ impl PassSlot { scene_user, scene_list, fs_scratch, - fs_work, - ta_work, + fs_work: cmds.fs_work.clone(), + ta_work: cmds.ta_work.clone(), ta_seq: cmds.ta_seq.clone(), fs_seq: cmds.fs_seq.clone(), ta_scratch: alloc(o, 0x10000, sh, None, 0, false)?, diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 64f7305725f5b..2df865d4f856a 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -131,7 +131,7 @@ def module(text, name): } pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} - let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent)).unwrap()}); + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent),k).unwrap()}); PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c } impl Objects{ @@ -139,7 +139,7 @@ def module(text, name): pub fn persistent()->Self{Self{objects:vec![],persistent:true}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()||r.lower.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -354,18 +354,23 @@ def module(text, name): assert!(matches!(vm.alloc(req(Class::FwCoherent,None,None)),Err(EINVAL))); let mut dev=Objects::persistent(); assert!(matches!(dev.alloc(req(Class::FwCoherent,Some((0x7040000000,g16::hw::pte::LEAF_NC)),None)),Err(EINVAL))); - assert!(matches!(dev.alloc(req(Class::FwCoherent,None,Some(0x70f1000000))),Err(EINVAL))); + assert!(dev.alloc(req(Class::FwCoherent,None,Some(0x70f1000000))).is_ok()); // Two VMs' pass slot 3 share index 3's records; neither VM arena owns any of them. let (mut a,mut b)=(Objects::new(),Objects::new()); let pa=g16::slots::PassSlot::new(&mut a,3,1,&crate::g16::object::test_cmds(3)).unwrap(); let pb=g16::slots::PassSlot::new(&mut b,3,1,&crate::g16::object::test_cmds(3)).unwrap(); - let records=|p:&g16::slots::PassSlot|[p.ta_seq.clone(),p.fs_seq.clone(),p.own_barrier.clone(),p.prev_barrier.clone(),p.ta_fs_barrier.clone(),p.fs_dep.clone(),p.compute_barrier.clone(),p.fs_compute_barrier.clone()]; + let records=|p:&g16::slots::PassSlot|[p.ta_seq.clone(),p.fs_seq.clone(),p.own_barrier.clone(),p.prev_barrier.clone(),p.ta_fs_barrier.clone(),p.fs_dep.clone(),p.compute_barrier.clone(),p.fs_compute_barrier.clone(),p.ta_work.clone(),p.fs_work.clone()]; let (ra,rb)=(records(&pa),records(&pb)); - for (x,y) in ra.iter().zip(rb.iter()){ + for (i,(x,y)) in ra.iter().zip(rb.iter()).enumerate(){ assert!(crate::sync::Arc::ptr_eq(x,y)); assert_eq!(x.class,Class::FwCoherent); - assert_eq!((x.gva,x.lower_gva,x.client_leaf),(None,None,None)); + assert_eq!((x.gva,x.client_leaf),(None,None)); + // Only the work images have the (uncached) kernel GPU task lower alias. + assert_eq!(x.lower_gva.is_some(),i>=8); } + assert!(ra[8..].iter().all(|o|o.lower_leaf==Some(g16::hw::pte::LOWER))); + assert_eq!((pa.refs().ta_work_gva,pa.refs().fs_work_gva),(pb.refs().ta_work_gva,pb.refs().fs_work_gva)); + assert_eq!((pa.refs().ta_work,pa.refs().ta_work_gva),(ra[8].va,ra[8].lower_gva.unwrap())); assert!(a.objects.iter().chain(b.objects.iter()).all(|o|o.class!=Class::FwCoherent)); assert!(a.objects.iter().chain(b.objects.iter()).all(|o|ra.iter().all(|r|!crate::sync::Arc::ptr_eq(o,r)))); let pc=g16::slots::PassSlot::new(&mut b,4,1,&crate::g16::object::test_cmds(4)).unwrap(); @@ -374,10 +379,10 @@ def module(text, name): // records of one page; the encoders name the shared records. assert_eq!((pa.ta_seq.va&0x3fff,pa.fs_seq.va&0x3fff),(0,0)); let page=ra[2].va&!0x3fff; - let mut spans:Vec<(u64,u64)>=ra[2..].iter().map(|o|(o.va,o.va+o.size as u64)).collect(); + let mut spans:Vec<(u64,u64)>=ra[2..8].iter().map(|o|(o.va,o.va+o.size as u64)).collect(); spans.sort(); assert!(spans.windows(2).all(|w|w[0].1<=w[1].0)); - assert!(ra[2..].iter().all(|o|o.va&!0x3fff==page&&o.va%0x40==0&&o.va+o.size as u64<=page+0x4000)); + assert!(ra[2..8].iter().all(|o|o.va&!0x3fff==page&&o.va%0x40==0&&o.va+o.size as u64<=page+0x4000)); assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pb.refs().ta_seq,pb.refs().fs_seq)); assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pa.ta_seq.va,pa.fs_seq.va)); // Closing VM a drops its arena and pass slot: the device table still owns and hands @@ -389,12 +394,16 @@ def module(text, name): let p=p.borrow();let owned=&p.as_ref().unwrap().objects; assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[0]))); assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[1]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[8]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[9]))); assert!(owned.iter().all(|o|o.class==Class::FwCoherent)); }); drop(pb);drop(pc);drop(b); } #[test]fn work_has_kernel_lower_alias_without_application_alias(){ let mut o=Objects::new();let slots=Slots::new().unwrap();let arena=arenas(&mut o); + assert!(arena.compute.compute.iter().all(|s|s.work.class==g16::object::Class::Shared)); + assert!(arena.render.passes.iter().all(|s|s.ta_work.class==g16::object::Class::FwCoherent&&s.fs_work.class==g16::object::Class::FwCoherent)); let work=arena.compute.compute.iter().map(|s|&s.work) .chain(arena.render.passes.iter().flat_map(|s|[&s.ta_work,&s.fs_work])); for object in work { @@ -402,7 +411,7 @@ def module(text, name): assert_eq!(object.client_leaf,None); assert!(object.lower_gva.is_some()); assert_eq!(object.lower_leaf,Some(0x00c0000000000c8b)); - assert_eq!(object.class,g16::object::Class::Shared); + assert!(object.class==g16::object::Class::Shared||object.class==g16::object::Class::FwCoherent); assert!(object.va>=0xfffffc2000000000); let lower=object.lower_gva.unwrap(); for client in &o.objects { @@ -1535,23 +1544,24 @@ def module(text, name): g16::slots::PassSlot::new(&mut o_base, 0, 1, &crate::g16::object::test_cmds((0) as u64)).unwrap(); let base_slot_bytes: usize = o_base.objects.iter().map(|obj| obj.mapped).sum(); // Microsequences and barrier records are the device-lifetime records of the index. - assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 480) * 1024); + assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 448) * 1024); let mut o_ext = Objects::new(); g16::slots::PassSlot::new(&mut o_ext, 2, 1, &crate::g16::object::test_cmds((2) as u64)).unwrap(); let ext_slot_bytes: usize = o_ext.objects.iter().map(|obj| obj.mapped).sum(); - assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 480) * 1024); - // Each index's device-lifetime records: two microsequence pages and one barrier page. + assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 448) * 1024); + // Each index's device-lifetime records: two work image pages, two microsequence pages + // and one barrier page. let indices = crate::g16::object::PASS_CMDS.with(|p| p.borrow().len()); let device_bytes: usize = crate::g16::object::PERSISTENT .with(|p| p.borrow().as_ref().unwrap().objects.iter().map(|obj| obj.mapped).sum()); - assert_eq!((indices, device_bytes), (2, 2 * 3 * 16 * 1024)); + assert_eq!((indices, device_bytes), (2, 2 * 5 * 16 * 1024)); // Cumulative extension backing across the 4 demand-grown tiers: - // Tier 0 (6 ext): 20.8125 MiB, Tier 1 (16 ext): 55.50 MiB, - // Tier 2 (30 ext): 104.0625 MiB, Tier 3 (46 ext): 159.5625 MiB. - assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 21_312 * 1024); - assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 56_832 * 1024); - assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 106_560 * 1024); - assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 163_392 * 1024); + // Tier 0 (6 ext): 20.625 MiB, Tier 1 (16 ext): 55.00 MiB, + // Tier 2 (30 ext): 103.125 MiB, Tier 3 (46 ext): 158.125 MiB. + assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 21_120 * 1024); + assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 56_320 * 1024); + assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 105_600 * 1024); + assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 161_920 * 1024); } #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ @@ -2861,6 +2871,14 @@ def module(text, name): source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() +object_source = (production/'object.rs').read_text() +# A firmware-cached object with an uncached GPU lower alias is cleaned to the point of +# coherency after every host store; only that combination sets the flag. +stored_fn = item(object_source, 'fn stored(&self') +assert 'crate::pgtable::clean_poc(' in stored_fn and 'crate::pgtable::poc_barrier()' in stored_fn, 'FwObject::stored must clean and complete' +for store in ('pub(crate) fn write(', 'pub(crate) fn fill(', 'pub(crate) fn w32(', 'pub(crate) fn w64('): + assert 'self.stored(' in item(object_source, store), store + ' must clean firmware-cached GPU-aliased stores' +assert object_source.count('let clean = req.class == Class::FwCoherent && req.lower.is_some();') == 1, 'only FwCoherent work with a lower alias cleans its stores' assert 'pub(crate) struct ComputeUnitSet {' in resources_source, 'resources.rs must split compute units into per-unit ComputeArenas' assert 'ComputeArena::new(factory, bind, vm, live, k, placement)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' assert 'compute_ext: Option>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' From d1e55b93c9a0a4c4f6916d9343b6e1d12173dd01 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 01:00:00 -0500 Subject: [PATCH 7/7] drm/asahi: g16: run SCS compute only beside SCS compute of its VM Ray-query compute on G16G runs with shader-context scratch (SCS). Each compute work item sets the compute engine's SCS state in its register list: a ray-query item enables the SCS window, and every other item writes it disabled. The engine pins ray-query compute to pipe 0 and holds it while compute runs on pipe 1. It still lets another VM's compute, or the same VM's non-SCS compute, queue behind a ray-query item on pipe 0, and lets a ray-query item queue behind such compute. Such an overlapped ray-query dispatch is reported complete before its results reach memory. With a ray-query process and a long-ALU process sharing the GPU, 33,091 to 35,419 of 131,072 rays still held the buffer's fill pattern when the fence signalled, with every Mesa build tried. Once the ray-query process exited, the rest of its stores were written back from the shader cores' L1 cache into its closed VM: fault bank 4: status 0x283a03a1 va 0x5bf27c5180 (write unmapped level 3 unit 0x1 ctx 29) attribution: busy=1 ctx=29 flight_matches=0 live_vm=None flights=9 When those writes filled all eight fault banks, the firmware did not finish the recovery and the GPU stopped. Let SCS compute (ray queries, and every compute command of a job with SCS scratch) share the compute engine only with SCS compute of its own VM. Other compute neither queues behind it nor runs while it is published; each waits for the other to retire. One ray-query queue still pipelines its own commands, and renders are not affected. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 25 ++++- .../drivers/gpu/asahi-m4/test-publication.py | 105 ++++++++++++++---- 2 files changed, 100 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 64467a397408a..b67b6ba5b817d 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -163,6 +163,18 @@ const fn cross_engine_barrier_type(producer_initbm: bool, consumer_initbm: bool) BarrierType::from_stamp_only(!producer_initbm && !consumer_initbm) } +/// Whether a compute command of `vm` that runs shader-context scratch (SCS) work (`scs`), or +/// does not, must wait for compute flight `f` to retire before it is published. +/// +/// SCS compute (ray queries, and every compute command of a job with SCS scratch) shares the +/// compute engine only with SCS compute of its own VM. Each compute work item sets the +/// engine's SCS state in its register list, enabled for SCS work and disabled otherwise. An +/// SCS item that other compute overlaps is reported complete while its stores are still in +/// flight, and they land after its fence has signalled, also after its VM is gone. +fn scs_compute_conflict(f: &Flight, vm: &Arc, scs: bool) -> bool { + f.computes != 0 && (f.rt_compute != scs || (scs && !Arc::ptr_eq(&f.job.vm, vm))) +} + /// Resolved ring-barrier placement for one render pass (legacy, `FRAGMENT_BARRIERS`, or /// `DRM_ASAHI_RENDER_STAGE_PREFIXES`). #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -1308,7 +1320,7 @@ impl Firmware { f.doomed || f.recovery_suspect || f.initbm - || (is_rt_compute && f.computes != 0 && f.compute_pipe != 0) + || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) @@ -1477,13 +1489,14 @@ impl Firmware { .flights .iter() .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); - let rt_pipe1_busy = (job.resources.compute_scs() || c.is_rt()) - && e.flights - .iter() - .any(|f| f.computes != 0 && f.compute_pipe != 0); + let scs = job.resources.compute_scs() || c.is_rt(); + let scs_conflict = e + .flights + .iter() + .any(|f| scs_compute_conflict(f, &job.vm, scs)); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); !cross_vm_render - && !rt_pipe1_busy + && !scs_conflict && !waits_for_timestamps && compute_count < params::compute_flights() && !self.slots.compute_exhausted() diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 8c32b1ff744a3..5cefe344b3090 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -94,8 +94,8 @@ def item(declaration): macro_rules! dev_err {($($argument:tt)*)=>{()};} __PUBLICATION_ERROR__ #[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } -#[derive(Copy,Clone)]struct ComputeCommand { query_access: bool } -impl ComputeCommand { fn is_rt(&self) -> bool { false } } +#[derive(Copy,Clone)]struct ComputeCommand { query_access: bool, rt: bool } +impl ComputeCommand { fn is_rt(&self) -> bool { self.rt } } #[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(()) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} struct Vm { status:Status, slot:u32 } @@ -129,8 +129,9 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,doomed:false,recovery_suspect:false,initbm:false}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false}}} +__SCS_COMPUTE_CONFLICT__ struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} impl Engine { __PICK__ @@ -283,7 +284,7 @@ def item(declaration): Arc::new(Job{id,vm, queue:Queue::new(0,0), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) } fn job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ job_on_vm(id,mk_vm(id),render,sent,dependency) @@ -437,7 +438,7 @@ def item(declaration): id,vm:vm1.clone(), queue:Queue::new(0,priority), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // Head render (prio 2) is blocked behind active render flight; alt-class fallback @@ -556,7 +557,7 @@ def item(declaration): let mk_q=|id:u32,q:Arc,render:bool|Arc::new(Job{ id,vm:vm1.clone(),queue:q, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // q1 has blocked render job 1 followed by compute job 2 on the SAME queue q1; @@ -641,7 +642,7 @@ def item(declaration): let mk=|id:u32,render:bool,query_access:bool,dep:Result|Arc::new(Job{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access,rt:false})}], dependency:dep,terminal_marked:AtomicBool::new(false),resources:Resources, }); // Seed 4 active TA passes so TA wave pacing is active. @@ -788,6 +789,7 @@ def item(declaration): #[derive(Copy, Clone, Debug, PartialEq, Eq)] __RENDER_BARRIER_PLAN__ __PLAN_RENDER_BARRIERS__ + __SCS_COMPUTE_CONFLICT__ impl QueueBehindHost { __NEEDS_ENGINE_DRAIN__ __BLOCKED_ON_SLOT_HEADROOM__ @@ -805,7 +807,7 @@ def item(declaration): let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -843,6 +845,60 @@ def item(declaration): p.slots.compute_available=false; assert!(!p.can_queue_behind(&j2)); } + #[test]fn scs_compute_shares_the_compute_engine_only_with_scs_compute_of_its_vm(){ + // gpubench compute.long: a ray-query lane (vm1) beside a long-ALU lane (vm2). The + // ray-query dispatch was reported complete with its results unwritten whenever the + // other lane's compute ran with it, and its stores then faulted in its closed VM. + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:2}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,0); + let mk=|id:u32,vm:Arc,queue:Arc,rt:bool|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt})], + order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; + let rq=mk(1,vm1.clone(),q1.clone(),true); + let rq_next=mk(2,vm1.clone(),q1.clone(),true); + let rq_post=mk(3,vm1.clone(),q1.clone(),false); + let alu=mk(4,vm2.clone(),q2.clone(),false); + let rq_vm2=mk(5,vm2.clone(),q2.clone(),true); + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![flight(rq.clone(),true,0)]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Behind an SCS flight only SCS compute of its own VM queues, so one ray-query + // queue keeps pipelining. + assert!(p.can_queue_behind(&rq_next)); + assert!(!p.needs_engine_drain(&rq_next)); + for j in [&alu,&rq_post,&rq_vm2] { + assert!(!p.can_queue_behind(j)); + assert!(p.needs_engine_drain(j)); + } + // SCS compute does not start beside non-SCS compute on either pipe. + for pipe in [0u8,1] { + p.engine.flights=vec![flight(alu.clone(),false,pipe)]; + assert!(!p.can_queue_behind(&rq)); + assert!(p.needs_engine_drain(&rq)); + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); + } + // A render flight of its own VM does not hold it; once SCS compute is gone, the rest + // overlaps as before. + let mut render=flight(mk(6,vm1.clone(),q1.clone(),false),false,0); + render.computes=0; + render.renders=1; + p.engine.flights=vec![render]; + assert!(!p.needs_engine_drain(&rq)); + assert!(p.can_queue_behind(&rq)); + p.engine.flights=vec![flight(rq_post.clone(),false,0)]; + assert!(p.can_queue_behind(&alu)); + assert!(!p.needs_engine_drain(&alu)); + } #[test]fn compute_query_access_waits_for_timed_predecessor_unless_no_query_access(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,0); @@ -850,7 +906,7 @@ def item(declaration): let mk=|id:u32,queue:Arc,query_access:bool,wait_vdm:Option,wait_cdm:Option|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access})], + commands:vec![Command::Compute(ComputeCommand{query_access,rt:false})], order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -893,7 +949,7 @@ def item(declaration): let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(),progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -938,7 +994,7 @@ def item(declaration): let q2=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -980,7 +1036,7 @@ def item(declaration): let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1012,7 +1068,7 @@ def item(declaration): let multi_c=Arc::new(QueueBehindJob{ id:6,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false});3], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false});3], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![ Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, @@ -1052,7 +1108,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1094,7 +1150,7 @@ def item(declaration): let c_job=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q_comp.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1131,7 +1187,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1289,7 +1345,7 @@ def item(declaration): let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], }); @@ -1633,7 +1689,7 @@ def item(declaration): let mk=|id:u32,vm:Arc,queue:Arc,seq:u64|Arc::new(QueueBehindJob{ id,vm,queue, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1681,7 +1737,7 @@ def item(declaration): let mk=|id:u32,seq:u64,wait_c:Option|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,wait_c]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1741,7 +1797,7 @@ def item(declaration): let c1=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1755,7 +1811,7 @@ def item(declaration): let c2_wait_q1=Arc::new(QueueBehindJob{ id:3,vm:vm1.clone(),queue:q2.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[Some(1),Some(1)]}], @@ -1763,7 +1819,7 @@ def item(declaration): let c2_query_wait_q1=Arc::new(QueueBehindJob{ id:4,vm:vm1.clone(),queue:q2.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:true})], + commands:vec![Command::Compute(ComputeCommand{query_access:true,rt:false})], order:Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[None,Some(1)]}], @@ -2514,12 +2570,13 @@ def item(declaration): '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', '__WAIT_COMPUTE_STAMPS_FOR__': 'fn wait_compute_stamps_for(', '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', + '__SCS_COMPUTE_CONFLICT__': 'fn scs_compute_conflict(', '__WAIT_TARGET__': 'struct WaitTarget {', '__CROSS_ENGINE_BARRIER_TYPE__': 'const fn cross_engine_barrier_type(', '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): - harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::").replace("super::queue::QueueState", "crate::Queue").replace("super::fence::", "crate::fence::")) + harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::").replace("super::queue::QueueState", "crate::Queue").replace("super::vm::VmState", "crate::Vm").replace("super::fence::", "crate::fence::")) unit = output / 'publication.rs' unit.write_text(harness) log = ''