diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index 62dc0452e781..2f9d086c3efe 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -287,6 +287,7 @@ impl fmt::Display for Identity { /// Identifies the firmware build loaded at `text` (DATA `data_size` bytes) among `builds`, /// before any firmware-visible write. #[cfg_attr(not(CONFIG_DRM_ASAHI_G16), allow(dead_code))] +#[inline(never)] pub(crate) fn identify( dev: &device::Device, text: Range, diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index d885732c0219..3c639f054c4e 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -139,7 +139,8 @@ pub(crate) fn layout(dev: &device::Device) -> Option<&'static hw::FwLayout> { } /// Validates the FDT contract and returns the reserved physical regions, read-only. -pub(crate) fn read(dev: &device::Device) -> Result { +#[inline(never)] +pub(crate) fn read(dev: &device::Device) -> Result> { let node = dev.of_node().ok_or(EINVAL)?; let (version, vas, flags) = handoff(dev)?; let names: KVec = node.get_property(c_str!("memory-region-names"))?; @@ -223,14 +224,17 @@ pub(crate) fn read(dev: &device::Device) -> Result { performance.count ); let [ttbs, tables, handoff, shared_l2, text, data] = regions; - Ok(GpuAdt { - ttbs, - tables, - handoff, - shared_l2, - text, - data, - performance, - layout, - }) + Ok(KBox::init( + init!(GpuAdt { + ttbs, + tables, + handoff, + shared_l2, + text, + data, + performance, + layout, + }), + GFP_KERNEL, + )?) } diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index fdef6c7c908d..353c576b247d 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -462,7 +462,7 @@ impl Rtkit { /// The result of admission: everything probe-time checks established, nothing written. pub(crate) struct Admitted { pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, } /// The running firmware session: RTKit, MMIO and the adopted UAT. (The @@ -472,7 +472,7 @@ pub(crate) struct Session { pub(crate) shared: Arc, pub(crate) rtkit: Rtkit, pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, uat: Arc, /// The PPL handoff page, mapped here only to read the firmware's powered flag /// ([`hw::FwLayout::powered`]); `None` when the firmware keeps the GPU powered. @@ -602,7 +602,7 @@ pub(crate) fn admit( _dev: &AsahiDrmDevice, cfg: &'static Config, res: shared_regs::G16Resources, -) -> Result { +) -> Result> { let dev = pdev.as_ref(); // The board check guards the PMP AGX vote, which only the 25G83 start sends. A firmware // whose handoff names the start without the vote (26B123) rests on the firmware identity @@ -677,7 +677,7 @@ pub(crate) fn admit( return Err(Error::from_errno(-(bindings::EHOSTDOWN as i32))); } dev_info!(dev, "T8132 G16G admitted, ASC={:#x}\n", regs.asc_control()?); - Ok(Admitted { regs, adt }) + Ok(KBox::init(init!(Admitted { regs, adt }), GFP_KERNEL)?) } /// Posts one device control with only the opcode and waits for it. @@ -758,6 +758,7 @@ fn publish_loader_table(session: &Session, init: &InitData, offset: u64) -> Resu } /// Wake the sole firmware instance, publish its loader table, then qualify NOP and policy. +#[inline(never)] fn run( session: &mut Session, events: &mut Events, @@ -900,15 +901,54 @@ fn run( Ok(()) } +/// Retains a failed firmware start out-of-line so [`start`] never reserves an [`Orphan`] slot on +/// its normal stack frame. +#[cold] +#[inline(never)] +fn retain_start_failure( + shared: &Shared, + session: Session, + objects: Objects, + built: Option<(InitData, Channels, u32)>, + events: Events, +) { + let (init, channels) = match built { + Some((init, channels, _)) => (Some(init), Some(channels)), + None => (None, None), + }; + match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => { + let orphan = slot + .write_init(init!(Orphan { + session, + _objects: objects, + channels, + _init: init, + events, + })) + .unwrap_or_else(|e| match e {}); + shared.retain_failed(super::Retained::Orphan(orphan)); + } + Err(_) => { + dev_err!( + shared.dev.as_ref(), + "G16: cannot keep the failed session; leaked\n" + ); + // Without memory for the box, leak the firmware-reachable parts. + core::mem::forget((session, objects, channels, init, events)); + } + } +} + /// Brings the firmware to READY. #[inline(never)] pub(crate) fn start( - admitted: Admitted, + admitted: KBox, dev: &AsahiDrmDevice, cfg: &'static Config, shared: &Arc, -) -> Result { - let Admitted { regs, adt } = admitted; +) -> Result> { + let Admitted { regs, adt } = KBox::into_inner(admitted); let d: ARef = shared.dev.clone(); // Cold ownership must hold before the PMP vote as well as immediately before RUN. if regs.asc_control()? & regs::ASC_RUN != 0 { @@ -1005,6 +1045,13 @@ pub(crate) fn start( return Err(e); } }; + let booted_slot = match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => slot, + Err(e) => { + core::mem::forget(objects); + return Err(e.into()); + } + }; let mut session = Session { dev: d.clone(), shared: shared.clone(), @@ -1074,27 +1121,19 @@ pub(crate) fn start( "G16 start failed: {:?}; session retained until reboot\n", e ); - let (init, channels) = match built { - Some((init, channels, _)) => (Some(init), Some(channels)), - None => (None, None), - }; - shared.orphan(Orphan { - session, - _objects: objects, - channels, - _init: init, - events, - }); + retain_start_failure(shared, session, objects, built, events); return Err(e); } let (init, channels, max_frequency_khz) = built.ok_or(EINVAL)?; - Ok(Booted { - session, - init, - objects, - channels, - events, - id, - max_frequency_khz, - }) + Ok(booted_slot + .write_init(init!(Booted { + session, + init, + objects, + channels, + events, + id, + max_frequency_khz, + })) + .unwrap_or_else(|e| match e {})) } diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 10311e618483..c45d53bc86ea 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 @@ -637,18 +695,16 @@ fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { /// Maximum page-aligned GPUVM spans retained in one logical queue's validation cache. const MAX_PROOF_RANGES: usize = 128; -/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions. -/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never -/// reused across unmaps or remaps. -pub(crate) struct SpanProof { +/// Bounded cache of validated page-aligned GPUVM spans and permissions. +struct ProofCache { epoch: Option, ranges: [(u64, u64, u8); MAX_PROOF_RANGES], count: usize, overflow: bool, } -impl SpanProof { - pub(crate) const fn new() -> Self { +impl ProofCache { + const fn new() -> Self { Self { epoch: None, ranges: [(0, 0, 0); MAX_PROOF_RANGES], @@ -668,7 +724,7 @@ impl SpanProof { }) } - pub(crate) fn invalidate(&mut self) { + fn invalidate(&mut self) { self.epoch = None; self.count = 0; self.overflow = false; @@ -680,13 +736,7 @@ impl SpanProof { .any(|&range| Self::contains(range, req)) } - pub(crate) fn covers_aligned( - &self, - epoch: Option, - first: u64, - size: u64, - access: u8, - ) -> bool { + fn covers_aligned(&self, epoch: Option, first: u64, size: u64, access: u8) -> bool { self.epoch.is_some() && self.epoch == epoch && self.covers_entry((first, size, access)) } @@ -726,7 +776,7 @@ impl SpanProof { self.count += 1; } - pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { if epoch.is_none() { self.invalidate(); return; @@ -761,6 +811,63 @@ impl SpanProof { } } +/// Heap-resident validation scratch paired with [`ProofCache`] so `Prepared::validate` never +/// stages kilobytes of span/command arrays on the kernel stack. +struct ValidateScratch { + batch: SpanBatch, + missing: [(u64, u64, u8); 48], + vdm_vas: [u64; MAX_COMMANDS as usize], + cdm_ranges: [(u64, u64); MAX_COMMANDS as usize], +} + +impl ValidateScratch { + const fn new() -> Self { + Self { + batch: SpanBatch::new(), + missing: [(0, 0, 0); 48], + vdm_vas: [0; MAX_COMMANDS as usize], + cdm_ranges: [(0, 0); MAX_COMMANDS as usize], + } + } +} + +/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions, +/// together with reusable scratch buffers for `Prepared::validate`. +/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never +/// reused across unmaps or remaps. +pub(crate) struct SpanProof { + cache: ProofCache, + scratch: ValidateScratch, +} + +impl SpanProof { + #[allow(dead_code)] + pub(crate) const fn new() -> Self { + Self { + cache: ProofCache::new(), + scratch: ValidateScratch::new(), + } + } + + pub(crate) fn invalidate(&mut self) { + self.cache.invalidate(); + } + + pub(crate) fn covers_aligned( + &self, + epoch: Option, + first: u64, + size: u64, + access: u8, + ) -> bool { + self.cache.covers_aligned(epoch, first, size, access) + } + + pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + self.cache.record_one(epoch, first, size, access); + } +} + /// Batches page-aligned GPUVM coverage checks under one `gpuvm.lock_inner()` hold while /// preserving exact per-span `ENOENT` / `EACCES` / `EINVAL` error reporting on failure. struct SpanBatch { @@ -820,18 +927,26 @@ impl SpanBatch { Self::report_failure(vm, &self.ranges[..n]) } - fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { + fn clear(&mut self) { + self.len = 0; + } + + fn flush_with_proof_parts( + &mut self, + vm: &mmu::Vm, + cache: &mut ProofCache, + missing: &mut [(u64, u64, u8); 48], + ) -> Result { let n = self.len; if n == 0 { return Ok(()); } self.len = 0; let epoch = vm.mapping_validation_epoch(); - if proof.epoch.is_some() && proof.epoch == epoch { - let mut missing = [(0u64, 0u64, 0u8); 48]; + if cache.epoch.is_some() && cache.epoch == epoch { let mut missing_len = 0usize; for &req in &self.ranges[..n] { - if !proof.covers_entry(req) { + if !cache.covers_entry(req) { missing[missing_len] = req; missing_len += 1; } @@ -840,30 +955,35 @@ impl SpanBatch { return Ok(()); } let (mut covered, mut walked) = vm.covers_ranges_batch(&missing[..missing_len]); - if covered && walked != proof.epoch { + if covered && walked != cache.epoch { (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); } if covered { - proof.record_slice(walked, &self.ranges[..n]); + cache.record_slice(walked, &self.ranges[..n]); return Ok(()); } - proof.invalidate(); + cache.invalidate(); return Self::report_failure(vm, &self.ranges[..n]); } let (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); if covered { - proof.record_slice(walked, &self.ranges[..n]); + cache.record_slice(walked, &self.ranges[..n]); return Ok(()); } - proof.invalidate(); + cache.invalidate(); Self::report_failure(vm, &self.ranges[..n]) } - fn flush_locked_with_proof( + #[allow(dead_code)] + fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { + self.flush_with_proof_parts(vm, &mut proof.cache, &mut proof.scratch.missing) + } + + fn flush_locked_with_cache( &mut self, guard: &mut mmu::VmReadGuard<'_>, epoch: Option, - proof: &mut SpanProof, + cache: &mut ProofCache, ) -> Result { let n = self.len; if n == 0 { @@ -872,14 +992,14 @@ impl SpanBatch { self.len = 0; let mut had_miss = false; for &(first, size, access) in &self.ranges[..n] { - if proof.covers_aligned(epoch, first, size, access) { + if cache.covers_aligned(epoch, first, size, access) { continue; } had_miss = true; let read = access & 1 != 0; let write = access & 2 != 0; if !guard.covers_range(first, size, read, write) { - proof.invalidate(); + cache.invalidate(); return if guard.covers_range(first, size, false, false) { Err(EACCES) } else { @@ -888,10 +1008,20 @@ impl SpanBatch { } } if had_miss { - proof.record_slice(epoch, &self.ranges[..n]); + cache.record_slice(epoch, &self.ranges[..n]); } Ok(()) } + + #[allow(dead_code)] + fn flush_locked_with_proof( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: &mut SpanProof, + ) -> Result { + self.flush_locked_with_cache(guard, epoch, &mut proof.cache) + } } /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. @@ -1159,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, @@ -1168,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) @@ -1294,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); @@ -1327,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); @@ -1361,6 +1556,9 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result Result> { + Ok(KBox::init( + init!(Self { + cache <- init!(ProofCache { + epoch: None, + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + count: 0, + overflow: false, + }), + scratch <- init!(ValidateScratch { + batch <- init!(SpanBatch { + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + len: 0, + }), + missing <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + vdm_vas <- ::pin_init::init_array_from_fn(|_| 0), + cdm_ranges <- ::pin_init::init_array_from_fn(|_| (0, 0)), + }), + }), + GFP_KERNEL, + )?) + } +} + impl Prepared { /// Checks each command's spans, programs and stream gates, with a job reference on the VM /// already held so that the checked mappings are retained until the job retires. @@ -1443,42 +1669,51 @@ impl Prepared { proof: &mut SpanProof, ) -> Result { let Prepared { - commands, + mut commands, orders, counts, } = self; if commands.is_empty() { return Err(EINVAL); } - let mut batch = SpanBatch::new(); - let mut vdm_vas = [0u64; MAX_COMMANDS as usize]; let mut vdm_count = 0usize; - let mut cdm_ranges = [(0u64, 0u64); MAX_COMMANDS as usize]; let mut cdm_count = 0usize; - for command in commands.iter() { - match command { - Command::Render(render) => { - check_render( - &mut batch, - context, - &render.cmd, - &render.vertex_attachments, - &render.fragment_attachments, - )?; - if vdm_count >= vdm_vas.len() { - return Err(EINVAL); + { + let scratch = &mut proof.scratch; + scratch.batch.clear(); + for command in commands.iter_mut() { + match command { + Command::Render(render) => { + check_render( + &mut scratch.batch, + context, + &render.cmd, + &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); + } + scratch.vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; + vdm_count += 1; } - vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; - vdm_count += 1; - } - Command::Compute(compute) => { - let range = - check_compute(&mut batch, context, &compute.cmd, &compute.attachments)?; - if cdm_count >= cdm_ranges.len() { - return Err(EINVAL); + Command::Compute(compute) => { + let range = check_compute( + &mut scratch.batch, + context, + &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); + } + scratch.cdm_ranges[cdm_count] = range; + cdm_count += 1; } - cdm_ranges[cdm_count] = range; - cdm_count += 1; } } } @@ -1495,12 +1730,14 @@ impl Prepared { let mut guard = Some(context.vm.read_lock().map_err(|_| EFAULT)?); let mut epoch = guard.as_ref().and_then(|g| g.epoch()); if let Some(g) = guard.as_mut() { - batch.flush_locked_with_proof(g, epoch, proof)?; + let SpanProof { cache, scratch } = proof; + scratch.batch.flush_locked_with_cache(g, epoch, cache)?; if need_vdm { - gate::vdm_batch_locked(g, &vdm_vas[..vdm_count])?; + gate::vdm_batch_locked(g, &scratch.vdm_vas[..vdm_count])?; } } - for &(base, end) in &cdm_ranges[..cdm_count] { + for i in 0..cdm_count { + let (base, end) = proof.scratch.cdm_ranges[i]; gate::cdm_locked( context.vm, &mut guard, @@ -1512,7 +1749,10 @@ impl Prepared { )?; } } else { - batch.flush_with_proof(context.vm, proof)?; + let SpanProof { cache, scratch } = proof; + scratch + .batch + .flush_with_proof_parts(context.vm, cache, &mut scratch.missing)?; } Ok(Submission { counts, diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index 9fdc397dc3cf..5c91c50db288 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 179f39cb4c3b..78c972ac4c9d 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( @@ -360,6 +476,7 @@ pub(crate) fn encode_compute_for( 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() { @@ -412,12 +529,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 0d7f569c9a54..ebf2e03a6826 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); @@ -290,6 +378,7 @@ pub(crate) fn encode_ta_for( 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( @@ -340,8 +429,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 +475,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 +499,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 +547,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 +565,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 +583,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); @@ -534,6 +658,7 @@ pub(crate) fn encode_fs_for( 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/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 6d7286fdd661..64467a397408 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, } } } @@ -407,7 +410,7 @@ enum PublicationError { } /// Engine statistics, printed by `aurora-g16/stats`. -#[derive(Default)] +#[derive(Default, Zeroable)] pub(crate) struct Stats { pub(crate) pub_ns: u64, pub(crate) idle_from_ns: u64, @@ -465,7 +468,7 @@ pub(crate) struct Stats { /// Host-side phase timers of publication and polling, on with `debug_flags` bit 49 /// (`Debug1`); printed as the `prof:` line of `aurora-g16/stats`. A measurement aid: nothing is /// timed while the flag is off. -#[derive(Default)] +#[derive(Default, Zeroable)] pub(crate) struct Prof { /// Published prefixes timed. pub(crate) prefixes: u64, @@ -520,17 +523,21 @@ struct Scratch { } impl Scratch { - fn new() -> Result { + #[inline(never)] + fn new_boxed() -> Result> { let z = |n| KVec::from_elem(0u8, n, GFP_KERNEL); - Ok(Self { - cw: z(work::compute::WORK_SIZE)?, - cq: z(work::compute::SEQ_SIZE)?, - ta: z(work::ta::WORK_SIZE)?, - tas: z(work::ta::SEQ_SIZE)?, - fs: z(work::fs::WORK_SIZE)?, - fss: z(work::fs::SEQ_SIZE)?, - scene: z(work::scene::ACTIVE_SIZE)?, - }) + KBox::try_init( + try_init!(Self { + cw: z(work::compute::WORK_SIZE)?, + cq: z(work::compute::SEQ_SIZE)?, + ta: z(work::ta::WORK_SIZE)?, + tas: z(work::ta::SEQ_SIZE)?, + fs: z(work::fs::WORK_SIZE)?, + fss: z(work::fs::SEQ_SIZE)?, + scene: z(work::scene::ACTIVE_SIZE)?, + }), + GFP_KERNEL, + ) } } @@ -601,6 +608,7 @@ pub(crate) struct Engine { } impl Engine { + #[inline(never)] pub(crate) fn new() -> Result { // Wrapped native stamps are safe only while pending references fit within the // signed half-window: at most FLIGHTS commands are published at once, far inside it. @@ -633,12 +641,12 @@ impl Engine { short_repoll: false, progress_flight: [0; 3], progress: [None; 4], - stats: KBox::new(Stats::default(), GFP_KERNEL)?, - prof: KBox::new(Prof::default(), GFP_KERNEL)?, + stats: KBox::zeroed(GFP_KERNEL)?, + prof: KBox::zeroed(GFP_KERNEL)?, debugfs: None, // Allocate host encoder buffers before any submitted fence can depend on // the device mutex. Publication must never enter direct reclaim here. - scratch: Some(KBox::new(Scratch::new()?, GFP_KERNEL)?), + scratch: Some(Scratch::new_boxed()?), }) } @@ -924,6 +932,7 @@ impl Firmware { } self.engine.pending.push(job.clone(), GFP_NOWAIT)?; job.progress.set_pending(true); + job.origin.mark_enqueued(); let q = &job.queue; let owned = self.engine.queue_published(&job) + self @@ -1105,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(); @@ -1119,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_slots() - .is_ok_and(|n| self.pools.exhausted_for_within(&job.vm, n)) - || 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(); @@ -1288,21 +1300,31 @@ 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)) }) || (is_render && !job .resources - .pb_slots() - .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(n, blocks)| { - self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + .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_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) })) } @@ -1329,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(); @@ -1413,7 +1435,7 @@ impl Firmware { // retirement, so dispatches without DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS must wait // for prior timestamped flights in their dependency prefix to retire first. let waits_for_timestamps = c.query_access - && job.command_order(sent).is_some_and(|o| { + && (job.command_order(sent).is_some_and(|o| { let waits_class = |class: usize| { o.wait_through[class].is_some_and(|last| { e.flights.iter().any(|f| { @@ -1432,21 +1454,44 @@ impl Firmware { }) }; waits_class(super::command::COMPUTE) || waits_class(super::command::RENDER) - }); + }) || job.fw_waits.iter().any(|w| { + (0..2).any(|class| { + w.last_ordinal[class].is_some_and(|last| { + e.flights.iter().any(|f| { + let matches_class = if class == super::command::RENDER { + f.renders != 0 + } else { + f.computes != 0 + }; + matches_class + && f.has_timestamps + && Arc::ptr_eq(&f.job.queue, &w.queue) + && f.job + .command_order(f.first as u32) + .is_none_or(|fo| fo.sequence <= last) + }) + }) + }) + })); let cross_vm_render = e .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() && 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 @@ -1462,10 +1507,16 @@ impl Firmware { && super::recovery::logic::next_ordinal(e.draw).is_some() && job .resources - .pb_slots() - .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(n, blocks)| { - self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + .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_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) }) && job .resources @@ -1476,10 +1527,10 @@ impl Firmware { } } - /// Resolves a same-queue target stamp and producer `InitBM` state for `class` (`RENDER` -> - /// `r_fs_stamp`, `COMPUTE` -> `cstamp`) when `target_seq` names an in-flight command of - /// `job.queue` or an earlier member of an in-progress render batch `current`. Returns - /// `Ok(None)` when no barrier was requested or the waited prefix has already retired. + /// Resolves the newest in-flight target stamp and producer `InitBM` state for `class` + /// (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`) across `job`'s same-queue `target_seq` + /// and any cross-queue `job.fw_waits` (plus an earlier member of an in-progress render batch + /// `current`). Returns `Ok(None)` when no barrier is needed or every waited prefix retired. fn wait_stamp_for_with( &self, job: &Arc, @@ -1487,97 +1538,128 @@ impl Firmware { target_seq: Option, current: Option<&Flight>, ) -> Result> { - let Some(last) = target_seq else { - return Ok(None); - }; - if job.queue.completed[class].load(Ordering::Acquire) >= last { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[class].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[class] else { + continue; + }; + if wait.queue.completed[class].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { return Ok(None); } - if class == super::command::COMPUTE { - for flight in &self.engine.flights { - if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { - continue; - } - let mut member = 0usize; - for k in flight.first..flight.first + flight.count { - if flight.job.command_order(k as u32).is_some_and(|fo| { - fo.engine == super::command::COMPUTE && fo.sequence == last - }) { - return Ok(Some(WaitTarget { - stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, - initbm: flight.initbm, - })); - } - member += 1; - } - for j2 in flight.group.iter() { - for k in 0..j2.progress.count() { - if j2.command_order(k).is_some_and(|fo| { - fo.engine == super::command::COMPUTE && fo.sequence == last - }) { - return Ok(Some(WaitTarget { - stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, - initbm: flight.initbm, - })); - } - member += 1; - } + let mut newest: Option = None; + let scan_flight = |flight: &Flight, + targets: &mut [Option<(&Arc, u64, bool)>], + newest: &mut Option| + -> Result { + if class == super::command::COMPUTE { + if flight.computes == 0 { + return Ok(()); } + } else if flight.renders == 0 { + return Ok(()); } - return Err(EAGAIN); - } - let find_render = |flight: &Flight| -> Option { - if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { - return None; + if !targets + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { + return Ok(()); } - let max_members = (flight.renders as usize).min(flight.r_fs_stamp.len()); + let max_members = if class == super::command::COMPUTE { + (flight.computes as usize).min(flight.cstamp.len()) + } else { + (flight.renders as usize).min(flight.r_fs_stamp.len()) + }; let mut member = 0usize; for k in flight.first..flight.first + flight.count { if member >= max_members { - return None; + break; } - if flight - .job - .command_order(k as u32) - .is_some_and(|fo| fo.engine == super::command::RENDER && fo.sequence == last) - { - return Some(WaitTarget { - stamp: flight.r_fs_stamp[member], - initbm: flight.initbm, - }); + if let Some(fo) = flight.job.command_order(k as u32) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } } member += 1; } for j2 in flight.group.iter() { for k in 0..j2.progress.count() { if member >= max_members { - return None; + break; } - if j2.command_order(k).is_some_and(|fo| { - fo.engine == super::command::RENDER && fo.sequence == last - }) { - return Some(WaitTarget { - stamp: flight.r_fs_stamp[member], - initbm: flight.initbm, - }); + if let Some(fo) = j2.command_order(k) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } } member += 1; } } - None + Ok(()) }; - if let Some(target) = current.and_then(find_render) { - return Ok(Some(target)); - } for flight in &self.engine.flights { - if let Some(target) = find_render(flight) { - return Ok(Some(target)); - } + scan_flight(flight, &mut targets[..count], &mut newest)?; + } + if let Some(cur) = current { + scan_flight(cur, &mut targets[..count], &mut newest)?; } - Err(EAGAIN) + if targets[..count].iter().flatten().any(|(_, _, found)| !*found) { + return Err(EAGAIN); + } + Ok(newest) } - /// Resolves a same-queue target stamp for `class` across published in-flight flights. + /// Resolves a same-queue or cross-queue target stamp for `class` across published flights. fn wait_stamp_for( &self, job: &Arc, @@ -1587,10 +1669,9 @@ impl Firmware { self.wait_stamp_for_with(job, class, target_seq, None) } - /// Resolves a same-queue cross-engine barrier target when `job`'s command `index` waits on - /// an in-flight command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`). - /// Returns `Ok(None)` when no cross-engine barrier was requested or the waited prefix has - /// already retired. + /// Resolves a cross-engine barrier target when `job`'s command `index` waits on an in-flight + /// command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`), including + /// cross-queue `fw_waits`. Returns `Ok(None)` when no barrier is needed or retired. fn cross_engine_wait( &self, job: &Arc, @@ -1603,26 +1684,55 @@ impl Firmware { self.wait_stamp_for(job, other, target_seq) } - /// Resolves the newest in-flight same-queue compute producer on each compute pipe with - /// ordinal `<= target_seq`. Returns `Ok([None; COMPUTE_PIPES])` when no barrier was - /// requested or the entire prefix through `target_seq` has already retired, and `Err(EAGAIN)` - /// if `target_seq` is neither in flight nor retired. + /// Resolves the newest in-flight compute producer on each compute pipe across `job`'s + /// same-queue `target_seq` and any cross-queue `job.fw_waits`. Returns + /// `Ok([None; COMPUTE_PIPES])` when no barrier is needed or every waited prefix retired, + /// and `Err(EAGAIN)` if any unretired target ordinal is missing from `flights`. fn wait_compute_stamps_for( &self, job: &Arc, target_seq: Option, ) -> Result<[Option; sizes::COMPUTE_PIPES]> { - let Some(last) = target_seq else { - return Ok([None; sizes::COMPUTE_PIPES]); - }; - if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[super::command::COMPUTE] else { + continue; + }; + if wait.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { return Ok([None; sizes::COMPUTE_PIPES]); } let mut waits = [None; sizes::COMPUTE_PIPES]; - let mut best_seq = [0u64; sizes::COMPUTE_PIPES]; - let mut found_last = false; for flight in &self.engine.flights { - if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { + if flight.computes == 0 + || !targets[..count] + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { continue; } let pipe = flight.compute_pipe as usize; @@ -1632,12 +1742,17 @@ impl Firmware { let mut member = 0usize; for k in flight.first..flight.first + flight.count { if let Some(fo) = flight.job.command_order(k as u32) { - if fo.engine == super::command::COMPUTE && fo.sequence <= last { - if fo.sequence == last { - found_last = true; + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } } - if fo.sequence >= best_seq[pipe] { - best_seq[pipe] = fo.sequence; + if matched { waits[pipe] = Some(WaitTarget { stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, initbm: flight.initbm, @@ -1650,12 +1765,17 @@ impl Firmware { for j2 in flight.group.iter() { for k in 0..j2.progress.count() { if let Some(fo) = j2.command_order(k) { - if fo.engine == super::command::COMPUTE && fo.sequence <= last { - if fo.sequence == last { - found_last = true; + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } } - if fo.sequence >= best_seq[pipe] { - best_seq[pipe] = fo.sequence; + if matched { waits[pipe] = Some(WaitTarget { stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, initbm: flight.initbm, @@ -1667,15 +1787,18 @@ impl Firmware { } } } - if !found_last && !job.queue.is_compute_retired(last) { - return Err(EAGAIN); + for (q, last, found) in targets[..count].iter().flatten() { + if !*found && !q.is_compute_retired(*last) { + return Err(EAGAIN); + } } Ok(waits) } /// 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 @@ -1683,10 +1806,16 @@ impl Firmware { fn choose_compute_pipe( &self, waits: [Option; sizes::COMPUTE_PIPES], - units: usize, + slot_mask: u32, + rt_compute: bool, ) -> usize { - if units <= super::resources::BASE_COMPUTE_UNITS - || !self.slots.compute_available_for_pipe(units, 1) + if rt_compute + || self + .engine + .flights + .iter() + .any(|fl| fl.computes != 0 && fl.rt_compute) + || !self.slots.compute_available_in_mask_for_pipe(slot_mask, 1) { return 0; } @@ -1694,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]; @@ -1734,14 +1863,18 @@ impl Firmware { let mut a = job .resources .prepare_pb_in_flight(alloc_slot, draw, render_pipelined)?; - let pb_slots = job.resources.pb_slots()?; + 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_within(alloc_slot, &job.vm, pb_slots, 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; @@ -1752,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); @@ -1844,6 +1978,7 @@ impl Firmware { /// producer writes and queue kicks. EAGAIN defers while storage/channel state is held; /// The error records whether firmware may see a counter/producer update, independently /// of errno; unpublished EIO is still an ordinary job failure. + #[inline(never)] fn publish_prefix( &mut self, job: &Arc, @@ -1924,13 +2059,15 @@ 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( 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, slot_mask, rt_compute), waits) }; let pipe_behind = !render && self @@ -2035,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 { @@ -2059,8 +2197,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; }; @@ -2072,6 +2211,9 @@ impl Firmware { let Some(Command::Compute(c2)) = command(job, end) else { break; }; + if c2.is_rt() { + break; + } self.prefix_compute( job, &job.resources, @@ -2089,7 +2231,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() { @@ -2110,6 +2252,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); @@ -2175,7 +2322,10 @@ impl Firmware { }) { return Err(E2BIG); } - let Some(k) = self.slots.pick_pass_in(&job.resources, &geometry, 0) else { + let Some(k) = + self.slots + .pick_pass_in_for(&job.resources, &geometry, 0, Some(job.vm.id)) + else { self.engine.slot_wait = true; return Err(EAGAIN); }; @@ -2232,10 +2382,11 @@ impl Firmware { break; } let geo2 = Geometry::new(&r2.cmd, 0); - let Some(k2) = self.slots.pick_pass_in( + let Some(k2) = self.slots.pick_pass_in_for( &job.resources, &geo2, f.claims.pass_mask, + Some(job.vm.id), ) else { break; }; @@ -2318,6 +2469,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) @@ -2361,10 +2514,11 @@ impl Firmware { break; }; let geo2 = Geometry::new(&r2.cmd, 0); - let Some(slot) = self.slots.pick_pass_in( + let Some(slot) = self.slots.pick_pass_in_for( &job.resources, &geo2, picked_mask, + Some(job.vm.id), ) else { precheck_ok = false; break; @@ -2466,6 +2620,7 @@ impl Firmware { f.pb_slot as usize, &job.vm, job.resources.pb_owner_arena(f.pb_slot as usize), + job.resources.pb_uma_lease(f.pb_slot as usize), )?; } // Reserve lifetime ownership before any counter or producer becomes reachable. @@ -2715,11 +2870,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, @@ -2728,6 +2884,7 @@ impl Firmware { job.vm.slot, n, 1, + &rt, w, image(&mut scratch.cq)?, ) @@ -2801,6 +2958,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)?; @@ -2913,8 +3071,20 @@ impl Firmware { .rev() .find(|fl| fl.renders != 0) .is_some_and(|fl| !Arc::ptr_eq(&fl.job.vm, &job.vm)); + let plan_flags = if !staged + && job.fw_waits.iter().any(|w| { + w.last_ordinal[super::command::RENDER].is_some_and(|last| { + w.queue.completed[super::command::RENDER].load(Ordering::Acquire) < last + }) + }) + { + cmd.cmd.flags + & !kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS + } else { + cmd.cmd.flags + }; let plan = plan_render_barriers( - cmd.cmd.flags, + plan_flags, has_prior_render, params::early_tiling(), prev_fs, @@ -2931,11 +3101,18 @@ impl Firmware { .claim_pass_in(resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; self.slots.hold_render_pass(k, &job.vm, resources)?; let (refs, init_buffer) = if member == 0 { - let pb_slots = resources.pb_slots()?; + let (pb_mask, pb_home) = resources.pb_slot_mask()?; let heap_blocks = resources.pb_heap_blocks()?; let alloc_slot = self .pools - .pick_slot_within_blocks(&job.vm, behind, pb_slots, 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) = @@ -2967,7 +3144,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, @@ -2977,10 +3155,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, @@ -2991,6 +3170,7 @@ impl Firmware { draw, target, &geometry, + &fragment_rt, image(&mut scratch.fs)?, &mut scratch.fss[..], ); @@ -3195,3 +3375,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/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 2890428717f5..75ca2b6768c8 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -12,6 +12,7 @@ //! queue teardown). Fences of one context must signal in order, so a [`Timeline`] holds a //! completed fence back until every earlier fence of the queue has completed. +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use kernel::{ c_str, dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, @@ -21,6 +22,7 @@ use kernel::{ sync::{Arc, LockClassKey, Mutex}, }; +use super::queue::QueueState; use crate::file::SyncItem; /// Inline storage for the common 0-2 input fences, spilling to a heap `KVec` above 2. @@ -119,9 +121,153 @@ pub(crate) fn wait_dependencies(inputs: &[Fence]) -> Result { static TIMELINE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); static ERROR_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); +static JOB_FENCE_OPS: AtomicUsize = AtomicUsize::new(0); + +/// Maximum distinct cross-queue firmware waits carried inline/on-heap by one job. +pub(crate) const MAX_FW_WAITS: usize = 8; + +/// Immutable origin and atomic lifecycle flags attached to every G16 job fence so another +/// logical queue on the same GPU and VM can resolve a binary or timeline semaphore into an +/// in-firmware ring barrier instead of round-tripping through `drm_sched` and CPU retirement. +pub(crate) struct FenceOrigin { + pub(crate) gpu_id: usize, + pub(crate) vm_id: u64, + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + enqueued: AtomicBool, + failed: AtomicBool, +} + +impl FenceOrigin { + pub(crate) fn new( + gpu_id: usize, + vm_id: u64, + queue: Arc, + last_ordinal: [Option; 2], + ) -> Self { + Self { + gpu_id, + vm_id, + queue, + last_ordinal, + enqueued: AtomicBool::new(false), + failed: AtomicBool::new(false), + } + } + + pub(crate) fn mark_enqueued(&self) { + self.enqueued.store(true, Ordering::Release); + } + + pub(crate) fn is_enqueued(&self) -> bool { + self.enqueued.load(Ordering::Acquire) + } + + pub(crate) fn mark_failed(&self) { + self.failed.store(true, Ordering::Release); + } + + pub(crate) fn is_failed(&self) -> bool { + self.failed.load(Ordering::Acquire) + } +} + +/// One per-queue cross-queue firmware barrier target, coalescing multiple fences from the same +/// logical queue (e.g. from a timeline semaphore chain or repeated input syncs) to the highest +/// required render and compute ordinals on that queue. +pub(crate) struct FwWait { + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + origin: Arc, +} + +impl FwWait { + pub(crate) fn is_failed(&self) -> bool { + self.origin.is_failed() + } +} + +/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 queues, bounded to +/// [`MAX_FW_WAITS`] distinct logical queues). +pub(crate) enum FwWaits { + Empty, + One([FwWait; 1]), + Heap(KVec), +} + +impl FwWaits { + fn push_unique(&mut self, origin: Arc) -> Result { + let existing = match self { + Self::Empty => None, + Self::One(items) => items + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + Self::Heap(vec) => vec + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + }; + if let Some(wait) = existing { + let mut newer = false; + for engine in 0..2 { + if let Some(seq) = origin.last_ordinal[engine] { + match wait.last_ordinal[engine] { + Some(cur) if seq > cur => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + None => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + _ => {} + } + } + } + if newer { + wait.origin = origin; + } + return Ok(()); + } + if self.len() >= MAX_FW_WAITS { + return Err(E2BIG); + } + let wait = FwWait { + queue: origin.queue.clone(), + last_ordinal: origin.last_ordinal, + origin, + }; + match self { + Self::Empty => *self = Self::One([wait]), + Self::One(_) => { + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::One([first]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(first); + let _ = vec.push_within_capacity(wait); + } + *self = Self::Heap(vec); + } + Self::Heap(vec) => vec.push(wait, GFP_KERNEL)?, + } + Ok(()) + } +} + +impl core::ops::Deref for FwWaits { + type Target = [FwWait]; + + fn deref(&self) -> &[FwWait] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Heap(vec) => vec, + } + } +} /// Fence operations of G16 job fences. -pub(crate) struct JobFenceOps; +pub(crate) struct JobFenceOps { + origin: Arc, +} #[vtable] impl FenceOps for JobFenceOps { @@ -134,6 +280,85 @@ impl FenceOps for JobFenceOps { } } +/// Fence operations of pre-signalled refused-submission fences (distinct vtable from +/// [`JobFenceOps`] so refused error fences never match [`origin_from_raw`]). +struct RefusedFenceOps; + +#[vtable] +impl FenceOps for RefusedFenceOps { + fn get_driver_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("aurora") + } + + fn get_timeline_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("g16-refused") + } +} + +/// Resolves a G16 [`FenceOrigin`] from a raw `dma_fence` pointer if and only if its vtable +/// pointer matches the registered [`JobFenceOps`] vtable. +/// +/// # Safety +/// +/// `raw` must be null or point to a live, initialized `dma_fence` whose reference is held for +/// the duration of this call. +unsafe fn origin_from_raw(raw: *mut kernel::bindings::dma_fence) -> Option> { + let expected = JOB_FENCE_OPS.load(Ordering::Acquire); + if expected == 0 || raw.is_null() { + return None; + } + // SAFETY: Caller retains a live dma_fence reference. `JobFenceOps` has a distinct timeline + // name and nontrivial payload drop (`Arc`). No cast precedes the exact + // registered vtable check, and `FenceObject` begins with its `dma_fence`. + let object = unsafe { + if (*raw).ops as usize != expected { + return None; + } + &*(raw as *const FenceObject) + }; + Some(object.origin.clone()) +} + +/// Resolves `inputs` into same-GPU, same-VM in-firmware cross-queue waits outside the device +/// lock. Returns `None` if any leaf is failed, foreign, cross-VM, not yet enqueued, or exceeds +/// [`MAX_FW_WAITS`], leaving the caller to retain normal `drm_sched` / `InputFences` waits. +pub(crate) fn resolve_fw_waits(inputs: &[Fence], gpu_id: usize, vm_id: u64) -> Option { + if inputs.is_empty() { + return Some(FwWaits::Empty); + } + let mut waits = FwWaits::Empty; + for input in inputs { + let status = dependency_status(input); + if status < 0 { + return None; + } + if status > 0 { + continue; + } + let leaves = crate::g17::sync_input::collect_coalesced(input)?; + for leaf in leaves.iter() { + if leaf.status < 0 { + return None; + } + if leaf.status > 0 { + continue; + } + // SAFETY: `leaf` retains an owned reference to `leaf.fence` until dropped. + let origin = unsafe { origin_from_raw(leaf.fence) }?; + if origin.gpu_id != gpu_id + || origin.vm_id != vm_id + || !origin.is_enqueued() + || origin.is_failed() + || origin.last_ordinal == [None, None] + { + return None; + } + waits.push_unique(origin).ok()?; + } + } + Some(waits) +} + /// Stack batch size for signalling completed fences outside `Timeline::pending`. const SIGNAL_BATCH: usize = 8; @@ -192,11 +417,23 @@ impl Timeline { /// Creates the fence of the next accepted job. Fences are created in submission order: the /// caller holds the queue (SUBMIT is serialized per queue). - pub(crate) fn next(self: &Arc) -> Result { + pub(crate) fn next(self: &Arc, origin: Arc) -> Result { // SUBMIT already holds the logical queue, so allocating the next sequence before // taking pending preserves creation order. Fence completion needs pending too: // never enter reclaim while holding that mutex. - let fence: UserFence = self.jobs.new_fence(0, JobFenceOps)?.into(); + let fence: UserFence = self.jobs.new_fence(0, JobFenceOps { origin })?.into(); + // SAFETY: `fence` is a live `UserFence` whose `dma_fence::ops` is static. + let ops = unsafe { (*fence.raw()).ops as usize }; + let previous = JOB_FENCE_OPS.load(Ordering::Acquire); + if previous == 0 { + match JOB_FENCE_OPS.compare_exchange(0, ops, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => {} + Err(existing) if existing == ops => {} + Err(_) => return Err(EIO), + } + } else if previous != ops { + return Err(EIO); + } let mut pending = self.pending.lock(); pending.reserve(1, GFP_NOWAIT)?; pending @@ -276,7 +513,7 @@ impl Timeline { /// A fence on `contexts` signalled with `error`. Every fence of an error context signals at /// creation, so the context's fences signal in order. fn error_fence(contexts: &FenceContexts, error: Error) -> Result { - let fence = contexts.new_fence(0, JobFenceOps)?; + let fence = contexts.new_fence(0, RefusedFenceOps)?; fence.set_error(error); fence.signal(); Ok(Fence::from_fence(&fence)) diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index 07317ee4663d..e0a7b43b677b 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 e3c95e275672..80279283a4da 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 0341c5f6116d..5b1220b301e3 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; @@ -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; @@ -112,7 +115,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 +133,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; @@ -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; @@ -179,7 +185,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 0bde4d35e886..85daf5876aec 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). @@ -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]; @@ -89,7 +94,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/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 4514454acbe1..f23f4936ab3a 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -278,6 +278,7 @@ pub(crate) struct Graphs { pub(crate) render: RenderGraph, } impl Graphs { + #[inline(never)] pub(crate) fn new(dev: &AsahiDrmDevice, o: &mut Objects) -> Result { // Host polls sched_ctx from WC during register_context(); keep uncached and share one // scheduling context across all compute pipes and the render graph. @@ -295,6 +296,7 @@ impl Graphs { } } impl Firmware { + #[inline(never)] pub(crate) fn init_graphs(&mut self) -> Result { for ch in [Channel::Ta, Channel::Fs, Channel::Compute] { if self.channels.read(ch)? != 0 || self.channels.write_cell(ch)? != 0 { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index a9c5cad5814d..d556b290062e 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,10 +606,23 @@ 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. Slots 0..4 live in 0x7010000000..0x7020000000; slots 4..PB_SLOTS - // live in 0x7008000000..0x7010000000, above base compute units 0..2 (ending at - // 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). + // 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 + // (ending at 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). pub(crate) const fn render_base(k: u64) -> u64 { if k < 4 { 0x7010000000 + k * 0x04000000 @@ -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 { @@ -714,11 +750,23 @@ pub(crate) mod sizes { pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; /// Base physical PB/UMA allocator slots allocated per VM on first render. pub(crate) const BASE_PB_SLOTS: usize = 2; - /// Physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware UMA slot 33). - /// Base slots `0..BASE_PB_SLOTS` serve normal cross-VM switching; extra slots are allocated - /// lazily per VM only after a render hang permanently quarantines an allocator slot. - pub(crate) const PB_SLOTS: usize = 6; - const _: () = assert!(PB_SLOTS >= BASE_PB_SLOTS && PB_SLOTS <= 6); + /// Device-wide warm physical PB/UMA allocator slots (`parameter_id` `0..WARM_PB_SLOTS`, + /// hardware UMA slots `33..33 + WARM_PB_SLOTS`). Each VM maps two base units (`local_idx` + /// `0..BASE_PB_SLOTS`) bound to a rotating `[home, alt]` pair in this pool so up to + /// `WARM_PB_SLOTS` concurrent render VMs stay warm without extra per-VM memory. + pub(crate) const WARM_PB_SLOTS: usize = 16; + /// Lazily allocated recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`, mapped at + /// per-VM local VA indices `BASE_PB_SLOTS..MAX_VM_PB_SLOTS`) claimed only after a render + /// hang permanently quarantines an allocator slot. + pub(crate) const EXT_PB_SLOTS: usize = 4; + /// Maximum PB/UMA allocator slots mapped in one VM's client VA space (`render_base(0..6)`). + pub(crate) const MAX_VM_PB_SLOTS: usize = BASE_PB_SLOTS + EXT_PB_SLOTS; + /// Total device-wide physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware + /// UMA slots `RENDER_UMA_SLOT..RENDER_UMA_SLOT + PB_SLOTS`). + pub(crate) const PB_SLOTS: usize = WARM_PB_SLOTS + EXT_PB_SLOTS; + const _: () = assert!(WARM_PB_SLOTS >= BASE_PB_SLOTS); + const _: () = assert!(MAX_VM_PB_SLOTS >= BASE_PB_SLOTS && MAX_VM_PB_SLOTS <= 6); + const _: () = assert!(PB_SLOTS <= 32); const _: () = assert!(super::client::compute_context(1) + 0x40000 <= super::client::render_base(4)); const _: () = @@ -799,6 +847,53 @@ pub(crate) mod sizes { super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) <= super::engine::RENDER_UMA_SLOT ); + /// 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!( + 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/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index 01861b790a62..e4898529be5c 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -93,6 +93,7 @@ fn pair(graph: &[Arc], state: usize, ring: usize) -> Ring { /// Builds the complete unpublished M4 graph. The return shape is shared with /// the other backend, while all object layouts and policy are M4-specific. +#[inline(never)] pub(crate) fn build( dev: &device::Device, adt: &GpuAdt, diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 6547895cceef..a5dbc19b7d3e 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -45,7 +45,7 @@ use kernel::{ use super::{ command::{Command, Commands, Order, Orders}, - fence::{InputFences, JobFence}, + fence::{FenceOrigin, FwWaits, InputFences, JobFence}, hw, queue::QueueState, vm::VmState, @@ -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, @@ -107,6 +109,10 @@ pub(crate) struct Job { pub(crate) progress: super::engine::Progress, /// Inputs and resolved historical-prefix dependencies, held through every command. inputs: InputFences, + /// Exported fence identity for same-GPU, same-VM cross-queue firmware handoff. + pub(crate) origin: Arc, + /// Same-GPU, same-VM cross-queue waits resolved into firmware ring barriers. + pub(crate) fw_waits: FwWaits, /// Bitmask of commands (`0..MAX_COMMANDS`) with full owner-retirement proof; an aborted /// receipt never sets its bit. Tracks per-command bits so concurrent compute/render /// commands within one job may retire in either hardware completion order. @@ -141,10 +147,13 @@ impl Job { fence: JobFence, guard: mmu::VmJobGuard, inputs: InputFences, + origin: Arc, + fw_waits: FwWaits, ) -> Result> { 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, @@ -156,11 +165,14 @@ impl Job { queue, vm, commands, + long, orders, resources, fence, progress, inputs, + origin, + fw_waits, full_retired: AtomicU64::new(0), terminal_retired: AtomicBool::new(false), // Scheduler free can race the final off-lock completion reference. @@ -175,9 +187,16 @@ 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) { + self.origin.mark_failed(); if error == ECANCELED || (self.terminal_retired.load(Ordering::Acquire) && error != EIO @@ -217,6 +236,7 @@ impl Job { return; } if let Err(error) = result { + self.origin.mark_failed(); if error == ECANCELED || ((!engine || self.terminal_retired.load(Ordering::Acquire)) && error != EIO @@ -321,7 +341,10 @@ impl Job { /// Whether command `index` is a ready, barrier-free compute command continuing a compute /// horizon at queue-local compute ordinal `expected`. pub(crate) fn can_fold_horizon_cmd(&self, index: u32, expected: u64) -> bool { - if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { return false; } let Some(Command::Compute(_)) = self.commands.get(index as usize) else { @@ -342,6 +365,7 @@ impl Job { pub(crate) fn can_fold_horizon_job(&self, first_expected: u64) -> bool { let count = self.progress.count(); if count == 0 + || !self.fw_waits.is_empty() || self.progress.sent() != 0 || self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 @@ -374,7 +398,10 @@ impl Job { /// at queue-local render ordinal `expected` (treating `expected - 1` as already published /// within the in-progress render flight). pub(crate) fn can_fold_render_cmd(&self, index: u32, expected: u64) -> bool { - if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { return false; } let Some(Command::Render(_)) = self.commands.get(index as usize) else { @@ -411,6 +438,7 @@ impl Job { pub(crate) fn can_fold_render_horizon_job(&self, first_expected: u64) -> bool { let count = self.progress.count(); if count == 0 + || !self.fw_waits.is_empty() || self.progress.sent() != 0 || self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 @@ -471,6 +499,19 @@ impl Job { let order = self.orders.get(index as usize).ok_or(EINVAL)?; self.queue.check(order)?; super::fence::check_dependencies(&self.inputs)?; + for wait in self.fw_waits.iter() { + if wait.is_failed() { + return Err(ECANCELED); + } + for engine in 0..2 { + if let Some(seq) = wait.last_ordinal[engine] { + wait.queue.cancelled_through(engine, seq)?; + if wait.queue.published[engine].load(Ordering::Acquire) < seq { + return Err(EAGAIN); + } + } + } + } let completed = self .queue .completed @@ -599,6 +640,11 @@ impl Job { Ok(()) } + /// Whether this job holds a cross-queue firmware wait on `queue`. + pub(crate) fn waits_on_queue(&self, queue: &Arc) -> bool { + self.fw_waits.iter().any(|w| Arc::ptr_eq(&w.queue, queue)) + } + /// Cancels a job the scheduler never ran (queue teardown, or a failed submission). fn cancel_unstarted(&self) { if self.started.swap(true, Ordering::AcqRel) { @@ -608,6 +654,7 @@ impl Job { self.finish(Err(ECANCELED), false); } else if !self.progress.signaled.swap(true, Ordering::AcqRel) { // A refused submission's job: its fence orders nothing and was never published. + self.origin.mark_failed(); self.fence.signal(Err(ECANCELED)); } } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 670a85634528..2dedd2d48c3b 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; @@ -206,6 +207,33 @@ const WAIT_HINT_GAP_NS: u64 = 4_000_000; const WAIT_HINT_STREAK_ON: u32 = 8; const WAIT_HINT_LINGER_NS: u64 = 8_000_000; +/// A firmware session retained until reboot after a failed boot or backend start. +pub(crate) enum Retained { + Orphan(KBox), + Booted(KBox), + Firmware(KBox), +} + +impl Retained { + fn drain(&mut self) -> Result { + match self { + Self::Orphan(orphan) => orphan.drain(), + Self::Booted(booted) => { + let booted = &mut **booted; + booted + .channels + .drain_rings(&booted.session.dev, &mut booted.events) + } + Self::Firmware(firmware) => { + let firmware = &mut **firmware; + firmware + .channels + .drain_rings(&firmware.session.dev, &mut firmware.events) + } + } + } +} + /// Device state shared with the RTKit callbacks and the poll work. #[pin_data] pub(crate) struct Shared { @@ -223,6 +251,9 @@ pub(crate) struct Shared { /// Set by external state changes (VM teardown, unstarted queue cancellation) so the next /// `poll_step()` re-evaluates `publish_checked()` even while unrelated flights are active. pub(crate) publish_wake: AtomicBool, + /// Set on VM close (and re-armed while any non-quarantined slot still holds a closed VM) + /// so displaced closed-VM slot leases are reclaimed without scanning on the hot path. + pub(crate) closed_vm_reclaim: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, /// CPU whose cluster currently restricts `events_unbound` (`u32::MAX` before first pin). @@ -263,10 +294,16 @@ 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, - /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. - pub(crate) needed_pb_slots: AtomicU32, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: AtomicU32, + /// Round-robin cursor assigning each rendering VM a `[home, alt]` pair in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: AtomicU32, + /// Live open VMs that own a `RenderArena`, used to size multi-VM pass-slot headroom. + pub(crate) active_render_vms: Arc, /// The GFX power state word from before a system sleep. sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. @@ -282,7 +319,7 @@ pub(crate) struct Shared { /// Dedicated unbound workqueue for cpufreq `FREQ_QOS_MIN` updates outside `Shared::state`. pub(crate) feed_wq: OwnedQueue, #[pin] - pub(crate) orphan: Mutex>>, + pub(crate) orphan: Mutex>, #[pin] pub(crate) poll: DelayedWork, #[pin] @@ -290,7 +327,7 @@ pub(crate) struct Shared { #[pin] pub(crate) fast_poll_unbound: Work, #[pin] - pub(crate) scrub_queue: SpinLock, + pub(crate) scrub_queue: SpinLock>, #[pin] pub(crate) scrub_work: Work, #[pin] @@ -499,36 +536,26 @@ impl Shared { /// Keeps a firmware session that did not complete until reboot; its receive rings stay /// drained by the poll work. - pub(crate) fn orphan(&self, orphan: boot::Orphan) { + #[cold] + #[inline(never)] + pub(crate) fn retain_failed(&self, retained: Retained) { let mut slot = self.orphan.lock(); if slot.is_some() { // Never replace and drop an already firmware-reachable session. - core::mem::forget(orphan); + core::mem::forget(retained); dev_err!( self.dev.as_ref(), "G16: additional failed session retained without drain\n" ); return; } - match KBox::::new_uninit(GFP_KERNEL) { - Ok(storage) => { - *slot = Some(KBox::write(storage, orphan)); - self.orphaned.store(true, Ordering::Release); - } - // Without memory for the box, leak the parts as they are. - Err(_) => { - core::mem::forget(orphan); - dev_err!( - self.dev.as_ref(), - "G16: cannot keep the failed session; leaked\n" - ); - } - } + *slot = Some(retained); + self.orphaned.store(true, Ordering::Release); } /// Drains the receive rings of an orphaned session. fn drain_orphan(&self) { - if let Some(orphan) = self.orphan.lock().as_deref_mut() { + if let Some(orphan) = &mut *self.orphan.lock() { let _ = orphan.drain(); } } @@ -562,7 +589,7 @@ pub(crate) struct Firmware { /// PMP thermal vote and firmware DVFS ceiling state. pub(crate) power: power::Power, /// Render UMA/PB allocators, their spare set and parameter-buffer growth. - pub(crate) pools: pools::Pools, + pub(crate) pools: KBox, /// Live VMs and their exclusive TTBAT slots, and the client aliases of every user VM. pub(crate) vms: Arc, /// Monotonic timestamp (ns) of the last full housekeeping pass (power, health, hang poll). @@ -591,6 +618,7 @@ impl Gpu { /// Admits and boots a G16 GPU: identity checks, PMP AGX vote, RTKit, UAT handoff, initdata, /// READY, then the compute and render graphs. On success the module is pinned: the /// firmware session lasts until reboot. + #[inline(never)] pub(crate) fn new( pdev: &platform::Device>, dev: &AsahiDrmDevice, @@ -610,6 +638,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 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(), @@ -619,6 +649,7 @@ impl Gpu { crashed: AtomicBool::new(false), evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), unbound_cluster_cpu: AtomicU32::new(u32::MAX), unbound_pinning: AtomicBool::new(false), @@ -637,8 +668,11 @@ 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), - needed_pb_slots: AtomicU32::new(hw::sizes::BASE_PB_SLOTS as u32), + quarantined_pb_mask: AtomicU32::new(0), + next_pb_slot: AtomicU32::new(0), + active_render_vms, sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, @@ -650,7 +684,7 @@ impl Gpu { poll <- new_delayed_work!("g16::Shared::poll"), fast_poll <- new_work!("g16::Shared::fast_poll"), fast_poll_unbound <- new_work!("g16::Shared::fast_poll_unbound"), - scrub_queue <- new_spinlock!(slots::ScrubQueue::new(), "g16::Shared::scrub_queue"), + scrub_queue <- new_spinlock!(scrub_queue, "g16::Shared::scrub_queue"), scrub_work <- new_work!("g16::Shared::scrub_work"), feed_work <- new_work!("g16::Shared::feed_work"), resnap <- HrTimer::new(), @@ -705,63 +739,51 @@ impl Firmware { #[inline(never)] fn start_backend( dev: &AsahiDrmDevice, - booted: boot::Booted, + mut booted: KBox, shared: &Arc, mut power: power::Power, ) -> Result> { - let boot::Booted { - session, - init, - mut objects, - channels, - events, - .. - } = booted; dev_info!( dev.as_ref(), "G16: firmware at READY, starting the backend\n" ); - power.set_table(init.rows); - let orphan = |session: boot::Session, - objects: object::Objects, - channels: channel::Channels, - init: initdata::InitData, - events: event::Events, - error: Error| - -> Error { - dev_err!( - dev.as_ref(), - "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", - error - ); - shared.orphan(boot::Orphan { - session, - _objects: objects, - channels: Some(channels), - _init: Some(init), - events, - }); - error - }; + power.set_table(booted.init.rows); let backend = (|| -> Result<_> { - let graph = graph::Graphs::new(dev, &mut objects)?; + let graph = graph::Graphs::new(dev, &mut booted.objects)?; let slots = slots::Slots::new()?; - let pools = pools::Pools::new(dev); + 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(e) => return Err(orphan(session, objects, channels, init, events, e)), + Err(error) => { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Booted(booted)); + return Err(error); + } }; - let mut firmware = KBox::write( - slot, - Firmware { + let boot::Booted { + session, + init, + mut objects, + channels, + events, + .. + } = KBox::into_inner(booted); + let private_factory = objects.private_factory(render_cmds); + let mut firmware = slot + .write_init(init!(Firmware { session, init, - private_factory: objects.private_factory(), + private_factory, objects, channels, events, @@ -774,18 +796,16 @@ impl Firmware { vms, last_housekeeping_ns: 0, last_aux_drain_ns: 0, - }, - ); - if let Err(e) = firmware.init_graphs() { - let Firmware { - session, - init, - objects, - channels, - events, - .. - } = KBox::into_inner(firmware); - return Err(orphan(session, objects, channels, init, events, e)); + })) + .unwrap_or_else(|e| match e {}); + if let Err(error) = firmware.init_graphs() { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Firmware(firmware)); + return Err(error); } Ok(firmware) } @@ -882,6 +902,7 @@ impl gpu::Gpu for Gpu { } fn vm_closed(&self, vm: &mmu::Vm) { self.vms.close(vm.id()); + self.shared.closed_vm_reclaim.store(true, Ordering::Release); self.shared.wake_publish(); } diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 767df69e03f3..c4c42d1dd129 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -46,6 +46,15 @@ pub(crate) enum Class { Shared, /// Firmware and GPU, ASC-cached. SharedCached, + /// 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. 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)] Mmio, @@ -59,6 +68,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, } } @@ -100,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 @@ -148,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(()) } @@ -167,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(()) } @@ -176,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()) @@ -188,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()) @@ -296,11 +322,28 @@ pub(crate) struct Request { /// Private allocation coordinates. Only normal non-cacheable objects may be reclaimed. struct Private { - vm: mmu::Vm, + vm: Option, firmware: core::ops::Range, pending: Option>, } +/// VM-independent firmware-object lease whose backing and firmware/lower mappings stay alive +/// until a later command overwrites the same hardware table slot in firmware RAM. +/// +/// Dropping an `Arc` offloads unmap to `cleanup::Deferred`, so replacing a lease under +/// `Shared::state` never sleeps or blocks fence producers. +pub(crate) struct FwLease(crate::cleanup::Deferred); + +impl FwLease { + pub(crate) fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(objects)?), + GFP_KERNEL, + )?) + } +} + /// Immutable factory shared by ioctl-side private arena construction. #[derive(Clone)] pub(crate) struct Factory { @@ -308,6 +351,7 @@ pub(crate) struct Factory { uat: Arc, window: Arc>, firmware: core::ops::Range, + render_cmds: Arc, } impl Factory { @@ -317,11 +361,58 @@ impl Factory { uat: self.uat.clone(), window: self.window.clone(), private: Some(Private { - vm: vm.clone(), + vm: Some(vm.clone()), + firmware: self.firmware.clone(), + pending: None, + }), + sealed: false, + persistent: false, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + pages: 0, + } + } + + /// Allocates firmware-only and context-0 lower-alias objects with no client VM binding. + pub(crate) fn fw_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: false, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + 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(), @@ -330,6 +421,12 @@ impl Factory { pages: 0, } } + + /// 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) + } } /// The firmware object allocator and the set of retained objects. @@ -340,6 +437,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. @@ -368,6 +467,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(), @@ -378,19 +478,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) } @@ -406,7 +511,7 @@ impl Objects { lower: None, cpu: true, }, - Some(0x7040000000..0x7080000000), + Some(hw::client::DYNAMIC), ) } @@ -416,7 +521,9 @@ 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() || client_range.is_some())) || req.size == 0 || req.offset >= hw::PAGE as usize { @@ -431,15 +538,27 @@ 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 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 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) }; + if clean { + crate::pgtable::clean_poc(pointer.as_ptr(), bytes); + crate::pgtable::poc_barrier(); + } Some(pointer) } else { None @@ -473,7 +592,8 @@ impl Objects { None }; let client_gva = if let Some(range) = client_range { - let mapping = private.vm.map_in_range( + let vm = private.vm.as_ref().ok_or(EINVAL)?; + let mapping = vm.map_in_range( &backing.gem, 0..bytes, hw::PAGE, @@ -485,6 +605,7 @@ impl Objects { self.mappings.push(mapping, GFP_KERNEL)?; Some(address) } else if let Some((gva, leaf)) = req.client { + let vm = private.vm.as_ref().ok_or(EINVAL)?; let end = gva.checked_add(bytes as u64).ok_or(EOVERFLOW)?; if gva < hw::client::CLIENT_APERTURE.start || end > hw::client::CLIENT_APERTURE.end @@ -494,9 +615,7 @@ impl Objects { return Err(EINVAL); } self.mappings.push( - private - .vm - .map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, + vm.map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, GFP_KERNEL, )?; Some(gva) @@ -523,6 +642,7 @@ impl Objects { backing, _parent: None, limit: None, + clean, }, GFP_KERNEL, )?; @@ -581,6 +701,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); } @@ -674,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/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index ed93d1fd6469..434faf2ee2a0 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/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 61567df95f16..2fca6c71513e 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -272,6 +272,9 @@ impl Shared { }); } if pub_res.is_ok() { + if retired_any || !had_flights { + firmware.reclaim_closed_vm_slots(); + } pub_res = if recovery_pending { let r = firmware.publish(done); if r.is_ok() { @@ -579,6 +582,27 @@ pub(crate) fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { } impl Firmware { + /// Reclaims displaced slot leases belonging to closed VMs so dead processes do not keep + /// multi-hundred-MiB render/compute arenas and TTBAT ASIDs pinned while idle. + /// + /// Respects all hardware displacement contracts (active, in-flight, undisplaced, scrubbing, + /// and quarantined slots are preserved) and re-arms `Shared::closed_vm_reclaim` whenever a + /// non-quarantined slot still holds a closed VM awaiting retirement, displacement, or scrub. + pub(crate) fn reclaim_closed_vm_slots(&mut self) { + let Some(shared) = self.engine.shared.as_ref() else { + return; + }; + if !shared.closed_vm_reclaim.load(Ordering::Acquire) + || !shared.closed_vm_reclaim.swap(false, Ordering::AcqRel) + { + return; + } + let remaining = self.pools.reclaim_closed() | self.slots.reclaim_closed(); + if remaining { + shared.closed_vm_reclaim.store(true, Ordering::Release); + } + } + /// One non-sleeping poll step under the device lock. /// /// Retires finished flights and publishes ready work before periodic 1 ms housekeeping so @@ -622,7 +646,12 @@ impl Firmware { self.last_aux_drain_ns = now; ran_housekeeping = true; self.drain_rings()?; + self.reclaim_closed_vm_slots(); if self.recovery_idle()? && self.engine.pending.is_empty() { + let _ = self.slots.take_scrub_woke(); + if let Some(shared) = self.engine.shared.as_ref() { + shared.publish_wake.store(false, Ordering::Release); + } return Ok(false); } } @@ -645,6 +674,9 @@ impl Firmware { .shared .as_ref() .is_some_and(|shared| shared.publish_wake.swap(false, Ordering::AcqRel)); + if retired_any || publish_woke || scrub_woke || housekeeping_due { + self.reclaim_closed_vm_slots(); + } // Skip redundant `publish_checked()` walks on busy polls where nothing could have // unblocked `engine.pending`. `Prepared::drop` releases standby PB epochs only for // `Cache::prepare` waiters (`standby_available`, which enter `submit_locked()` directly), @@ -750,6 +782,7 @@ impl Firmware { self.last_aux_drain_ns = now; } self.last_housekeeping_ns = now; + self.reclaim_closed_vm_slots(); if !self.engine.flights.is_empty() || recovery_pending { self.check_hangs(done)?; } @@ -1346,18 +1379,22 @@ 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); shared - .needed_pb_slots - .store(self.pools.needed_slots() as u32, Ordering::Release); + .quarantined_pb_mask + .store(self.pools.quarantined_mask(), Ordering::Release); } } /// Retire the flight at `index` (the oldest of its engine class). Only a full normal receipt /// retires its storage; a passed abort quarantines it. Job failure independently drops /// remaining unpublished commands even when the storage fully retired. + #[inline(never)] pub(crate) fn retire_oldest( &mut self, index: usize, @@ -1538,11 +1575,34 @@ impl Firmware { let p = &job.progress; p.next.store(p.next() + f.count as u32, Ordering::Relaxed); if result.is_err() { - // Its queue's later commands queued behind it fail with it, as unpublished ones - // are cancelled: they never report a successful receipt after this hole. + // Later commands of this queue, and any cross-queue flights transitively waiting + // on it via firmware handoff, fail with it so no dependent command reports success + // after an upstream failure. + let mut changed = false; for later in self.engine.flights.iter_mut() { - if Arc::ptr_eq(&later.job.queue, &job.queue) { + if !later.doomed + && (Arc::ptr_eq(&later.job.queue, &job.queue) + || later.job.waits_on_queue(&job.queue)) + { later.doomed = true; + changed = true; + } + } + while changed { + changed = false; + for i in 0..self.engine.flights.len() { + if self.engine.flights[i].doomed { + continue; + } + let dep_doomed = self.engine.flights.iter().any(|other| { + other.doomed + && (Arc::ptr_eq(&other.job.queue, &self.engine.flights[i].job.queue) + || self.engine.flights[i].job.waits_on_queue(&other.job.queue)) + }); + if dep_doomed { + self.engine.flights[i].doomed = true; + changed = true; + } } } } diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index c18608606429..c08da53d7fac 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, 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::{ @@ -57,6 +58,9 @@ pub(crate) struct Allocator { list: Arc, submitted: Arc, heap: Arc, + /// VM-free firmware lease retaining `descriptor` and `submitted` across closed-VM reclaim + /// until a later render overwrites this hardware UMA slot in firmware RAM. + uma_lease: Arc, published: AtomicBool, id: u32, } @@ -80,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( @@ -92,7 +98,7 @@ fn alloc( o.alloc(Request { size, class, - placement: Placement::Anywhere, + placement: super::object::Placement::Anywhere, offset: 0, client, lower: None, @@ -131,39 +137,91 @@ fn write_records( Ok(()) } impl Allocator { - pub(crate) fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { + /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. + 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, 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 + /// `RENDER_UMA_SLOT + hw_slot`). + pub(crate) fn new_at( + o: &mut Objects, + fw_factory: &Factory, + 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. - // In particular its firmware pointers, +0x54 completion and +0x5c exclusion flag - // must not share a writable GPU page with the engine auxiliary records. - let descriptor = alloc(o, uma_manager::SIZE, Class::Fw, None, true)?; + // Keep descriptor + submitted in a VM-free FwLease so firmware's global UMA table + // stays mapped across closed-VM reclaim without pinning the VM's ASID or pools. + let mut fw = fw_factory.fw_objects(); + let descriptor = alloc(&mut fw, uma_manager::SIZE, Class::Fw, None, true)?; + let submitted = alloc(&mut fw, 0x40, Class::Fw, None, true)?; + let uma_lease = FwLease::new(fw)?; let auxiliary = alloc( o, 0x4000, Class::Shared, - nc(client::render_descriptor(k)), + nc(state_va + client::RENDER_DESCRIPTOR_OFF), false, )?; - let pool = alloc( + let pool = alloc(o, placement.pool_bytes(), Class::Shared, nc(pool_va), false)?; + let state = alloc( o, - 0x2000000, + placement.freelist_bytes(), Class::Shared, - nc(client::render_pool(k)), - false, + nc(freelist_va), + true, + )?; + let list = alloc( + o, + 0x4000, + Class::Shared, + nc(state_va + client::RENDER_LIST_OFF), + true, )?; - let state = alloc(o, 0x20000, Class::Shared, nc(client::render_state(k)), true)?; - let list = alloc(o, 0x4000, Class::Shared, nc(client::render_list(k)), true)?; - let submitted = alloc(o, 0x40, Class::Fw, None, 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( descriptor.va, - engine::RENDER_UMA_SLOT + k as u32, + engine::RENDER_UMA_SLOT + hw_slot, gva(&state)?, gva(&list)?, submitted.va, + placement.seeds(), + super::rt::freelist_records(placement.seeds()), ), )?; Ok(Self { @@ -174,10 +232,19 @@ impl Allocator { list, submitted, heap, + uma_lease, published: AtomicBool::new(false), - id: k as u32, + id: hw_slot, }) } + /// Firmware-only lease retaining this allocator's UMA descriptor and submitted counter. + pub(crate) fn uma_lease(&self) -> Arc { + self.uma_lease.clone() + } + /// Device-wide hardware PB/UMA slot (`parameter_id`) owned by this allocator unit. + pub(crate) fn id(&self) -> u32 { + self.id + } pub(crate) fn refs(&self) -> Result { let prior = read64(&self.submitted, 0)?; if prior & 1 != 0 { @@ -270,7 +337,16 @@ pub(crate) fn alloc_pb_heap_chunk( } impl PoolSet { - pub(crate) fn new(o: &mut Objects) -> Result { + pub(crate) fn new(o: &mut Objects, fw_factory: &Factory) -> Result { + Self::new_with_slots(o, fw_factory, [0, 1]) + } + /// Base render allocator units mapped at per-VM local VA indices `0..BASE_PB_SLOTS` and + /// bound to device-wide physical PB/UMA slots `slots`. + pub(crate) fn new_with_slots( + o: &mut Objects, + fw_factory: &Factory, + slots: [usize; sizes::BASE_PB_SLOTS], + ) -> Result { // The firmware copes with a full PB without the host (its overflow counters move and // the scene completes), so the heap is sized well below the 256 MiB window. let heap_blocks = super::params::pb_heap_blocks().min(buffer::MAX_BLOCKS); @@ -282,15 +358,50 @@ impl PoolSet { false, )?; let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; - for k in 0..sizes::BASE_PB_SLOTS as u64 { - units.push(Allocator::new(o, k, &heap)?, 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, + Placement::Base, + )?, + GFP_KERNEL, + )?; } Ok(Self { 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) @@ -356,13 +467,25 @@ impl PoolSet { pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, + /// The epoch whose manager `pb_mgr_table[k]` names, kept until a newer epoch retires on + /// slot `k`, also after its VM closed: it maps the manager's page and block lists and keeps + /// the VM's TTBAT slot bound, the context through which those lists are written. owners: [Option>; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each `parameter_id`'s `pb_manager` + `counter` page mapped + /// for firmware's global `pb_mgr_table[parameter_id]` across closed-VM reclaim until a newer + /// `InitBM` retires on that exact slot. + retained_pb: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] owner_vms: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] owner_arenas: [Option; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each render UMA slot's `descriptor` + `submitted` page + /// mapped for firmware's global `uma_mgr_table[RENDER_UMA_SLOT + k]` across closed-VM reclaim + /// until a newer render retires on that exact slot. + retained_uma: [Option>; sizes::PB_SLOTS], pending_vms: [Option>; sizes::PB_SLOTS], pending_arenas: [Option; sizes::PB_SLOTS], + pending_uma: [Option>; sizes::PB_SLOTS], /// Per allocator slot, a binding count, bumped by each fresh epoch (its InitBM rebinds the /// slot) and by a firmware recovery. It identifies a binding without holding the epoch. binds: [u64; sizes::PB_SLOTS], @@ -380,15 +503,19 @@ pub(crate) struct Pools { quarantined_epochs: [Option>; sizes::PB_SLOTS], } impl Pools { + #[allow(dead_code)] pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { Self { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], owner_vms: [const { None }; sizes::PB_SLOTS], owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], pending_vms: [const { None }; sizes::PB_SLOTS], pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], binds: [0; sizes::PB_SLOTS], keep: [false; sizes::PB_SLOTS], active: None, @@ -398,6 +525,44 @@ impl Pools { quarantined_epochs: [const { None }; sizes::PB_SLOTS], } } + /// Allocates [`Pools`] directly on the heap so probe/backend bring-up does not stage the + /// per-slot lease arrays on the kernel stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed(dev: &AsahiDrmDevice) -> Result> { + Ok(KBox::init( + init!(Self { + dev: dev.as_ref().as_ref().into(), + stats: PbStats::default(), + owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], + owner_vms: [const { None }; sizes::PB_SLOTS], + owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], + pending_vms: [const { None }; sizes::PB_SLOTS], + pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], + binds: [0; sizes::PB_SLOTS], + keep: [false; sizes::PB_SLOTS], + active: None, + last_clean_retired: None, + inflight: [0; sizes::PB_SLOTS], + quarantined: [false; sizes::PB_SLOTS], + quarantined_epochs: [const { None }; sizes::PB_SLOTS], + }), + GFP_KERNEL, + )?) + } + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) fn quarantined_mask(&self) -> u32 { + let mut mask = 0u32; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + mask |= 1u32 << k; + } + } + mask + } /// Number of contiguous PB/UMA allocator slots (`0..n`) each rendering VM should prepare /// so at least [`sizes::BASE_PB_SLOTS`] healthy slots remain available across quarantines. #[allow(dead_code)] @@ -425,6 +590,10 @@ impl Pools { let n = limit.min(sizes::PB_SLOTS); (0..n).any(|k| self.slot_displaced(k)) } + /// Whether at least one displaced physical PB allocator slot exists in `slot_mask`. + fn has_displaced_slot_in_mask(&self, slot_mask: u32) -> bool { + (0..sizes::PB_SLOTS).any(|k| (slot_mask & (1u32 << k)) != 0 && self.slot_displaced(k)) + } /// Allocator slot `k`'s owner epoch, if its render retired normally while the slot was still /// bound to it, it belongs to `vm` and was exposed (its InitBM ran). InitBM binds the /// device-wide slot to one epoch and VM; a fresh epoch handed to the slot rebinds it, so @@ -438,49 +607,194 @@ 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_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_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_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 within `0..limit` for `vm`, requiring any reused - /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. + /// 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_mode(a, vm, slot_mask, min_blocks, want_scs) + .is_some() + { + return Some(a); + } + } + if let Some(k) = (0..sizes::PB_SLOTS).find(|&k| { + in_mask(k) + && self + .reusable_for_mask_mode(k, vm, slot_mask, min_blocks, want_scs) + .is_some() + }) { + return Some(k); + } + if behind { + return None; + } + // Cold (drained): claim the VM's unused home slot first, then any unused warm slot, + // then a displaced warm slot (preferring home), and finally recovery spares. + if home < sizes::WARM_PB_SLOTS + && in_mask(home) + && self.slot_displaced(home) + && self.owners[home].is_none() + { + return Some(home); + } + if let Some(k) = (0..sizes::WARM_PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_none()) + { + return Some(k); + } + if home < sizes::WARM_PB_SLOTS && in_mask(home) && self.slot_displaced(home) { + return Some(home); + } + if let Some(k) = + (0..sizes::WARM_PB_SLOTS).find(|&k| in_mask(k) && self.slot_displaced(k)) + { + return Some(k); + } + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_some()) + .or_else(|| { + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k)) + }) + } + /// 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_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` 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_mode(vm, false, slot_mask, home, 0, want_scs) + .is_none() + } + /// 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. - pub(crate) fn pick_slot_within_blocks( + #[allow(dead_code)] + 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 { @@ -491,7 +805,20 @@ 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( &self, vm: &Arc, @@ -505,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)] @@ -514,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)] @@ -544,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 @@ -551,14 +904,14 @@ 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)] pub(crate) fn exhausted_for(&self, vm: &Arc) -> bool { self.exhausted_for_within(vm, sizes::PB_SLOTS) } - /// Retains the candidate VM and owning render/recovery arena (holding the UMA descriptors) + /// Retains the candidate VM, owning render/recovery arena, and firmware UMA descriptor lease /// before publication visibility. #[allow(dead_code)] pub(crate) fn hold_alloc( @@ -566,12 +919,14 @@ impl Pools { k: usize, vm: &Arc, arena: Option, + uma_lease: Option>, ) -> Result { if k >= sizes::PB_SLOTS || self.quarantined[k] { return Err(EINVAL); } self.pending_vms[k] = Some(vm.clone()); self.pending_arenas[k] = arena; + self.pending_uma[k] = uma_lease; Ok(()) } /// Cancels unpublished candidate retention for allocator slot `k`. @@ -580,6 +935,7 @@ impl Pools { if k < sizes::PB_SLOTS { self.pending_vms[k] = None; self.pending_arenas[k] = None; + self.pending_uma[k] = None; } } /// Records a render reaching firmware visibility on allocator slot `k`. @@ -607,12 +963,16 @@ impl Pools { return Ok(()); } self.owners[k] = Some(epoch.clone()); + self.retained_pb[k] = Some(epoch.records_lease()); if let Some(vm) = self.pending_vms[k].take() { self.owner_vms[k] = Some(vm); } if let Some(arena) = self.pending_arenas[k].take() { self.owner_arenas[k] = Some(arena); } + if let Some(uma) = self.pending_uma[k].take() { + self.retained_uma[k] = Some(uma); + } self.last_clean_retired = Some(k); self.retire_epoch(k, binding, completed); Ok(()) @@ -675,9 +1035,53 @@ impl Pools { *keep = false; } } + /// Releases the displaced render arenas and PB heaps of closed VMs while preserving active, + /// in-flight, undisplaced, and quarantined slots. Returns `true` if any non-quarantined + /// slot still holds such a closed-VM lease awaiting retirement or displacement. + /// + /// The owner epoch itself stays until a newer epoch retires on its slot + /// ([`Self::retire_flight`]): `pb_mgr_table[k]` keeps naming its manager, and the parameter + /// manager can still write that manager's page list through the context of the epoch's VM. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + continue; + } + let pending = self.pending_vms[k].is_some() + || self.pending_arenas[k].is_some() + || self.pending_uma[k].is_some(); + // Only the owner epoch is left; the next epoch to retire on the slot releases it. + if !pending && self.owner_vms[k].is_none() && self.owner_arenas[k].is_none() { + continue; + } + let closed = self.owner_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()) + || self.owners[k] + .as_ref() + .is_some_and(|epoch| epoch._vm.vm.is_closed()) + || self.pending_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !closed { + continue; + } + if self.slot_displaced(k) && !pending { + self.owner_vms[k] = None; + self.owner_arenas[k] = None; + self.keep[k] = false; + self.binds[k] = self.binds[k].wrapping_add(1); + } else { + remaining = true; + } + } + remaining + } #[allow(dead_code)] pub(crate) fn retire_binding(&mut self, k: usize, epoch: &Arc) -> Result { *self.owners.get_mut(k).ok_or(EINVAL)? = Some(epoch.clone()); + *self.retained_pb.get_mut(k).ok_or(EINVAL)? = Some(epoch.records_lease()); Ok(()) } pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { @@ -713,7 +1117,14 @@ pub(crate) struct PbEpochInner { pub(crate) initbm: Arc, assigned: AtomicU32, heap_blocks: AtomicU32, + /// 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]`. + records_lease: Arc, // Unmap private records before releasing the VM's aliases and ASID. _objects: Objects, _vm: Arc, @@ -726,8 +1137,10 @@ impl PbEpoch { vm: &Arc, permit: super::budget::Permit, ) -> Result> { + let mut fw = factory.fw_objects(); + let records = alloc(&mut fw, 0x500, Class::Fw, None, true)?; + let records_lease = FwLease::new(fw)?; let mut o = factory.objects(&vm.vm); - let records = alloc(&mut o, 0x500, Class::Fw, None, true)?; let mut inner = PbEpochInner { manager: FwObject::view(&records, 0, 0xc0)?, pages: o.alloc_dynamic_client(buffer::PAGE_LIST_SIZE)?, @@ -738,7 +1151,10 @@ impl PbEpoch { initbm: FwObject::view(&records, 0x400, 0x20)?, 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, _vm: vm.clone(), _permit: permit, @@ -750,9 +1166,27 @@ impl PbEpoch { )?) } + /// Firmware-only lease retaining this epoch's `pb_manager` + `counter` page. + pub(crate) fn records_lease(&self) -> Arc { + self.records_lease.clone() + } + /// 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 @@ -760,13 +1194,18 @@ impl PbEpoch { { return Err(EINVAL); } - // Only the backed part of the heap is named; the rest of the lists stays zero. + // Only the backed part of the heap is named; the rest of the zero-allocated lists stays + // zero. On an unpublished retry with fewer blocks, clear the previously seeded tail. + let prev_blocks = self.seeded_blocks.load(Ordering::Acquire); + let write_blocks = heap_blocks.max(prev_blocks); + self.seeded_blocks.store(write_blocks, Ordering::Release); let pages = heap_blocks * buffer::PAGES_PER_BLOCK; - write_records(&self.pages, buffer::MAX_PAGES as usize, |i| { + let write_pages = write_blocks * buffer::PAGES_PER_BLOCK; + write_records(&self.pages, write_pages as usize, |i| { let i = i as u32; (if i < pages { buffer::page_record(heap, i) } else { 0 }).to_le_bytes() })?; - write_records(&self.blocks, buffer::MAX_BLOCKS as usize, |i| { + write_records(&self.blocks, write_blocks as usize, |i| { let b = i as u32; u64::from(if b < heap_blocks { buffer::block_record(heap, b) } else { 0 }).to_le_bytes() })?; @@ -786,13 +1225,18 @@ impl PbEpoch { heap_blocks, ), )?; + 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/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 869e716b2b7e..d3cf6caf6084 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -118,10 +118,41 @@ 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) } + /// Whether owner `k` is permanently quarantined. + pub(crate) fn is_quarantined(&self, k: usize) -> bool { + self.units + .get(k) + .is_some_and(|u| u.state == State::Quarantined) + } pub(crate) fn claim(&mut self, k: usize) -> bool { if !self.available(k) { return false; diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 08cf2543c9c2..319232fd4633 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 @@ -101,6 +105,15 @@ impl QueueState { Ok(()) } + /// Whether any accepted ordinal of `engine` at or before `seq` was cancelled. + pub(crate) fn cancelled_through(&self, engine: usize, seq: u64) -> Result { + let first = self.cancelled_at[engine].load(Ordering::Acquire); + if first != 0 && first <= seq { + return Err(ECANCELED); + } + Ok(()) + } + /// Whether compute ordinal `seq` already has a full successful firmware receipt, either /// at or below the contiguous `completed[COMPUTE]` frontier or recorded in `compute_ooo`. pub(crate) fn is_compute_retired(&self, seq: u64) -> bool { @@ -147,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, } @@ -198,7 +215,7 @@ impl Queue { }, GFP_KERNEL, )?; - let proof = KBox::new(command::SpanProof::new(), GFP_KERNEL)?; + let proof = command::SpanProof::new_boxed()?; Ok(Self { scheduler, state, @@ -207,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, }) } @@ -237,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, )?; @@ -255,8 +276,11 @@ 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), - pb_slots: self.shared.needed_pb_slots.load(Ordering::Acquire) as usize, + quarantined_pb_mask: self.shared.quarantined_pb_mask.load(Ordering::Acquire), + next_pb_slot: &self.shared.next_pb_slot, + active_render_vms: &self.shared.active_render_vms, }; let resources = self .vm @@ -264,7 +288,25 @@ impl Queue { .as_ref() .ok_or(EIO)? .prepare(&self.vm, &submission.commands, hints)?; - let fence = self.timeline.next()?; + let gpu_id = Arc::as_ptr(&self.shared) as usize; + // Record cumulative queue ordinals across both engines so coalescing multiple + // same-queue fences in a timeline semaphore chain to the latest fence preserves + // any earlier unretired render or compute command on that queue. + let total_render = self.accepted[command::RENDER] + submission.counts[command::RENDER]; + let total_compute = self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]; + let last_ordinal = [ + (total_render != 0).then_some(total_render), + (total_compute != 0).then_some(total_compute), + ]; + let origin = Arc::new( + super::fence::FenceOrigin::new(gpu_id, self.vm.id, self.state.clone(), last_ordinal), + GFP_KERNEL, + )?; + let (inputs, fw_waits) = match super::fence::resolve_fw_waits(&inputs, gpu_id, self.vm.id) { + Some(waits) => (InputFences::new(), waits), + None => (inputs, super::fence::FwWaits::Empty), + }; + let fence = self.timeline.next(origin.clone())?; let job = Job::new( id, self.state.clone(), @@ -275,6 +317,8 @@ impl Queue { fence, guard, inputs, + origin, + fw_waits, )?; let published = job.fence.fence(); // Publish output syncs (including fallible cumulative scope allocation) before pushing @@ -290,6 +334,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 9f20506a0b0f..e64173551114 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); } @@ -172,6 +174,7 @@ impl Firmware { /// Protocol errors and transport loss always retain uncertain owners. /// A deadline without a firmware recovery notification is not permission /// to manipulate undocumented preemption controls. + #[inline(never)] pub(crate) fn check_hangs(&mut self, done: &mut Completions) -> Result { if let Some(error) = self.recovery.failed { return Err(error); @@ -205,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, @@ -231,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 f93b2cd35f4f..528760bb1654 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 84871c04b167..25b0d609a3d2 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, PassCmds, PassSlot, Placement}, vm::VmState, }; use crate::mmu; @@ -17,9 +17,64 @@ 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}, }; +/// 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 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] + 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, k as u64)?; + 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 @@ -27,6 +82,8 @@ use kernel::{ /// avoids allocating and mapping fresh epochs whenever submission depth rises. const SPARE_EPOCHS: usize = 32; +/// Backing for one physical compute unit (`k`) of a VM, deferred-dropped independently so an +/// undisplaced last-retired owner lease on one CDM pipe never pins the VM's other compute units. pub(crate) struct ComputeArena(crate::cleanup::Deferred); impl core::ops::Deref for ComputeArena { type Target = ComputeInner; @@ -35,7 +92,7 @@ impl core::ops::Deref for ComputeArena { } } pub(crate) struct ComputeInner { - pub(crate) compute: KVec, + pub(crate) unit: ComputeSlot, _objects: Objects, // Mappings must disappear while their root still owns its ASID. _bind: mmu::VmBind, @@ -53,23 +110,26 @@ const BURST_GAP_NS: u64 = 2_000_000; const BURST_COMMANDS: usize = 3; impl ComputeArena { - /// Units `units` (their index fixes their 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, - units: core::ops::Range, + k: usize, + placement: Placement, ) -> Result> { let mut objects = factory.objects(vm); - let mut compute = KVec::with_capacity(units.len(), GFP_KERNEL)?; - for k in units { - compute.push(ComputeSlot::new(&mut objects, k as u64)?, GFP_KERNEL)?; - } + let unit = ComputeSlot::new_in(&mut objects, factory, k as u64, placement)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { - compute, + unit, _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -79,20 +139,98 @@ impl ComputeArena { } } +/// Contiguous range of independently reference-counted [`ComputeArena`] units owned by a VM. +/// +/// Each unit `k` owns its own `Arc` so `Cache::close()` and +/// `Slots::reclaim_closed()` release all unused or displaced units immediately even while a +/// 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 + /// 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, placement)?, + 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() + } + /// 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) + } + fn arena(&self, idx: usize) -> Option> { + self.units.get(idx).cloned() + } +} + /// Render pass slots every VM gets with its first render command; extension slots /// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are grown lazily in bounded tiers once the VM /// pipelines renders or submits multi-pass/burst frames. 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.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), @@ -106,7 +244,7 @@ const _: () = assert!(EXT_RENDER_TIERS[1].1 == EXT_RENDER_TIERS[2].0); const _: () = assert!(EXT_RENDER_TIERS[2].1 == EXT_RENDER_TIERS[3].0); const _: () = assert!(EXT_RENDER_TIERS[3].1 == super::hw::sizes::RENDER_SLOTS); const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; -const EXT_PB_SLOTS: usize = super::hw::sizes::PB_SLOTS - BASE_PB_SLOTS; +const EXT_PB_SLOTS: usize = super::hw::sizes::EXT_PB_SLOTS; /// Demand-grown contiguous PB heap extensions within the 256 MiB /// [`super::hw::client::PB_HEAP_SIZE`] window so steady 60/120 Hz single-pass clients stay on /// the 64 MiB base heap while multi-pass and heavy 3D workloads expand to 128 MiB (Tier 0) and @@ -124,14 +262,95 @@ const _: () = assert!( const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; /// Device-wide hints read locklessly in `SUBMIT` to size per-VM extension backing. -#[derive(Copy, Clone, Default)] -pub(crate) struct PrepareHints { +#[derive(Copy, Clone)] +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, - /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. - pub(crate) pb_slots: usize, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: u32, + /// Round-robin cursor assigning a VM's `[home, alt]` base PB/UMA slots in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: &'a AtomicU32, + /// Live open VMs owning a `RenderArena`, used for multi-VM pass-slot headroom. + 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 @@ -161,8 +380,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.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. @@ -209,6 +428,51 @@ fn target_render_slots( target.min(super::hw::sizes::RENDER_SLOTS) } +/// Like [`target_render_slots`], returning `(effective_target, single_vm_target)`. +/// +/// When `active_render_vms` reaches Tier 0's pass-slot ceiling (`EXT_RENDER_TIERS[0].1 == 8`) +/// and this VM is already bursting (`single_vm_target > BASE_RENDER_SLOTS`), `effective_target` +/// expands up to Tier 1 (`EXT_RENDER_TIERS[1].1 == 18`) so up to 16 concurrent render VMs each +/// keep a warm pass slot without cross-VM full-scrub thrashing. Steady 60/120 Hz single-pass +/// clients stay at `BASE_RENDER_SLOTS`, and `single_vm_target` keeps `PB_HEAP_EXT_TIERS` gated +/// on actual single-VM pass demand so multi-VM light renders do not expand to 256 MiB PB heaps. +fn target_render_slots_for( + last_render_ns: &mut u64, + render_burst: &mut u32, + now: u64, + render_count: usize, + active_passes: u32, + base_quarantined: bool, + current_slots: usize, + single_vm_slots: usize, + active_render_vms: u32, +) -> (usize, usize) { + let single = target_render_slots( + last_render_ns, + render_burst, + now, + render_count, + active_passes, + base_quarantined, + single_vm_slots.max(BASE_RENDER_SLOTS), + ); + let mut target = current_slots.max(single); + if single > BASE_RENDER_SLOTS && (active_render_vms as usize) >= EXT_RENDER_TIERS[0].1 { + let multi_need = (active_render_vms as usize) + .saturating_add(1) + .min(EXT_RENDER_TIERS[1].1); + for &(start, end) in &EXT_RENDER_TIERS[..2] { + if target >= multi_need { + break; + } + if target < end && multi_need > start { + target = end; + } + } + } + (target.min(super::hw::sizes::RENDER_SLOTS), single) +} + pub(crate) struct RenderArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderArena { type Target = RenderInner; @@ -216,9 +480,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], @@ -243,18 +518,22 @@ impl RenderArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + base_pb_slots: [usize; BASE_PB_SLOTS], ) -> Result> { 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(&mut objects)?; + let pools = PoolSet::new_with_slots(&mut objects, factory, base_pb_slots)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderInner { 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], @@ -267,6 +546,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 { @@ -319,7 +622,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)?; @@ -345,8 +649,9 @@ impl RenderExtArena { } } -/// One lazily allocated recovery PB/UMA allocator slot (`BASE_PB_SLOTS..PB_SLOTS`), -/// sharing the VM's base PB heap so non-fault VMs pay zero extra allocator memory. +/// One lazily allocated recovery PB/UMA allocator slot (`WARM_PB_SLOTS..PB_SLOTS`), +/// mapped at per-VM local VA index `BASE_PB_SLOTS..MAX_VM_PB_SLOTS` and sharing the VM's base PB +/// heap so non-fault VMs pay zero extra allocator memory. pub(crate) struct PoolExtArena(crate::cleanup::Deferred); impl core::ops::Deref for PoolExtArena { type Target = PoolExtInner; @@ -366,11 +671,19 @@ impl PoolExtArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, - slot: usize, + local_idx: usize, + hw_slot: usize, heap: &Arc, ) -> Result> { let mut objects = factory.objects(vm); - let allocator = super::pools::Allocator::new(&mut objects, slot as u64, heap)?; + let allocator = super::pools::Allocator::new_at( + &mut objects, + factory, + local_idx as u64, + hw_slot as u32, + heap, + Placement::Base, + )?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(PoolExtInner { @@ -482,16 +795,23 @@ impl PassOwnerArena { #[derive(Default)] struct Ready { - compute: Option>, + compute: Option>, /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. - compute_ext: Option>, + 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()], /// Demand-grown contiguous PB heap extension tiers (`PB_HEAP_EXT_TIERS`). pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], - /// Recovery PB/UMA allocator slots (`BASE_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. + /// Recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. pb_ext: [Option>; EXT_PB_SLOTS], + /// Single-VM render pass slot target (excluding multi-VM Tier 1 expansion), gating + /// `PB_HEAP_EXT_TIERS` so concurrent light-render VMs do not allocate 256 MiB PB heaps. + single_vm_render_slots: usize, + /// Device-wide count of open rendering VMs; decremented once on `Cache::close()` or drop. + render_vm_counter: Option>, /// Last compute submission and the back-to-back run it continues. last_compute_ns: u64, burst: u32, @@ -499,6 +819,13 @@ struct Ready { last_render_ns: u64, render_burst: u32, } +impl Drop for Ready { + fn drop(&mut self) { + if let Some(counter) = self.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } + } +} struct Standby { /// Never-exposed epochs kept on standby for this VM's queued renders. /// Invariant: while open or while `reserved > 0`, `epochs.len() >= reserved as usize`. @@ -662,9 +989,13 @@ impl Cache { self.standby_available.notify_all(); let ready = { let mut ready = self.ready.lock(); + if let Some(counter) = ready.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } ( 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), @@ -678,7 +1009,7 @@ impl Cache { self: &Arc, vm: &Arc, commands: &[Command], - hints: PrepareHints, + hints: PrepareHints<'_>, ) -> Result { let computes = commands .iter() @@ -691,6 +1022,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. @@ -698,16 +1045,38 @@ 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() { - ready.compute = Some(ComputeArena::new( + 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 => { + 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, + hw_slots, + 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. @@ -721,46 +1090,82 @@ impl Cache { hints.expand_compute_ext, ) { // Best effort: without them the VM keeps the base compute units. - state.compute_ext = ComputeArena::new( + state.compute_ext = ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, &self.live, BASE_COMPUTE_UNITS..units, + Placement::Base, ) .ok(); } } } if render && ready.render.is_none() { + 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, + base_pb_slots, )?); + if ready.render_vm_counter.is_none() { + hints.active_render_vms.fetch_add(1, Ordering::AcqRel); + 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 { - let target_pb = hints.pb_slots.clamp(BASE_PB_SLOTS, super::hw::sizes::PB_SLOTS); - if target_pb > BASE_PB_SLOTS { - if let Some(base) = ready.render.as_ref() { + if let Some(base) = ready.render.as_ref() { + let quarantined = hints.quarantined_pb_mask; + let mut healthy = base + .base_pb_slots + .iter() + .filter(|&&slot| (quarantined & (1u32 << slot)) == 0) + .count(); + for (idx, ext) in ready.pb_ext.iter().enumerate() { + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ext.is_some() && (quarantined & (1u32 << hw_slot)) == 0 { + healthy += 1; + } + } + if healthy < BASE_PB_SLOTS { let heap = base.pools.heap().clone(); - for k in BASE_PB_SLOTS..target_pb { - let idx = k - BASE_PB_SLOTS; - if ready.pb_ext[idx].is_none() { - // Best effort: without recovery slots, keep prior PB slots. - ready.pb_ext[idx] = PoolExtArena::new( - &self.factory, - &self.bind, - &vm.vm, - &self.live, - k, - &heap, - ) - .ok(); - if ready.pb_ext[idx].is_none() { - break; - } + for idx in 0..EXT_PB_SLOTS { + if healthy >= BASE_PB_SLOTS { + break; + } + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ready.pb_ext[idx].is_some() + || (quarantined & (1u32 << hw_slot)) != 0 + { + continue; + } + let local_idx = BASE_PB_SLOTS + idx; + // Best effort: without recovery slots, keep prior PB slots. + ready.pb_ext[idx] = PoolExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + local_idx, + hw_slot, + &heap, + ) + .ok(); + if ready.pb_ext[idx].is_some() { + healthy += 1; + } else { + break; } } } @@ -778,7 +1183,8 @@ impl Cache { let now = unsafe { kernel::bindings::ktime_get() } as u64; let state = &mut *ready; let active_passes = self.active_render_passes.load(Ordering::Acquire); - let target = target_render_slots( + let active_vms = hints.active_render_vms.load(Ordering::Acquire); + let (target, single_target) = target_render_slots_for( &mut state.last_render_ns, &mut state.render_burst, now, @@ -786,7 +1192,10 @@ impl Cache { active_passes, hints.expand_render_ext, current_slots, + state.single_vm_render_slots, + active_vms, ); + state.single_vm_render_slots = state.single_vm_render_slots.max(single_target); for (idx, &(start, end)) in EXT_RENDER_TIERS.iter().enumerate() { if start >= target { break; @@ -809,8 +1218,11 @@ impl Cache { } if let Some(base) = ready.render.as_ref() { let base_blocks = base.pools.heap_blocks(); + let single_slots = ready.single_vm_render_slots; for (idx, &(start, end)) in PB_HEAP_EXT_TIERS.iter().enumerate() { - if ready.render_ext[idx].is_none() { + if single_slots < EXT_RENDER_TIERS[idx].1 + || ready.render_ext[idx].is_none() + { break; } if base_blocks >= end { @@ -851,8 +1263,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, @@ -953,7 +1373,9 @@ impl Cache { Ok(Prepared { compute, compute_ext, + compute_scs, render: render_arena, + render_scs, render_ext, pb_heap_ext, pb_ext, @@ -966,10 +1388,14 @@ impl Cache { /// Immutable references carried by an accepted job. No fallible lazy work in the engine. pub(crate) struct Prepared { - pub(crate) compute: Option>, + pub(crate) compute: Option>, /// The VM's extension compute units when the job was prepared. - pub(crate) compute_ext: Option>, + 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. @@ -998,40 +1424,91 @@ impl Drop for Prepared { } } impl Prepared { - pub(crate) fn compute(&self) -> Result<&ComputeArena> { + pub(crate) fn compute(&self) -> Result<&ComputeUnitSet> { 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()?.compute.len() - + self.compute_ext.as_deref().map_or(0, |e| e.compute.len())) + 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 arena holding compute unit `k`. + /// The per-unit arena holding compute unit `k`. pub(crate) fn compute_arena(&self, k: usize) -> Option> { let base = self.compute.as_ref()?; - if k < base.compute.len() { - Some(base.clone()) + 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 { - self.compute_ext.clone() + self.compute_ext + .as_ref() + .and_then(|ext| ext.arena(k - base.len())) } } - /// Contiguous PB/UMA allocator slots (`0..n`) this job can use. - pub(crate) fn pb_slots(&self) -> Result { - let _ = self.render()?; - let ext = self.pb_ext.iter().take_while(|slot| slot.is_some()).count(); - Ok(BASE_PB_SLOTS + ext) + /// 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()?; + let mut mask = 0u32; + for &slot in &base.base_pb_slots { + mask |= 1u32 << slot; + } + 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])) } fn pb_allocator(&self, k: usize) -> Result<&super::pools::Allocator> { let base = self.render()?; - if k < BASE_PB_SLOTS { - base.pools.unit(k).ok_or(EINVAL) - } else { - self.pb_ext - .get(k - BASE_PB_SLOTS) - .and_then(|slot| slot.as_deref()) - .map(|arena| &arena.allocator) - .ok_or(EINVAL) + if let Some(local) = base.base_pb_slots.iter().position(|&slot| slot == k) { + 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 + .get(idx) + .and_then(|slot| slot.as_deref()) + .map(|arena| &arena.allocator) + .ok_or(EINVAL) } pub(crate) fn prepare_pb_in_flight( &self, @@ -1071,15 +1548,23 @@ impl Prepared { pub(crate) fn pb_owner_arena(&self, k: usize) -> Option { let base = self.render.as_ref()?; let heap_ext = core::array::from_fn(|idx| self.pb_heap_ext[idx].clone()); - if k < BASE_PB_SLOTS { + if base.base_pb_slots.contains(&k) { Some(PbOwnerArena::Base(base.clone(), heap_ext)) } else { + let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS)?; self.pb_ext - .get(k - BASE_PB_SLOTS) + .get(idx) .and_then(|slot| slot.as_ref()) .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone(), heap_ext)) } } + /// VM-free firmware lease keeping PB/UMA allocator slot `k`'s `descriptor` + `submitted` + /// pages mapped in context-0 UAT across closed-VM reclaim. + pub(crate) fn pb_uma_lease(&self, k: usize) -> Option> { + self.pb_allocator(k) + .ok() + .map(super::pools::Allocator::uma_lease) + } fn render_ext_for(&self, k: usize) -> Option<(&Arc, usize)> { for tier in self.render_ext.iter().take_while(|t| t.is_some()).flatten() { if let Some(idx) = k.checked_sub(tier.start) { @@ -1161,15 +1646,19 @@ 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()?.compute; - match base.get(k) { + 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 .compute_ext .as_deref() - .and_then(|e| e.compute.get(k - base.len())) + .and_then(|e| e.unit(k - base.len())) .ok_or(EINVAL), } } diff --git a/drivers/gpu/drm/asahi/g16/rt.rs b/drivers/gpu/drm/asahi/g16/rt.rs new file mode 100644 index 000000000000..5b42e6f2d1dc --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/rt.rs @@ -0,0 +1,534 @@ +// 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. +//! - 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 +//! 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/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 261d872d2113..08ae0c679aa8 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -115,14 +115,16 @@ impl Shared { } self.events.drain(); self.events_unbound.drain(); - // `sleeping` is already set, so taking the queued scrubs under `scrub_queue` + // `sleeping` is already set, so draining queued scrubs under `scrub_queue` // guarantees no concurrent `enqueue_scrubs()` can still queue onto `scrub_wq` - // while `scrub_wq.drain()` runs. Drop the drained batch outside the spinlock. - let pending_scrubs = { - let mut queue = self.scrub_queue.lock(); - core::mem::replace(&mut *queue, super::slots::ScrubQueue::new()) - }; - drop(pending_scrubs); + // while `scrub_wq.drain()` runs. Drop each drained item outside the spinlock. + loop { + let item = self.scrub_queue.lock().pop(); + let Some(item) = item else { + break; + }; + drop(item); + } self.scrub_wq.drain(); self.feed.pause(); self.feed_wq.drain(); diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 7bcb1ca24913..f6952828e1ec 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -15,7 +15,7 @@ use super::encode::{Geometry, PassRefs}; use super::fw::work::{barrier, fs, ta}; use super::graph::{alloc, alloc_work, cmd_fw, Client}; use super::hw::{client, sizes}; -use super::object::{Class, FwObject, Objects}; +use super::object::{Class, Factory, FwLease, FwObject, Objects}; use super::pools::lifetime::Lifetime; /// One immutable allocation set. Mutable firmware pool cursors survive successful reuse. @@ -32,41 +32,152 @@ 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 { - pub(crate) fn new(o: &mut Objects, k: u64) -> Result { + #[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, placement.work(k), 0)?; + let counter = alloc(&mut fw, 0x80, sh, None, 0, false)?; + let uma_lease = FwLease::new(fw)?; let unit = Self { its: alloc(o, 16, sh, None, 0, false)?, preempt: alloc( o, 0x4000, sh, - Client::nc(client::compute_preempt(k)), + Client::nc(state + client::COMPUTE_PREEMPT_OFF), 0, false, )?, - work: alloc_work(o, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?, + work, seq: alloc(o, 0x300, cmd_fw(), None, 0, false)?, // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. barrier: alloc( @@ -78,41 +189,63 @@ 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: alloc(o, 0x80, sh, None, 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(state + client::COMPUTE_AUX_OFF), 0, false, )?, - aux: alloc(o, 0x4000, sh, Client::nc(client::compute_aux(k)), 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() + } /// Resets command-local state before reuse. Pool/list/counter/descriptor state is preserved. /// /// Clean same-VM reuse only zeroes the 16-byte internal timestamp pair so retirement @@ -131,6 +264,84 @@ impl ComputeSlot { } } +/// 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, + 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 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, 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)?, + 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, @@ -159,8 +370,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 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); let tpc = if i >= sizes::BASE_RENDER_SLOTS as u64 { @@ -237,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, @@ -258,35 +458,21 @@ impl PassSlot { scene_user, scene_list, 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)?, + 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)?, 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(), }) } @@ -461,6 +647,11 @@ pub(crate) struct ComputeOwners { /// descriptor when a later owner displaces it, after its VM's client closed. arena: [Option>; sizes::COMPUTE_UNITS], pending_arena: [Option>; sizes::COMPUTE_UNITS], + /// VM-free firmware leases keeping each hardware slot's `work` + `counter` mapped in + /// context-0 UAT across closed-VM reclaim until a later compute retirement overwrites + /// firmware `uma_mgr_table[1 + k]`. + retained_uma: [Option>; sizes::COMPUTE_UNITS], + pending_uma: [Option>; sizes::COMPUTE_UNITS], /// Force a full scrub on next claim (first use, cancel, error, or firmware recovery). scrub_full: [bool; sizes::COMPUTE_UNITS], /// Whether the most recent claim of each compute unit required a full scrub/work write. @@ -594,16 +785,21 @@ impl Drop for PendingScrub { } } +/// Maximum displaced render pass slots staged in one stack-resident [`ScrubBatch`]. +/// Keeping the batch bounded avoids multi-kilobyte stack frames in poll/submit paths while +/// any additional displaced slots remain flagged for the next pass. +const MAX_SCRUB_BATCH: usize = 8; + /// Zero-allocation batch of displaced render pass slots to scrub after dropping `Shared::state`. pub(crate) struct ScrubBatch { - items: [Option; sizes::RENDER_SLOTS], + items: [Option; MAX_SCRUB_BATCH], len: usize, } impl ScrubBatch { pub(crate) const fn new() -> Self { Self { - items: [const { None }; sizes::RENDER_SLOTS], + items: [const { None }; MAX_SCRUB_BATCH], len: 0, } } @@ -612,8 +808,12 @@ impl ScrubBatch { self.len == 0 } + fn is_full(&self) -> bool { + self.len >= MAX_SCRUB_BATCH + } + fn push(&mut self, item: PendingScrub) -> bool { - if self.len >= sizes::RENDER_SLOTS { + if self.len >= MAX_SCRUB_BATCH { return false; } self.items[self.len] = Some(item); @@ -637,6 +837,19 @@ impl ScrubQueue { } } + /// Allocates an empty [`ScrubQueue`] directly on the heap to keep `Shared` setup off the + /// probe stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed() -> Result> { + Ok(KBox::init( + init!(Self { + slots: [const { None }; sizes::RENDER_SLOTS], + }), + GFP_KERNEL, + )?) + } + /// Moves every staged scrub from `batch` into the queue. Returns `true` if any was queued. pub(crate) fn push_batch(&mut self, mut batch: ScrubBatch) -> bool { let mut pushed = false; @@ -698,6 +911,7 @@ pub(crate) struct Slots { render: KBox, } impl Slots { + #[inline(never)] pub(crate) fn new() -> Result { Ok(Self { cursor: 0, @@ -706,21 +920,23 @@ impl Slots { scrub_gen: 0, stats: SlotStats::default(), scrub: Arc::new(ScrubState::new(), GFP_KERNEL)?, - compute: KBox::new( - ComputeOwners { + compute: KBox::init( + init!(ComputeOwners { lifetime: Lifetime::new(true), owner: [const { None }; sizes::COMPUTE_UNITS], pending_retarget: [None; sizes::COMPUTE_UNITS], pending_owner: [const { None }; sizes::COMPUTE_UNITS], arena: [const { None }; sizes::COMPUTE_UNITS], pending_arena: [const { None }; sizes::COMPUTE_UNITS], + retained_uma: [const { None }; sizes::COMPUTE_UNITS], + pending_uma: [const { None }; sizes::COMPUTE_UNITS], scrub_full: [true; sizes::COMPUTE_UNITS], last_full: [true; sizes::COMPUTE_UNITS], - }, + }), GFP_KERNEL, )?, - render: KBox::new( - RenderOwners { + render: KBox::init( + init!(RenderOwners { lifetime: Lifetime::new(true), owner: [const { None }; sizes::RENDER_SLOTS], pending_retarget: [None; sizes::RENDER_SLOTS], @@ -731,7 +947,7 @@ impl Slots { last_full: [true; sizes::RENDER_SLOTS], staged: ScrubBatch::new(), scrub_pending: false, - }, + }), GFP_KERNEL, )?, }) @@ -760,9 +976,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() } @@ -786,20 +1011,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)] @@ -870,12 +1119,19 @@ impl Slots { || self.render.scrub_full[k] || self.scrub.is_scrubbing(k) || self.scrub.is_clean(k) + || self.render.owner[k] + .as_ref() + .is_none_or(|vm| vm.vm.is_closed()) { continue; } let Some(arena) = self.render.arena[k].clone() else { continue; }; + if self.render.staged.is_full() { + self.render.scrub_pending = true; + break; + } self.scrub.scrubbing.fetch_or(bit, Ordering::SeqCst); let generation = self.scrub.generation.load(Ordering::Acquire); let item = PendingScrub { @@ -886,6 +1142,7 @@ impl Slots { done: false, }; if !self.render.staged.push(item) { + self.render.scrub_pending = true; break; } } @@ -904,6 +1161,78 @@ impl Slots { } self.take_staged_scrubs() } + /// Releases displaced compute-unit and render-pass leases owned by closed VMs while + /// preserving active, in-flight, undisplaced, scrubbing, and quarantined slots. + /// + /// Returns `true` if any non-quarantined slot still holds a closed-VM lease awaiting + /// retirement, displacement, or an in-progress off-lock pass scrub. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::COMPUTE_UNITS { + if self.compute.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.compute.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.compute.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + if owner_closed + && self.compute.lifetime.available(k) + && self.compute.pending_owner[k].is_none() + && self.compute.pending_arena[k].is_none() + && self.compute.pending_uma[k].is_none() + { + self.compute.owner[k] = None; + self.compute.arena[k] = None; + self.compute.scrub_full[k] = true; + self.compute.last_full[k] = true; + } else { + remaining = true; + } + } + for k in 0..sizes::RENDER_SLOTS { + if self.render.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.render.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.render.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + let bit = 1u64 << k; + if owner_closed + && self.pass_busy & bit == 0 + && self.render.lifetime.available(k) + && self.render.pending_owner[k].is_none() + && self.render.pending_arena[k].is_none() + { + if self.scrub.is_scrubbing(k) { + self.scrub.waiter.store(true, Ordering::SeqCst); + } + if !self.scrub.is_scrubbing(k) { + self.render.owner[k] = None; + self.render.arena[k] = None; + self.render.scrub_full[k] = true; + self.render.last_full[k] = true; + self.scrub.clear_clean(k); + } else { + remaining = true; + } + } else { + remaining = true; + } + } + remaining + } /// Compute units published and not yet retired. pub(crate) fn compute_published(&self) -> u32 { self.compute.lifetime.published() @@ -918,20 +1247,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)] @@ -997,42 +1343,82 @@ impl Slots { if f.slot_count as usize >= f.slot.len() { return Ok(None); } - // Round robin over this VM's units eligible for `pipe`: 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 + // Prefer a warm unit already owned by `vm_id` (`!scrub_full`), then an unowned unit, + // 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; - for i in 0..span { - let k = start + (base_cursor + i) % span; - if self.compute.lifetime.claim(k) { - let full = self.compute.scrub_full[k] - || vm_id.is_none_or(|id| { - self.compute.owner[k] - .as_ref() - .is_none_or(|prev| prev.id != id) - }); - if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub(full)) { - self.compute.lifetime.cancel(k); - return Err(e); + 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..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) + && self.compute.lifetime.claim(k) + { + chosen = Some(k); + break; + } + } + if chosen.is_none() { + 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; + } } - self.compute.last_full[k] = full; - f.slot[f.slot_count as usize] = k as u32; - f.slot_count += 1; - f.compute_pipe = pipe as u8; - self.cursor = ((k + 1) % n) as u32; - return Ok(Some(k)); } } - Ok(None) + if chosen.is_none() { + 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; + } + } + } + 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() + .is_none_or(|prev| prev.id != id) + }); + if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub(full)) { + self.compute.lifetime.cancel(k); + return Err(e); + } + self.compute.last_full[k] = full; + f.slot[f.slot_count as usize] = k as u32; + f.slot_count += 1; + f.compute_pipe = pipe as u8; + self.cursor = ((k + 1) % n) as u32; + Ok(Some(k)) } #[allow(dead_code)] pub(crate) fn pick_pass( @@ -1088,10 +1474,27 @@ impl Slots { resources: &super::resources::Prepared, geo: &Geometry, picked: u64, + ) -> Option { + self.pick_pass_in_for(resources, geo, picked, None) + } + /// Selects a render pass slot in `resources` with capacity for `geo`, preferring slots + /// already owned by `vm_id` (clean before dirty) and unowned slots before retargeting + /// another VM's warm pass slot. + pub(crate) fn pick_pass_in_for( + &self, + resources: &super::resources::Prepared, + geo: &Geometry, + picked: u64, + vm_id: Option, ) -> Option { let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); - let mut clean_partial = None; - let mut fallback = None; + let mut same_clean_partial = None; + let mut same_dirty = None; + let mut unowned_clean = None; + let mut unowned_dirty = None; + let mut other_full_clean = None; + let mut other_clean_partial = None; + let mut other_dirty = None; let mut saw_scrubbing = false; for i in 0..n { let k = (self.pass_cursor as usize + i) % n; @@ -1107,22 +1510,55 @@ impl Slots { saw_scrubbing = true; continue; } - if self.scrub.is_clean(k) { - if let Ok(d) = resources.render_pass_dirty(k) { + let clean = self.scrub.is_clean(k); + let full_clean = clean + && resources.render_pass_dirty(k).is_ok_and(|d| { let need = d.tilemap.load(Ordering::Acquire).min(geo.tilemap_bytes); - if need <= d.tilemap_clean.load(Ordering::Acquire) + need <= d.tilemap_clean.load(Ordering::Acquire) && d.heap.load(Ordering::Acquire) == 0 - { + }); + if let Some(id) = vm_id { + let same_vm = !self.render.scrub_full[k] + && self.render.owner[k].as_ref().is_some_and(|o| o.id == id); + if same_vm { + if full_clean { return Some(k); } + if clean { + same_clean_partial.get_or_insert(k); + } else { + same_dirty.get_or_insert(k); + } + } else if self.render.owner[k].is_none() { + if full_clean { + unowned_clean.get_or_insert(k); + } else { + unowned_dirty.get_or_insert(k); + } + } else if full_clean { + other_full_clean.get_or_insert(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); } - clean_partial.get_or_insert(k); - continue; + } else if full_clean { + return Some(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); } - fallback.get_or_insert(k); } } - if let Some(k) = clean_partial.or(fallback) { + if let Some(k) = same_clean_partial + .or(same_dirty) + .or(unowned_clean) + .or(unowned_dirty) + .or(other_full_clean) + .or(other_clean_partial) + .or(other_dirty) + { return Some(k); } if saw_scrubbing { @@ -1327,6 +1763,7 @@ impl Slots { .and_then(|old| Self::vm_retarget(k, old, vm)); self.compute.pending_owner[k] = Some(vm.clone()); self.compute.pending_arena[k] = resources.compute_arena(k); + self.compute.pending_uma[k] = resources.compute_unit(k).ok().map(ComputeSlot::uma_lease); Ok(()) } @@ -1448,6 +1885,12 @@ impl Slots { if let Some(cell) = self.compute.pending_arena.get_mut(k as usize) { *cell = resources.compute_arena(k as usize); } + if let Some(cell) = self.compute.pending_uma.get_mut(k as usize) { + *cell = resources + .compute_unit(k as usize) + .ok() + .map(ComputeSlot::uma_lease); + } } let mut mask = f.pass_mask & PASS_MASK; while mask != 0 { @@ -1526,6 +1969,9 @@ impl Slots { for &k in &f.slot[..f.slot_count as usize] { self.compute.owner[k as usize] = self.compute.pending_owner[k as usize].take(); self.compute.arena[k as usize] = self.compute.pending_arena[k as usize].take(); + if let Some(lease) = self.compute.pending_uma[k as usize].take() { + self.compute.retained_uma[k as usize] = Some(lease); + } if clean_scrub { self.compute.scrub_full[k as usize] = false; } @@ -1577,6 +2023,7 @@ impl Slots { self.compute.pending_retarget[k as usize] = None; self.compute.pending_owner[k as usize] = None; self.compute.pending_arena[k as usize] = None; + self.compute.pending_uma[k as usize] = None; self.compute.scrub_full[k as usize] = true; } let mut mask = f.pass_mask & PASS_MASK; diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f..6ab44208a4f8 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -34,7 +34,7 @@ mod completion; pub(crate) mod context; mod data_segment; mod dependency; -mod sync_input; +pub(crate) mod sync_input; pub(crate) mod exec_share; pub(crate) mod sync_output; mod trace; diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 145a5955c879..6c68414b49fd 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -8,19 +8,43 @@ static int collect_leaf(struct dma_fence *leaf, struct asahi_g17_fence_leaf *out, size_t capacity, - size_t *count) + size_t *count, bool coalesce_contexts) { + int status = dma_fence_get_status(leaf); + size_t i; + + /* Already-signalled non-error leaves need no further wait or barrier. */ + if (status > 0) + return 0; + + for (i = 0; i < *count; ++i) { + if (out[i].fence == leaf) { + if (status < 0 && out[i].status >= 0) + out[i].status = status; + return 0; + } + if (coalesce_contexts && status == 0 && out[i].status == 0 && + out[i].fence->context == leaf->context) { + if (dma_fence_is_later(leaf, out[i].fence)) { + dma_fence_put(out[i].fence); + out[i].fence = dma_fence_get(leaf); + } + return 0; + } + } + if (*count == capacity) return -ENOSPC; out[*count].fence = dma_fence_get(leaf); - out[*count].status = dma_fence_get_status(leaf); + out[*count].status = status; ++*count; return 0; } /* Called without the device mutex: status polling may run fence callbacks. */ -int asahi_g17_collect_fences(struct dma_fence *head, - struct asahi_g17_fence_leaf *out, size_t capacity) +static int collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity, + bool coalesce_contexts) { struct dma_fence *pending[128]; size_t count = 0, depth = 1; @@ -34,11 +58,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, if (asahi_g17_is_scope(node)) { struct dma_fence *children[2]; - unsigned int n = asahi_g17_scope_children(node, children), i; + unsigned int n, i; + int status = dma_fence_get_status(node); + + if (status > 0) { + dma_fence_put(node); + continue; + } + n = asahi_g17_scope_children(node, children); if (!n) { /* Preserve a failed scope as a failed leaf, never drop its error. */ - if (dma_fence_get_status(node) < 0) - error = collect_leaf(node, out, capacity, &count); + if (status < 0) + error = collect_leaf(node, out, capacity, &count, + coalesce_contexts); } else if (depth + n > ARRAY_SIZE(pending)) { for (i = 0; i < n; ++i) dma_fence_put(children[i]); @@ -60,7 +92,8 @@ int asahi_g17_collect_fences(struct dma_fence *head, } else if (dma_fence_is_container(leaf)) { error = -EOPNOTSUPP; } else { - error = collect_leaf(leaf, out, capacity, &count); + error = collect_leaf(leaf, out, capacity, &count, + coalesce_contexts); } if (error) break; @@ -79,6 +112,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, return count; } +int asahi_g17_collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity) +{ + return collect_fences(head, out, capacity, false); +} + +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity) +{ + return collect_fences(head, out, capacity, true); +} + void asahi_g17_put_fence(struct dma_fence *fence) { dma_fence_put(fence); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.h b/drivers/gpu/drm/asahi/g17/sync_input.h index 44d3e338c197..9fd39e223cf3 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.h +++ b/drivers/gpu/drm/asahi/g17/sync_input.h @@ -13,6 +13,9 @@ struct asahi_g17_fence_leaf { int asahi_g17_collect_fences(struct dma_fence *head, struct asahi_g17_fence_leaf *out, size_t capacity); +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity); void asahi_g17_put_fence(struct dma_fence *fence); struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t count); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 33ac3f94d4f2..4d7629a8ffe7 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -6,14 +6,16 @@ use kernel::{bindings, dma_fence::{Fence, RawDmaFence}, prelude::*}; #[repr(C)] -pub(super) struct Leaf { - pub(super) fence: *mut bindings::dma_fence, - pub(super) status: i32, +pub(crate) struct Leaf { + pub(crate) fence: *mut bindings::dma_fence, + pub(crate) status: i32, } unsafe extern "C" { fn asahi_g17_collect_fences(head: *mut bindings::dma_fence, out: *mut Leaf, capacity: usize) -> i32; + fn asahi_g17_collect_fences_coalesced(head: *mut bindings::dma_fence, + out: *mut Leaf, capacity: usize) -> i32; fn asahi_g17_put_fence(fence: *mut bindings::dma_fence); fn asahi_g17_merge_fences(fences: *const *mut bindings::dma_fence, count: usize) -> *mut bindings::dma_fence; @@ -42,27 +44,40 @@ impl Drop for Leaf { } } -/// Allocation, unsupported containers, or a large prefix retain normal waits. -pub(super) fn collect(input: &Fence) -> Option> { +fn collect_with( + input: &Fence, + collector: unsafe extern "C" fn(*mut bindings::dma_fence, *mut Leaf, usize) -> i32, +) -> Option> { let mut capacity = 4; loop { let mut leaves = KVec::with_capacity(capacity, GFP_KERNEL).ok()?; // SAFETY: The input owns its fence. The C helper writes at most capacity // fully initialized records and releases every reference on failure. - let count = unsafe { - asahi_g17_collect_fences(input.raw(), leaves.as_mut_ptr(), capacity) - }; + let count = unsafe { collector(input.raw(), leaves.as_mut_ptr(), capacity) }; if count == ENOSPC.to_errno() && capacity < 128 { capacity = (capacity * 4).min(128); continue; } - if count < 0 { return None; } + if count < 0 { + return None; + } // SAFETY: The helper returned this many initialized, owned records. unsafe { leaves.set_len(count as usize) }; return Some(leaves); } } +/// Allocation, unsupported containers, or a large prefix retain normal waits. +pub(crate) fn collect(input: &Fence) -> Option> { + collect_with(input, asahi_g17_collect_fences) +} + +/// Like [`collect`], coalescing unsignalled non-error leaves sharing a `dma_fence` context to +/// their latest sequence number so deep timeline chains stay bounded by distinct contexts. +pub(crate) fn collect_coalesced(input: &Fence) -> Option> { + collect_with(input, asahi_g17_collect_fences_coalesced) +} + use super::fence::Submission; use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index db053aef6227..0ffd1dd52198 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 62fb9222460f..e0099ee4862e 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 4b8523235201..27093fdfdf1e 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,7 +697,10 @@ 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 fn check_render_one( @@ -744,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; @@ -777,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; @@ -834,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(); @@ -874,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( @@ -911,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); @@ -957,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)); @@ -974,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-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index c0dd3e2616dc..0843277bc936 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -3,7 +3,9 @@ """Exercise production DMA-fence lockdep guard and Timeline off-pending signalling.""" from common import kernel_root, output_dir, rustc, sha import json +import os import pathlib +import shlex import subprocess import tempfile @@ -92,6 +94,10 @@ def extract_function(text, name): fence_source.index('/// Inline storage for the common 0-2 input fences'): fence_source.index('/// Reads a retained dependency') ] +fw_waits_src = fence_source[ + fence_source.index('/// Maximum distinct cross-queue firmware waits'): + fence_source.index('/// Fence operations of G16 job fences.') +] syncs_src = fence_source[ fence_source.index('/// The syncs of one SUBMIT.'): ] @@ -417,9 +423,92 @@ def extract_function(text, name): assert_eq!(log2.borrow().failed, vec![Fence(ENOMEM.0)]); } } + +mod fw_waits_test { + use super::{Error, Result, GFP_KERNEL}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + + const E2BIG: Error = Error(-7); + + pub(crate) struct QueueState(u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + impl core::ops::DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } + } + + FW_WAITS_SRC + + #[test] + fn fw_waits_coalesces_deep_two_queue_timeline_chain_and_merges_engines() { + let q0 = Arc::new(QueueState(0)); + let q1 = Arc::new(QueueState(1)); + let mut waits = FwWaits::Empty; + // 64 alternating timeline hops across 2 queues coalesce to 2 per-queue entries. + for hop in 1..=64u64 { + let (q, r, c) = if hop % 2 == 1 { + (q0.clone(), Some((hop + 1) / 2), Some(hop)) + } else { + (q1.clone(), None, Some(hop / 2)) + }; + let origin = Arc::new(FenceOrigin::new(1, 7, q, [r, c])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), 2); + let w0 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q0)).unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w0.last_ordinal, [Some(32), Some(63)]); + assert_eq!(w1.last_ordinal, [None, Some(32)]); + + // Merging an earlier render-only origin with a later compute-only origin on q1 keeps both. + waits + .push_unique(Arc::new(FenceOrigin::new(1, 7, q1.clone(), [Some(5), None]))) + .unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w1.last_ordinal, [Some(5), Some(32)]); + } + + #[test] + fn fw_waits_caps_distinct_queues_at_max_fw_waits() { + let mut waits = FwWaits::Empty; + for idx in 0..MAX_FW_WAITS { + let q = Arc::new(QueueState(idx as u32)); + let origin = Arc::new(FenceOrigin::new(1, 7, q, [None, Some(1)])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), MAX_FW_WAITS); + let extra = Arc::new(FenceOrigin::new( + 1, + 7, + Arc::new(QueueState(99)), + [None, Some(1)], + )); + assert_eq!(waits.push_unique(extra), Err(E2BIG)); + } +} '''.replace('SIGNAL_BATCH_LINE', signal_batch_line).replace( 'TIMELINE_COMPLETE_FN', timeline_complete_fn ).replace('INPUT_FENCES_SRC', input_fences_src).replace( + 'FW_WAITS_SRC', fw_waits_src +).replace( 'SYNCS_SRC', syncs_src.replace('crate::g17::', 'g17::') ) @@ -439,9 +528,247 @@ def extract_function(text, name): if result.returncode: raise SystemExit(result.returncode) +# Exercise the actual production g17/sync_input.c collector against lightweight C dma_fence +# and dma_fence_chain shims to prove deep 2-queue timeline chains coalesce without -ENOSPC, +# skip signalled leaves, and preserve error leaves. +sync_input_c = root / 'drivers/gpu/drm/asahi/g17/sync_input.c' +sync_input_dir = sync_input_c.parent +c_harness = r''' +#include +#include +#include +#include +#include +#include +#include + +typedef uint64_t u64; +#define ASAHI_G17_SYNC_SCOPE_H 1 +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define GFP_KERNEL 0 + +struct dma_fence { + uint64_t context; + uint64_t seqno; + int status; + int refcount; + bool is_chain; + bool is_container; + struct dma_fence *chain_next; + struct dma_fence *chain_fence; +}; + +struct dma_fence_unwrap { + struct dma_fence *chain; + struct dma_fence *array; + unsigned int index; +}; + +static inline struct dma_fence *dma_fence_get(struct dma_fence *f) +{ + if (f) + ++f->refcount; + return f; +} + +static inline void dma_fence_put(struct dma_fence *f) +{ + if (f) { + assert(f->refcount > 0); + --f->refcount; + } +} + +static inline int dma_fence_get_status(struct dma_fence *f) +{ + return f ? f->status : 1; +} + +static inline bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) +{ + return f1->seqno > f2->seqno; +} + +static inline bool dma_fence_is_container(struct dma_fence *f) +{ + return f && (f->is_chain || f->is_container); +} + +static inline struct dma_fence *dma_fence_unwrap_first(struct dma_fence *head, + struct dma_fence_unwrap *cursor) +{ + cursor->chain = NULL; + cursor->array = NULL; + cursor->index = 0; + if (!head) + return NULL; + if (head->is_chain) { + cursor->chain = dma_fence_get(head); + return head->chain_fence; + } + return head; +} + +static inline struct dma_fence *dma_fence_unwrap_next(struct dma_fence_unwrap *cursor) +{ + struct dma_fence *next; + + if (!cursor->chain) + return NULL; + next = cursor->chain->chain_next; + dma_fence_put(cursor->chain); + if (!next) { + cursor->chain = NULL; + return NULL; + } + cursor->chain = dma_fence_get(next); + return next->chain_fence; +} + +#define dma_fence_unwrap_for_each(fence, cursor, head) \ + for ((fence) = dma_fence_unwrap_first((head), (cursor)); (fence); \ + (fence) = dma_fence_unwrap_next((cursor))) + +static inline void *kmalloc_array(size_t n, size_t size, int flags) +{ + (void)flags; + return calloc(n, size); +} + +static inline void kfree(void *p) +{ + free(p); +} + +static inline struct dma_fence *__dma_fence_unwrap_merge(unsigned int n, + struct dma_fence **f, + struct dma_fence_unwrap *c) +{ + (void)n; + (void)f; + (void)c; + return NULL; +} + +static inline bool asahi_g17_is_scope(struct dma_fence *f) +{ + (void)f; + return false; +} + +static inline unsigned int asahi_g17_scope_children(struct dma_fence *f, + struct dma_fence *out[2]) +{ + (void)f; + (void)out; + return 0; +} + +#include "sync_input.h" +#include "sync_input.c" + +int main(void) +{ + enum { HOPS = 256 }; + struct dma_fence leaves[HOPS]; + struct dma_fence chains[HOPS]; + struct asahi_g17_fence_leaf out[4]; + int n, i; + + /* 256 alternating unsignalled hops across 2 contexts (10 and 20). */ + memset(leaves, 0, sizeof(leaves)); + memset(chains, 0, sizeof(chains)); + for (i = 0; i < HOPS; ++i) { + leaves[i].context = (i % 2 == 0) ? 10 : 20; + leaves[i].seqno = (uint64_t)(i / 2 + 1); + leaves[i].status = 0; + leaves[i].refcount = 1; + + chains[i].is_chain = true; + chains[i].refcount = 1; + chains[i].chain_fence = &leaves[i]; + chains[i].chain_next = (i > 0) ? &chains[i - 1] : NULL; + } + + /* Coalesced collector fits a 256-hop 2-queue timeline chain into capacity=4 with 2 leaves. */ + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 2); + assert((out[0].fence == &leaves[HOPS - 1] && out[1].fence == &leaves[HOPS - 2]) || + (out[1].fence == &leaves[HOPS - 1] && out[0].fence == &leaves[HOPS - 2])); + for (i = 0; i < n; ++i) { + assert(out[i].status == 0); + asahi_g17_put_fence(out[i].fence); + } + + /* Non-coalesced collector still sees distinct unsignalled leaves and hits -ENOSPC at cap=4. */ + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == -ENOSPC); + + /* Already-signalled leaves (status > 0) are skipped by both collectors. */ + for (i = 0; i < HOPS; ++i) + leaves[i].status = 1; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 0); + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == 0); + + /* Error leaf (status < 0) is preserved even when a later same-context leaf is unsignalled. */ + leaves[5].status = -5; + leaves[HOPS - 1].status = 0; + leaves[HOPS - 2].status = 0; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 3); + { + bool saw_err = false, saw_ctx10 = false, saw_ctx20 = false; + for (i = 0; i < n; ++i) { + if (out[i].fence == &leaves[5] && out[i].status == -5) + saw_err = true; + else if (out[i].fence == &leaves[HOPS - 2] && out[i].status == 0) + saw_ctx10 = true; + else if (out[i].fence == &leaves[HOPS - 1] && out[i].status == 0) + saw_ctx20 = true; + asahi_g17_put_fence(out[i].fence); + } + assert(saw_err && saw_ctx10 && saw_ctx20); + } + + /* Every refcount returns cleanly to 1 (no leaks or double puts). */ + for (i = 0; i < HOPS; ++i) { + assert(leaves[i].refcount == 1); + assert(chains[i].refcount == 1); + } + printf("sync_input C coalescing tests passed (256-hop chain -> 2 leaves, error preserved)\n"); + return 0; +} +''' + +with tempfile.TemporaryDirectory(prefix='m4-c-sync-input-') as directory: + directory = pathlib.Path(directory) + (directory / 'linux').mkdir() + for hdr in ('dma-fence.h', 'dma-fence-unwrap.h', 'slab.h', 'types.h'): + (directory / 'linux' / hdr).write_text('/* host shim */\n') + (directory / 'linux' / 'errno.h').write_text('#define ENOSPC 28\n#define EOPNOTSUPP 95\n') + (directory / 'sync_scope.h').write_text('/* host shim */\n') + c_unit = directory / 'test_sync_input.c' + c_unit.write_text(c_harness) + c_bin = directory / 'test_sync_input' + cc = shlex.split(os.environ.get('CC', 'cc')) + for command in [ + cc + ['-Wall', '-Wextra', '-Werror', '-I', str(directory), '-I', str(sync_input_dir), + str(c_unit), '-o', str(c_bin)], + [str(c_bin)], + ]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + logs += result.stdout + print(result.stdout, end='') + (out / 'fence-signalling.log').write_text(logs) + if result.returncode: + raise SystemExit(result.returncode) + (out / 'fence-signalling.json').write_text(json.dumps({ - 'passed': True, 'tests': 8, 'negative_compile_checks': 1, 'cpu_only': True, - 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants and g16 Timeline::complete() off-pending FIFO batch signalling.', + 'passed': True, 'tests': 11, 'negative_compile_checks': 1, 'cpu_only': True, + 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants, g16 Timeline::complete() off-pending FIFO batch signalling, FwWaits per-queue coalescing, and g17/sync_input.c chain coalescing.', 'source_sha256': sha(production), 'timeline_source_sha256': sha(fence_source_path), + 'sync_input_source_sha256': sha(sync_input_c), }, indent=2) + '\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py index 6cbe422995df..fe6818252cc8 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py @@ -32,8 +32,8 @@ def function_from(text, marker_text): def function(text, name): return function_from(text, 'fn ' + name + '(') -queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'is_compute_retired']) -methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired']) +queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'cancelled_through', 'is_compute_retired']) +methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired', 'waits_on_queue']) push_method = function_from(source, 'pub(crate) fn push(&mut self, job: Arc') fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies']) harness = r''' @@ -102,7 +102,13 @@ def function(text, name): mod command { pub(crate) use super::{Order, COMPUTE}; } struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2],compute_ooo:AtomicU64 } impl QueueState { QUEUE_METHODS } -struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,orders:Vec,queue:Arc,full_retired:AtomicU64,terminal_retired:AtomicBool } +struct FenceOrigin { queue:Arc, last_ordinal:[Option;2], failed:AtomicBool } +impl FenceOrigin { + fn new(queue:Arc, last_ordinal:[Option;2])->Arc { Arc::new(Self{queue,last_ordinal,failed:AtomicBool::new(false)}) } + fn mark_failed(&self) { self.failed.store(true,Ordering::Release); } + fn is_failed(&self)->bool { self.failed.load(Ordering::Acquire) } +} +struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,origin:Arc,fw_waits:Vec>,orders:Vec,queue:Arc,full_retired:AtomicU64,terminal_retired:AtomicBool } struct Shared { crashed:AtomicBool,sleeping:AtomicBool,recovering:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } impl Shared { fn new()->Arc { @@ -183,9 +189,10 @@ def function(text, name): job_with_orders(id,status,inputs,orders,Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)})) } fn job_with_orders(id:u64,status:Arc,inputs:Vec,orders:Vec,queue:Arc)->Arc { + let origin=FenceOrigin::new(queue.clone(),[None,Some(orders.len() as u64)]); Arc::new(Job{id,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)},started:AtomicBool::new(false),accepted:AtomicBool::new(true), - fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,orders,queue, + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,origin,fw_waits:vec![],orders,queue, full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false)}) } #[test] @@ -581,6 +588,56 @@ def function(text, name): assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),4); assert_eq!(queue.compute_ooo.load(Ordering::Acquire),0); } +#[test] +fn fw_wait_defers_until_producer_queue_publishes_and_propagates_failure() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders,q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2.clone(), + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert!(cons.waits_on_queue(&q1)); + assert!(!cons.waits_on_queue(&q2)); + // Producer not yet published -> consumer defers with EAGAIN. + assert_eq!(cons.check_command_dependencies(0),Err(EAGAIN)); + // Once producer publishes ordinal 1, consumer is ready for firmware handoff. + q1.published[COMPUTE].store(1,Ordering::Release); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + // Producer failure marks origin failed and cancels consumer with ECANCELED. + prod.latch_failure(ECANCELED); + assert!(prod.origin.is_failed()); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} +#[test] +fn fw_wait_cancels_when_producer_queue_cancels_ordinal() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[AtomicU64::new(0),AtomicU64::new(1)],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders.clone(),q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2, + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + q1.cancel(&p_orders,0); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} '''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::').replace('super::command::','command::')).replace('PUSH_METHOD', push_method) with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory: @@ -592,6 +649,6 @@ def function(text, name): (OUT/'job-failure-host.log').write_text(result.stdout+result.stderr) (OUT/'job-failure-host.json').write_text(json.dumps({ 'source':str(SOURCE),'sha256':hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result':'pass','test_groups':23, + 'result':'pass','test_groups':25, 'limitations':'Production Job methods with host VM/fence mocks; actual DRM scheduler and firmware publication gates require kernel and execution integration validation.' },indent=2)+'\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 5a7a7b3e5ba3..03099634f7b6 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -213,6 +213,7 @@ def item(declaration, text=source): sleeping: AtomicBool, evented: AtomicBool, publish_wake: AtomicBool, + closed_vm_reclaim: AtomicBool, rearmed: Cell, idle_power_polls: Cell, rearm_soon: Cell, @@ -224,6 +225,7 @@ def item(declaration, text=source): sleeping: AtomicBool::new(false), evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), rearmed: Cell::new(0), idle_power_polls: Cell::new(0), rearm_soon: Cell::new(0), @@ -262,14 +264,32 @@ def item(declaration, text=source): } } +#[derive(Default)] +struct Pools { + reclaim_calls: u32, + reclaim_remaining: bool, +} +impl Pools { + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } +} + #[derive(Default)] struct Slots { scrub_woke: AtomicBool, + reclaim_calls: u32, + reclaim_remaining: bool, } impl Slots { fn take_scrub_woke(&self) -> bool { self.scrub_woke.swap(false, Ordering::AcqRel) } + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } } struct Firmware { @@ -280,6 +300,7 @@ def item(declaration, text=source): events: Events, recovery: Recovery, power: Power, + pools: Pools, slots: Slots, last_housekeeping_ns: u64, last_aux_drain_ns: u64, @@ -333,6 +354,7 @@ def item(declaration, text=source): events: Events::default(), recovery: Recovery::default(), power: Power::default(), + pools: Pools::default(), slots: Slots::default(), last_housekeeping_ns: 0, last_aux_drain_ns: 0, @@ -410,12 +432,57 @@ def item(declaration, text=source): self.ta_pending } + __RECLAIM_CLOSED_VM_SLOTS__ __POLL_STEP__ __OLDEST_TERMINAL_EVENTS__ __TA_WAVE_READY__ __OLDEST_STAMP_REACHED__ } +#[test] +fn idle_poll_step_reclaims_closed_vm_slots_and_rearms_while_remaining() { + CLOCK.with(|c| c.set(1_000_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.engine.shared = Some(shared.clone()); + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared.publish_wake.store(true, Ordering::Release); + fw.pools.reclaim_remaining = true; + + let (mut retry_tail, mut hk_deferred, mut done) = (false, false, vec![]); + let busy = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert!(!busy); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (1, 1)); + assert!(!shared.publish_wake.load(Ordering::Acquire)); + assert!( + shared.closed_vm_reclaim.load(Ordering::Acquire), + "remaining undisplaced closed VM keeps reclaim armed" + ); + + // Once remaining clears, idle poll clears closed_vm_reclaim and later polls skip scans. + fw.pools.reclaim_remaining = false; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + + // Idle submit_locked also reclaims before publish_checked when armed. + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared + .submit_locked(&mut fw, Arc::new(Job { id: 9 }), &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (3, 3)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); +} + #[test] fn submit_locked_retires_inline_on_reached_stamp_without_full_housekeeping() { CLOCK.with(|c| c.set(100_000)); @@ -1501,6 +1568,7 @@ def item(declaration, text=source): for token, decl in { '__SUBMIT_LOCKED__': 'fn submit_locked(', + '__RECLAIM_CLOSED_VM_SLOTS__': 'pub(crate) fn reclaim_closed_vm_slots(', '__POLL_STEP__': 'pub(crate) fn poll_step(', '__RUN_HOUSEKEEPING__': 'pub(crate) fn run_housekeeping(', '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', @@ -1537,7 +1605,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 21, + 'tests': 22, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', 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 0942af9db869..8cc61598bf61 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 e01576c044d1..8c32b1ff744a 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_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} @@ -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__ @@ -152,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;} @@ -162,9 +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_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_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} @@ -172,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())} @@ -698,8 +703,15 @@ def item(declaration): } } +mod fence { + pub const MAX_FW_WAITS: usize = 8; + pub struct FwWait { + pub queue: std::sync::Arc, + pub last_ordinal: [Option; 2], + } +} #[derive(Copy,Clone)]struct Order{engine:usize,sequence:u64,wait_through:[Option;2]} -struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources} +struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources,fw_waits:Vec} impl QueueBehindJob{ fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} fn command_order(&self,index:u32)->Option{ @@ -718,15 +730,20 @@ 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{ 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} } @@ -737,6 +754,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_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 { @@ -788,7 +807,7 @@ def item(declaration): 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})}], 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, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let j1=mk(1,vm1.clone(),q1.clone(),false); let j2=mk(2,vm1.clone(),q1.clone(),false); @@ -796,7 +815,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}, }; @@ -833,7 +852,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access})], order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let timed=mk(1,q1.clone(),true,None,None); let query_copy=mk(2,q1.clone(),true,None,Some(1)); @@ -842,7 +861,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}, }; @@ -856,11 +875,11 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); 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}, }; @@ -876,7 +895,7 @@ def item(declaration): 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})}], 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, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r1=mk(1,vm1.clone(),true); let r2=mk(2,vm1.clone(),true); @@ -884,7 +903,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}, }; @@ -921,14 +940,14 @@ def item(declaration): 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})}], 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, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let vm1_r=mk(1,vm1.clone(),q1.clone(),true); let vm1_c=mk(2,vm1.clone(),q1.clone(),false); 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, }; @@ -963,7 +982,7 @@ def item(declaration): 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})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r1=mk(1,q1.clone(),true,1,[None,None]); let c1=mk(2,q1.clone(),false,1,[Some(1),None]); @@ -973,8 +992,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}, @@ -1000,7 +1019,7 @@ def item(declaration): Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, Order{engine:command::COMPUTE,sequence:3,wait_through:[None,None]}, ], - dependency:Ok(()),resources:Resources, + dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_wait_c2=mk(7,q1.clone(),true,3,[None,Some(2)]); let r_wait_c3=mk(8,q1.clone(),true,4,[None,Some(3)]); @@ -1010,7 +1029,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}, @@ -1035,7 +1054,7 @@ def item(declaration): 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})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_initbm=mk(1,true,1,[None,None]); let c_after_r=mk(2,false,1,[Some(1),None]); @@ -1043,7 +1062,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, }]}, @@ -1077,19 +1096,19 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_job=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q_rend.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); 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}, @@ -1100,7 +1119,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)); @@ -1114,7 +1133,7 @@ def item(declaration): 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})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,false,1,[None,None]); let c2=mk(2,false,2,[None,None]); @@ -1127,7 +1146,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}, @@ -1153,21 +1172,21 @@ def item(declaration): Order{engine:command::RENDER,sequence:2,wait_through:[Some(1),None]}, Order{engine:command::RENDER,sequence:3,wait_through:[Some(2),None]}, ], - dependency:Ok(()),resources:Resources, + dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let next_r=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:4,wait_through:[Some(3),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut r_fs=[0u32;16]; r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; 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}, @@ -1182,7 +1201,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}))); @@ -1192,19 +1211,19 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:5,wait_through:[Some(4),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_fold_b=Arc::new(QueueBehindJob{ id:11,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:6,wait_through:[Some(5),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); 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}))); @@ -1226,7 +1245,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_live=mk(1); let next_r=mk(2); @@ -1237,7 +1256,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, }]}, @@ -1272,7 +1291,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, - extra_orders:vec![],dependency:dep,resources:Resources, + extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], }); let r_live=mk(1,vm1.clone(),true,Ok(()),false,[None,None]); let r_same=mk(2,vm1.clone(),true,Ok(()),false,[None,None]); @@ -1282,7 +1301,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, }]}, @@ -1616,7 +1635,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,vm1.clone(),q1.clone(),1); let c2=mk(2,vm1.clone(),q1.clone(),2); @@ -1628,27 +1647,30 @@ 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], (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,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], (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], (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), 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. 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], (1u32 << 24) - 1, 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], (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)); @@ -1661,7 +1683,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,wait_c]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,1,None); let c2=mk(2,2,None); @@ -1671,12 +1693,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, }, @@ -1689,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), 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), 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, @@ -1706,12 +1728,79 @@ 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, (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); assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None, None])); } + #[test]fn cross_queue_fw_waits_resolve_stamps_reuse_compute_pipe_and_guard_timestamps(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Queue::new(0,2); + let q2=Queue::new(0,2); + 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})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r1=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + 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})], + 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)]}], + }); + 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})], + 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)]}], + }); + let host=QueueBehindHost{ + 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,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,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}, + }; + // 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,(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; + // non-query compute queues directly behind q1 in firmware. + assert!(!host.can_queue_behind(&c2_query_wait_q1)); + assert!(host.can_queue_behind(&c2_wait_q1)); + // Once q1 retires, fw_waits resolves to no barriers. + q1.completed[command::COMPUTE].store(1,Ordering::Release); + q1.completed[command::RENDER].store(1,Ordering::Release); + assert_eq!(host.wait_compute_stamps_for(&c2_wait_q1,None),Ok([None,None])); + assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(None)); + } } #[allow(non_camel_case_types, deprecated)] mod queue_limits_scope { @@ -1844,6 +1933,7 @@ def item(declaration): commands: Vec, orders: Vec, inputs: Vec, + fw_waits: Vec<()>, terminal_retired: AtomicBool, } impl Job { @@ -1865,6 +1955,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; let ok_job = mk( @@ -1925,6 +2016,15 @@ def item(declaration): 2, ); assert!(!cancelled.can_fold_horizon_job(2)); + let mut with_fw_wait = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![], + 0, + ); + with_fw_wait.fw_waits.push(()); + assert!(!with_fw_wait.can_fold_horizon_cmd(0, 2)); + assert!(!with_fw_wait.can_fold_horizon_job(2)); } #[test] @@ -1940,6 +2040,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; let multi = mk( @@ -1986,6 +2087,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; // Two-pass render job waiting on primary flight pass 1 and its own pass 2. @@ -2417,7 +2519,7 @@ def item(declaration): '__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::")) + 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::")) unit = output / 'publication.rs' unit.write_text(harness) log = '' 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 000000000000..bfc62d7c4c9e --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -0,0 +1,602 @@ +#!/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; 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 + 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}"); + } + // 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) || (flag..flag + 4).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); + // 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); + 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); + // 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); + 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 5f3741b9824d..2df865d4f856 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -44,9 +44,10 @@ def module(text, name): pub const ETIMEDOUT:Error=Error(110);pub const ERESTARTSYS:Error=Error(512); pub const GFP_KERNEL:u32=0; pub type Result = std::result::Result; +macro_rules! init { ($($tt:tt)*) => { $($tt)* }; } pub mod prelude {pub use crate::{Result,KVec,KBox,GFP_KERNEL,EINVAL,EAGAIN,E2BIG,EBUSY,EOVERFLOW,EIO,ETIMEDOUT,ERESTARTSYS};} pub struct KBox(Box); -implKBox{pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))}} +implKBox{pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} pub fn init(x:T,_:u32)->Result{Ok(Self(Box::new(x)))}} implstd::ops::Deref for KBox{type Target=T;fn deref(&self)->&T{&self.0}} implstd::ops::DerefMut for KBox{fn deref_mut(&mut self)->&mut T{&mut self.0}} pub struct KVec(Vec); @@ -93,27 +94,52 @@ 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 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} impl FwObject{ - pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false)},0)} - pub fn write(&self,o:usize,b:&[u8])->Result{let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} + pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)} + pub fn write(&self,o:usize,b:&[u8])->Result{self.write_bytes.fetch_add(b.len(),std::sync::atomic::Ordering::Relaxed);let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} pub fn fill(&self,o:usize,v:u8,n:usize)->Result{if self.fail_fill.swap(false,std::sync::atomic::Ordering::Relaxed){return Err(EIO);}self.fills.lock().unwrap().push((o,n));let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+n].fill(v);Ok(())} pub fn w32(&self,o:usize,v:u32)->Result{self.write(o,&v.to_le_bytes())} pub fn w64(&self,o:usize,v:u64)->Result{self.write(o,&v.to_le_bytes())} pub fn r32(&self,o:usize)->Result{let d=self.data.lock().unwrap();Ok(u32::from_le_bytes(d[self.offset+o..self.offset+o+4].try_into().unwrap()))} pub fn snapshot(&self)->Vec{self.data.lock().unwrap().clone()} } + pub struct FwLease(pub crate::cleanup::Deferred); + impl FwLease { + pub fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Arc::new(Self(crate::cleanup::Deferred::new(objects)?), 0) + } + } pub struct Factory; - impl Factory{pub fn objects(&self,_:&())->Objects{Objects::new()}} - pub struct Objects{pub objects:Vec>,next:u64} + 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 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),k).unwrap()}); + PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c + } impl Objects{ - pub fn new()->Self{Self{objects:vec![],next:0xfffffc2001000000}} + 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=self.next;self.next+=bytes as u64+0x4000;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)},0)?;self.objects.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 { @@ -138,8 +164,15 @@ def module(text, name): pub struct PassRefs{pub ta_work:u64,pub ta_work_gva:u64,pub fs_work:u64,pub fs_work_gva:u64,pub ta_seq:u64,pub fs_seq:u64,pub scene:u64,pub tpc_gva:u64,pub tilemap_gva:u64,pub heap_gva:u64,pub scene_user_gva:u64,pub scene_list:u64,pub pre_gva:[u64;3],pub fs_scratch_gva:u64,pub aux_gva:u64,pub its:u64,pub ta_scratch:u64,pub tpc_fw:u64,pub scratch_fw:u64} } pub mod vm { - use crate::{mmu,sync::Arc};use core::sync::atomic::Ordering; - pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:()} + use crate::{mmu,sync::Arc}; + use core::sync::atomic::{AtomicBool,Ordering}; + pub struct MockVm(AtomicBool); + impl MockVm{ + pub fn new()->Self{Self(AtomicBool::new(false))} + pub fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)} + pub fn close(&self){self.0.store(true,Ordering::Release);} + } + pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -156,7 +189,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)] @@ -169,10 +202,40 @@ def module(text, name): match self{Self::Base(a)=>Some((a.passes.get(k)?,PassDirty{tpc:a.tpc_dirty.get(k)?,tilemap:a.tilemap_dirty.get(k)?,tilemap_last:a.tilemap_last.get(k)?,tilemap_clean:a.tilemap_clean.get(k)?,heap:a.heap_dirty.get(k)?}))} } } + std::thread_local!{ + pub static COMPUTE_OWNER_ARENA:std::cell::RefCell< + Option>, + >=const{std::cell::RefCell::new(None)}; + pub static COMPUTE_OWNER_ARENAS:std::cell::RefCell< + Option>>, + >=const{std::cell::RefCell::new(None)}; + } 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_arena(&self,_k:usize)->Option>{None} + 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(idx).cloned())) + .or_else(||COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone())) + } pub fn render_arena(&self)->Option>{self.render.clone()} pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} pub fn render_pass(&self,k:usize)->Result<&super::slots::PassSlot>{self.render.as_deref().and_then(|r|r.passes.get(k)).ok_or(EINVAL)} @@ -184,6 +247,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)}} @@ -200,6 +264,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; } @@ -216,10 +281,14 @@ def module(text, name): heap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], } } + fn find_va(va:u64)->sync::Arc{ + g16::object::ALL_OBJECTS.with(|a|a.borrow().iter().find(|obj|obj.va==va).unwrap().clone()) + } fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); - for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,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)} + 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, &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<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} @@ -267,7 +336,7 @@ def module(text, name): } #[test]fn production_allocations_are_aligned_disjoint_and_in_mesa_hole(){ let mut o=Objects::new();let slots=Slots::new().unwrap();let arena=arenas(&mut o); - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let mut aliases=Vec::new(); for a in &o.objects{if let Some(g)=a.gva{assert_eq!(a.client_leaf,Some(__PRIVATE_RW__),"private GPU alias must match qualified J713 NC RW PTE");let base=g-a.offset as u64;assert_eq!(base&0x3fff,0);assert_eq!(a.mapped&0x3fff,0);assert!(base>=0x7000000000);assert!(base+a.mapped as u64<=0x7100000000);aliases.push((base,base+a.mapped as u64));}} aliases.push((0x1000000000,0x1000010000)); // Per-VM context store. @@ -276,8 +345,65 @@ def module(text, name): // One PB heap per VM, shared by both render allocators. assert_eq!(aliases.len(),42); } + #[test]fn firmware_cached_render_records_are_device_lifetime_and_never_owned_by_vm_arenas(){ + use g16::object::{Class,Placement,Request}; + let req=|class,client:Option<(u64,u64)>,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!(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(),p.ta_work.clone(),p.fs_work.clone()]; + let (ra,rb)=(records(&pa),records(&pb)); + 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.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(); + 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..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..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 + // 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().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 { @@ -285,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 { @@ -313,11 +439,11 @@ def module(text, name): } } #[test]fn allocator_metadata_is_firmware_only_and_shared_state_keeps_real_backing(){ - let mut o=Objects::new();let pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let read64=|obj:&g16::object::FwObject,at:usize|->u64{obj.r32(at).unwrap()as u64|((obj.r32(at+4).unwrap()as u64)<<32)}; for k in 0..2 { let refs=pools.allocator_refs_for(k).unwrap(); - let descriptor=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let descriptor=find_va(refs.uma_mgr[0]); let auxiliary=o.objects.iter().find(|obj|obj.va+0x100==refs.uma_aux[0]).unwrap(); assert_eq!(descriptor.class,g16::object::Class::Fw); assert_eq!(descriptor.gva,None);assert_eq!(descriptor.client_leaf,None); @@ -340,8 +466,8 @@ def module(text, name): } assert_eq!(metadata,descriptor.snapshot()); // Freelist and pool-table pointers still select writable client mappings. - let state_va=read64(descriptor,g16::fw::graph::manager::FREELIST); - let list_va=read64(descriptor,g16::fw::graph::manager::POOL_TABLE); + let state_va=read64(&descriptor,g16::fw::graph::manager::FREELIST); + let list_va=read64(&descriptor,g16::fw::graph::manager::POOL_TABLE); for va in [list_va,state_va] { let shared=o.objects.iter().find(|obj|obj.gva==Some(va)).unwrap(); assert_eq!(shared.class,g16::object::Class::Shared); @@ -367,11 +493,11 @@ def module(text, name): s.publish(&mut c).unwrap();s.quarantine(&mut c);assert!(s.compute_exhausted()); } #[test]fn production_render_descriptors_preserve_firmware_bytes_and_exact_counter(){ - let mut o=Objects::new();let mut pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let mut pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let a=pools.prepare(0,1).unwrap();assert!(a.init_buffer);assert_eq!(a.uma_submitted,2); assert!(!pools.retired(0).unwrap());pools.publish_batch(0,2,1).unwrap(); assert!(pools.publish_batch(0,2,1).is_err());assert!(pools.prepare(0,2).is_err()); - let d=o.objects.iter().find(|o|o.va==a.uma_mgr[0]).unwrap(); + let d=find_va(a.uma_mgr[0]); d.w64(0x54,2).unwrap();d.w64(0x60,0x5a5aa5a5).unwrap(); let original=d.snapshot();assert!(pools.retired(0).unwrap()); let next=pools.prepare(0,2).unwrap();assert!(next.init_buffer);assert_eq!(next.uma_submitted,4); @@ -380,9 +506,15 @@ def module(text, name): #[test]fn cross_vm_evidence_counts_only_noted_publication(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); - let a=sync::Arc::new(g16::vm::VmState{id:100,slot:1,generation:1,vm:()},0).unwrap(); - let b=sync::Arc::new(g16::vm::VmState{id:101,slot:2,generation:1,vm:()},0).unwrap(); - let c=sync::Arc::new(g16::vm::VmState{id:102,slot:3,generation:9,vm:()},0).unwrap(); + let a=sync::Arc::new( + g16::vm::VmState{id:100,slot:1,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let b=sync::Arc::new( + g16::vm::VmState{id:101,slot:2,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let c=sync::Arc::new( + g16::vm::VmState{id:102,slot:3,generation:9,vm:g16::vm::MockVm::new()},0, + ).unwrap(); let mut claims=Claims::new(); for vm in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,vm).unwrap();s.publish(&mut claims).unwrap();s.note_published(&claims);s.retire(&mut claims).unwrap();} assert_eq!(s.stats.cross_vm_retargets,[0,0]); @@ -399,7 +531,11 @@ def module(text, name): s.release(&mut claims);s.note_published(&claims);assert_eq!(s.stats.cross_vm_retargets,[1,0]); } - fn vm(id:u64)->sync::Arc{sync::Arc::new(g16::vm::VmState{id,slot:id as u32,generation:1,vm:()},0).unwrap()} + fn vm(id:u64)->sync::Arc{ + sync::Arc::new( + g16::vm::VmState{id,slot:id as u32,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap() + } #[test]fn previous_vm_lease_survives_replacement_publication_until_full_retirement(){ let mut o=Objects::new();let arena=arenas(&mut o);let mut s=Slots::new().unwrap(); let a=vm(1);let b=vm(2);let c=vm(3);let mut claims=Claims::new(); @@ -603,18 +739,20 @@ def module(text, name): assert_eq!(g16::hw::sizes::RENDER_SLOTS, 48); assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 24); let mut o=Objects::new(); - let pools=PoolSet::new(&mut o).unwrap(); - for k in g16::hw::sizes::BASE_PB_SLOTS as u64..g16::hw::sizes::PB_SLOTS as u64 { - let ext=g16::pools::Allocator::new(&mut o,k,pools.heap()).unwrap(); - assert_eq!(ext.refs().unwrap().parameter_id,k as u32); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); + 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(),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 { - g16::slots::ComputeSlot::new(&mut o,k).unwrap(); + g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(); } 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"); @@ -624,7 +762,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!( @@ -651,7 +789,7 @@ def module(text, name): } #[test]fn decoupled_pb_allocator_supports_same_vm_pipelining_cross_vm_displacement_and_abort(){ - let mut o=Objects::new();let pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let vm1=vm(1);let vm2=vm(2);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); let e1=g16::pools::PbEpoch::new(&factory,&vm1,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); e1.prepare(0,0x70c0000000,2048).unwrap();e1.check_assignment(0).unwrap();e1.expose(); @@ -664,7 +802,7 @@ def module(text, name): let a1=pools.prepare_in_flight(0,1,false).unwrap(); assert_eq!(a1.uma_submitted,2); pools.publish_batch(0,2,1).unwrap();p.publish_flight(0); - let d0=o.objects.iter().find(|obj|obj.va==a1.uma_mgr[0]).unwrap(); + let d0=find_va(a1.uma_mgr[0]); d0.w64(0x54,2).unwrap(); p.retire_flight(0,&e1,b1,true).unwrap(); // Same-VM pipelining: 3 concurrent renders share slot 0 with cumulative uma_submitted (4, 6, 8). @@ -701,13 +839,42 @@ def module(text, name): #[test]fn render_allocators_use_distinct_uma_slots_within_firmware_window(){ let mut o=Objects::new(); - let pools=PoolSet::new(&mut o).unwrap(); + let f=g16::object::Factory; + 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(), + g16::slots::Placement::Base + ).err(), + Some(EINVAL) + ); + assert_eq!( + g16::pools::Allocator::new_at( + &mut o, + &f, + 0, + g16::hw::sizes::PB_SLOTS as u32, + 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 alloc=g16::pools::Allocator::new(&mut o,k as u64,pools.heap()).unwrap(); + 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(),g16::slots::Placement::Base).unwrap(); let refs=alloc.prepare_in_flight(1,false).unwrap(); assert_eq!(refs.parameter_id,k as u32); - let desc=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let desc=find_va(refs.uma_mgr[0]); let slot_id=desc.r32(8).unwrap(); let expected=g16::hw::engine::RENDER_UMA_SLOT+k as u32; assert_eq!(slot_id,expected); @@ -826,57 +993,61 @@ def module(text, name): e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); e }; + let warm=g16::hw::sizes::WARM_PB_SLOTS; + let ext=g16::hw::sizes::EXT_PB_SLOTS; + let total=g16::hw::sizes::PB_SLOTS; let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); - // Quarantine 4 slots (0..4): 2 healthy slots (4 and 5) remain for cross-VM switching. - for hang in 0..4usize { - let n=p.needed_slots(); - let slot=p.pick_slot_within(&vm1,false,n).unwrap(); - assert_eq!(slot,hang); + // A VM bound to [0, 1] with all 4 recovery spares (16..20) survives 4 hangs cleanly + // and keeps 2 healthy slots (18, 19) for cross-VM switching. + let vm_mask:u32=(1u32<<0)|(1u32<<1)|(((1u32< global pool exhaustion. + assert_ne!(p.quarantined_mask() & (1u32< global pool exhaustion. @@ -922,7 +1093,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); @@ -980,7 +1151,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. @@ -1028,10 +1199,11 @@ 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(); - 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; @@ -1082,7 +1254,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. @@ -1122,10 +1294,12 @@ def module(text, name): let mut o=Objects::new(); let mut units=KVec::new(); for k in 0..hw::sizes::COMPUTE_UNITS { - units.push(ComputeSlot::new(&mut o,k as u64).unwrap(),0).unwrap(); + units.push(ComputeSlot::new(&mut o,&g16::object::Factory,k as u64).unwrap(),0).unwrap(); } - let prep=ComputeArena{compute:units,render:None}; - let a=Arc::new(vm::VmState{id:1,slot:1,generation:1,vm:()},0).unwrap(); + 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(); let mut s=Slots::new().unwrap(); assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),hw::sizes::COMPUTE_UNITS as u32); // Claim 4 units into one Claims for a compute horizon, publish, and retire in order. @@ -1159,10 +1333,10 @@ 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)}; + 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. @@ -1208,7 +1382,7 @@ def module(text, name): s.release(&mut cancel2); // PoolSet::publish_batch advances submitted by 2 * renders and rejects invalid deltas. - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); assert_eq!(pools.publish_batch(0,0,0),Err(EINVAL)); assert_eq!(pools.publish_batch(0,4,3),Err(EINVAL)); assert_eq!(pools.publish_batch(0,6,3),Ok(())); @@ -1221,10 +1395,10 @@ 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)}; + 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. @@ -1367,20 +1541,27 @@ 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 + 448) * 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 + 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 * 5 * 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.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(){ @@ -1388,9 +1569,9 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut units=KVec::new(); for k in 0..4u64 { - units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + 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. @@ -1415,39 +1596,40 @@ def module(text, name): // A base-only (2-unit) VM can now claim displaced base unit 0 again. let mut base_units=KVec::new(); for k in 0..2u64 { - base_units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + 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 { - units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + 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)); @@ -1460,29 +1642,124 @@ 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,k).unwrap(),0).unwrap(); + 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 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(); 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)}; + 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. @@ -1514,7 +1791,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. @@ -1572,10 +1849,10 @@ 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())}; + 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< = Vec::new(); + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if idx < 3 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + live.push(c); + } + for _round in 0..4 { + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if _round > 0 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + let mut old = std::mem::replace(&mut live[idx], c); + s.retire(&mut old).unwrap(); + } + } + for mut c in live { + s.retire(&mut c).unwrap(); + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + } + + #[test]fn warm_pb_pool_keeps_sixteen_concurrent_vms_warm_and_handles_overflow(){ + let warm = g16::hw::sizes::WARM_PB_SLOTS; + assert_eq!(warm, 16); + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mk_epoch = |owner: &sync::Arc, slot: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + owner, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.check_assignment(slot).unwrap(); + e.expose(); + e + }; + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let vms: Vec<_> = (0..20usize).map(|i| vm(100 + i as u64)).collect(); + let mask_for = |i: usize| -> (u32, usize) { + let home = i % warm; + let alt = (home + 1) % warm; + ((1u32 << home) | (1u32 << alt), home) + }; + // Prime 16 VMs arriving in scrambled (reverse) order: each claims its own home slot! + let mut epochs = Vec::new(); + for i in (0..warm).rev() { + let (mask, home) = mask_for(i); + let slot = p.pick_slot_in_mask_blocks_mode(&vms[i], false, mask, home, 512, false).unwrap(); + assert_eq!(slot, home, "VM {i} must claim its home slot {home} despite reverse arrival"); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + epochs.push((i, e)); + } + // All 16 VMs now pipeline concurrently (behind=true) on 16 disjoint warm slots with 0 InitBM. + let mut binds = Vec::new(); + for &(i, ref _e) in &epochs { + let (mask, home) = mask_for(i); + assert!(p.can_pipeline_in_mask_blocks_mode(&vms[i], mask, home, 512, false)); + let slot = p.pick_slot_in_mask_blocks_mode(&vms[i], true, mask, home, 512, false).unwrap(); + assert_eq!(slot, home); + assert!(p.reusable_for_mask_mode(slot, &vms[i], mask, 512, false).is_some()); + let b = p.bind(slot, true); + p.publish_flight(slot); + binds.push((i, slot, b)); + } + for (idx, (i, slot, b)) in binds.into_iter().enumerate() { + assert_eq!(p.slot_inflight(slot), 1); + p.retire_flight(slot, &epochs[idx].1, b, true).unwrap(); + assert_eq!(p.slot_inflight(slot), 0); + let _ = i; + } + // Overflow d=20: VMs 16..20 share warm slots [0..4] cleanly on drained displaced rotation. + for i in warm..20 { + let (mask, home) = mask_for(i); + assert!(!p.can_pipeline_in_mask_blocks_mode(&vms[i], mask, home, 512, false)); + let slot = p.pick_slot_in_mask_blocks_mode(&vms[i], false, mask, home, 512, false).unwrap(); + assert_ne!(mask & (1u32 << slot), 0); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + } + } + + #[test]fn vm_affine_render_pass_claiming_keeps_sixteen_vms_warm_and_scales_tier1(){ + use g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots_for}; + // Steady 60 Hz depth-1 VM stays at BASE_RENDER_SLOTS even when 16 render VMs are active. + let (mut last, mut burst) = (0u64, 0u32); + let (eff, single) = target_render_slots_for(&mut last, &mut burst, 10_000_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 16); + assert_eq!((eff, single), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + // Bursting VM with 4 active render VMs stays at Tier 0 (8 slots). + for step in 1..=3u64 { + let (e, s) = target_render_slots_for(&mut last, &mut burst, 10_000_000 + step * 500_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 4); + if step < 3 { + assert_eq!((e, s), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + } else { + assert_eq!((e, s), (EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1)); + } + } + // Once active_render_vms reaches 8 or 16, a bursting VM expands effective target to Tier 1 + // (18 slots) while keeping single_vm_target at Tier 0 (8) so PB_HEAP_EXT_TIERS[1] stays off. + let (eff8, single8) = target_render_slots_for(&mut last, &mut burst, 12_000_000, 1, 0, false, EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1, 8); + assert_eq!((eff8, single8), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + let (eff16, single16) = target_render_slots_for(&mut last, &mut burst, 12_500_000, 1, 0, false, eff8, single8, 16); + assert_eq!((eff16, single16), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + // Heavy single-VM multi-pass (8 passes) still advances single_vm_target to Tier 1. + let (eff_heavy, single_heavy) = target_render_slots_for(&mut last, &mut burst, 13_000_000, 8, 0, false, eff16, single16, 16); + assert_eq!((eff_heavy, single_heavy), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[1].1)); + + // 16 concurrent VMs across 18 pass slots stay on 16 disjoint warm pass slots with 0 cross-VM retargets. + let mut o = Objects::new(); + 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, &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 { + compute: KVec::new(), + render: Some(render), + hw_slots: None, + }; + let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; + let vms: Vec<_> = (0..16u64).map(|i| vm(200 + i)).collect(); + let mut vm_slots = [usize::MAX; 16]; + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + vm_slots[i] = k; + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + // Subsequent interleaved rounds across all 16 VMs hit their own warm pass slots every time! + for _round in 0..4 { + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + assert_eq!(k, vm_slots[i], "VM {i} must stay on its warm pass slot"); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(!s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + } + + #[test]fn pb_epoch_prepare_seeds_active_prefix_and_clears_shrink_tail(){ + use g16::fw::buffer; + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let v = vm(300); + g16::object::ALL_OBJECTS.with(|a| a.borrow_mut().clear()); + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let (page_obj, block_obj) = g16::object::ALL_OBJECTS.with(|a| { + let objs = a.borrow(); + ( + objs.iter().find(|o| o.gva.is_some() && o.size == buffer::PAGE_LIST_SIZE).unwrap().clone(), + objs.iter().find(|o| o.gva.is_none() && o.size == buffer::BLOCK_LIST_SIZE).unwrap().clone(), + ) + }); + let heap = g16::hw::client::pb_heap(0); + // First prepare for 512 blocks writes ONLY 512*4*4 = 8192 page bytes and 512*8 = 4096 block bytes. + e.prepare(0, heap, 512).unwrap(); + assert_eq!(page_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 4 * 4); + assert_eq!(block_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 8); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + // Grow unpublished epoch to 1024 blocks, then shrink retry back to 512 blocks: + // tail [512..1024] must be zeroed cleanly. + e.prepare(1, heap, 1024).unwrap(); + assert_ne!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_ne!(block_obj.r32(512 * 8).unwrap(), 0); + e.prepare(2, heap, 512).unwrap(); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + assert_eq!(page_obj.r32(1023 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(1023 * 8).unwrap(), 0); + } + + #[test]fn closed_vms_reclaim_displaced_pb_render_and_compute_slots(){ + use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; + use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; + use g16::slots::{ComputeSlot, PassSlot}; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + 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 mut passes = KVec::new(); + for k in 0..18 { + 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 }; + + let mut vms = Vec::new(); + let mut epochs = Vec::new(); + let mut pb_arenas = Vec::new(); + let mut pass_arenas = Vec::new(); + let mut comp_arenas = Vec::new(); + + // Bind and retire 16 concurrent VMs across 16 PB slots, 16 render passes, and 16 compute units. + for i in 0..WARM_PB_SLOTS { + let v = vm(400 + i as u64); + 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, &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 }; + let c_arena = sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, 0, + ).unwrap(); + + // 1) PB warm slot i + let mask = (1u32 << i) | (1u32 << ((i + 1) % WARM_PB_SLOTS)); + let pb_slot = p + .pick_slot_in_mask_blocks_mode(&v, false, mask, i, 512, false) + .unwrap(); + assert_eq!(pb_slot, i); + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(pb_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(pb_slot, false); + p.hold_alloc(pb_slot, &v, Some(PbOwnerArena::Base(pb_arena.clone())), None).unwrap(); + p.publish_flight(pb_slot); + p.retire_flight(pb_slot, &e, b, true).unwrap(); + + // 2) Render pass slot i + let pk = s.pick_pass_in_for(&r_prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&r_prep, pk, Some(v.id), geo.tilemap_bytes).unwrap(); + let mut rc = Claims::new(); + rc.pass[0] = pk as u32; + rc.pass_count = 1; + rc.pass_mask = 1u64 << pk; + s.hold_render_pass(pk, &v, &r_prep).unwrap(); + s.publish(&mut rc).unwrap(); + s.retire(&mut rc).unwrap(); + + // 3) Compute unit i + let mut cc = Claims::new(); + let ck = s + .claim_compute_for(&shared_prep_compute, &mut cc, Some(v.id)) + .unwrap() + .unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena.clone())); + s.hold_compute_slot(ck, &v, &shared_prep_compute).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc).unwrap(); + s.retire(&mut cc).unwrap(); + + vms.push(v); + epochs.push(e); + pb_arenas.push(pb_arena); + pass_arenas.push(r_arena); + comp_arenas.push(c_arena); + } + + // Live VMs stay pinned and reusable across reclaim_closed(). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + for i in 0..WARM_PB_SLOTS { + assert!(sync::Arc::strong_count(&pb_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&pass_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&comp_arenas[i]) > 1); + assert!(p.reusable(i, &vms[i]).is_some()); + } + + // Close all 16 VMs: displaced slots 0..15 reclaim immediately; undisplaced slot 15 stays. + for v in &vms { + v.vm.close(); + } + assert!(p.reclaim_closed(), "undisplaced PB slot 15 remains"); + assert!(s.reclaim_closed(), "undisplaced render/compute slot 15 remain"); + // Displaced pass scrubs must skip closed VMs. + s.stage_displaced_pass_scrubs(); + assert!(!s.scrubbing_active()); + + for i in 0..(WARM_PB_SLOTS - 1) { + assert_eq!(sync::Arc::strong_count(&pb_arenas[i]), 1, "PB arena {i} reclaimed"); + // pb_mgr_table[i] still names this epoch's manager: it stays until replaced. + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); + assert_eq!(sync::Arc::strong_count(&pass_arenas[i]), 1, "pass arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&comp_arenas[i]), 1, "compute arena {i} reclaimed"); + // Drop our local epoch ref to confirm VmState itself has only our Vec ref left. + assert_eq!(sync::Arc::strong_count(&vms[i]), 2); + } + // Final undisplaced slot 15 stays protected until displaced. + let last = WARM_PB_SLOTS - 1; + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 2); + + // 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()), hw_slots: None }; + let live_slot = p + .pick_slot_in_mask_blocks_mode(&live, false, 0b11, 0, 512, false) + .unwrap(); + assert_eq!(live_slot, 0); + let live_e = g16::pools::PbEpoch::new( + &factory, + &live, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + live_e.prepare(live_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + live_e.expose(); + let lb = p.bind(live_slot, false); + p.hold_alloc(live_slot, &live, Some(PbOwnerArena::Base(live_r_arena.clone())), None).unwrap(); + p.publish_flight(live_slot); + p.retire_flight(live_slot, &live_e, lb, true).unwrap(); + + let lpk = s.pick_pass_in_for(&live_r_prep, &geo, 0, Some(live.id)).unwrap(); + s.claim_pass_in(&live_r_prep, lpk, Some(live.id), geo.tilemap_bytes).unwrap(); + let mut lrc = Claims::new(); + lrc.pass[0] = lpk as u32; + lrc.pass_count = 1; + lrc.pass_mask = 1u64 << lpk; + s.hold_render_pass(lpk, &live, &live_r_prep).unwrap(); + s.publish(&mut lrc).unwrap(); + s.retire(&mut lrc).unwrap(); + + let mut lcc = Claims::new(); + let lck = s + .claim_compute_for(&shared_prep_compute, &mut lcc, Some(live.id)) + .unwrap() + .unwrap(); + s.hold_compute_slot(lck, &live, &shared_prep_compute).unwrap(); + s.publish(&mut lcc).unwrap(); + s.retire(&mut lcc).unwrap(); + + // Now slot 15 is displaced -> reclaim_closed() evicts it and returns false (0 remaining). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 1); + // VM 17's epoch replaced slot 0's; the other slots keep their closed owners' epochs. + assert_eq!(sync::Arc::strong_count(&epochs[0]), 1, "replaced PB epoch 0 released"); + for i in 1..WARM_PB_SLOTS { + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); + } + // Each epoch is released once a newer epoch retires on its own slot. + for i in 1..WARM_PB_SLOTS { + let next = vm(520 + i as u64); + let e = g16::pools::PbEpoch::new( + &factory, + &next, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(i, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(i, false); + p.hold_alloc(i, &next, None, None).unwrap(); + p.publish_flight(i); + p.retire_flight(i, &e, b, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "replaced PB epoch {i} released"); + } + assert!(!p.reclaim_closed()); + drop(epochs); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released"); + } + + // Active off-lock scrub on a closed VM's displaced pass slot waits for scrub completion. + 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, &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 }; + let va = vm(600); + let vb = vm(601); + for (k, owner) in [(0usize, &va), (1usize, &vb)] { + s2.claim_pass_in(&sc_prep, k, Some(owner.id), 0x2000).unwrap(); + sc_prep.set_pass_dirty(k, 0x1000, 0x2000, 0x200).unwrap(); + let mut c = Claims::new(); + c.pass[0] = k as u32; + c.pass_count = 1; + c.pass_mask = 1u64 << k; + s2.hold_render_pass(k, owner, &sc_prep).unwrap(); + s2.publish(&mut c).unwrap(); + s2.retire(&mut c).unwrap(); + } + // Stage off-lock scrub on displaced slot 0 while va is still open, then close va. + s2.stage_displaced_pass_scrubs(); + assert!(s2.scrubbing_active()); + let batch = s2.take_staged_scrubs(); + va.vm.close(); + assert!(s2.reclaim_closed(), "must not evict slot 0 mid-scrub"); + assert_eq!(sync::Arc::strong_count(&va), 2); + // Running the scrub wakes the reclaim waiter, then reclaim_closed() evicts slot 0. + assert!(drain_scrubs(batch)); + assert!(s2.take_scrub_woke()); + assert!(!s2.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&va), 1); + + // Quarantined closed-VM slots stay pinned forever AND do not keep reclaim_closed() armed. + let vq = vm(700); + let mut pq = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let eq = g16::pools::PbEpoch::new( + &factory, + &vq, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + pq.hold_alloc(0, &vq, Some(PbOwnerArena::Base(sc_arena.clone())), None).unwrap(); + pq.publish_flight(0); + pq.quarantine_flight(0, Some(eq.clone())); + let mut cq = Claims::new(); + let qk = s2.claim_compute_for(&shared_prep_compute, &mut cq, Some(vq.id)).unwrap().unwrap(); + s2.hold_compute_slot(qk, &vq, &shared_prep_compute).unwrap(); + s2.publish(&mut cq).unwrap(); + s2.quarantine(&mut cq); + vq.vm.close(); + assert!(!pq.reclaim_closed(), "quarantined PB slot must not spin reclaim"); + assert!(!s2.reclaim_closed(), "quarantined compute slot must not spin reclaim"); + assert!(sync::Arc::strong_count(&vq) > 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, 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). + 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, hw_slots: 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}; + use g16::slots::ComputeSlot; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + // VM1 primes PB/UMA slot 0 and compute unit 0; VM2 displaces both via slot 1 / unit 1. + let vm1 = vm(1001); + let vm2 = vm(1002); + let vm3 = vm(1003); + + let pools1 = PoolSet::new_with_slots(&mut o, &factory, [0, 1]).unwrap(); + let uma1 = pools1.unit(0).unwrap().uma_lease(); + let r_arena1 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e1 = g16::pools::PbEpoch::new( + &factory, + &vm1, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease1 = e1.records_lease(); + e1.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e1.expose(); + let b1 = p.bind(0, false); + p.hold_alloc(0, &vm1, Some(PbOwnerArena::Base(r_arena1.clone())), Some(uma1.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e1, b1, true).unwrap(); + + let pools2 = PoolSet::new_with_slots(&mut o, &factory, [1, 2]).unwrap(); + let uma2 = pools2.unit(0).unwrap().uma_lease(); + let r_arena2 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e2 = g16::pools::PbEpoch::new( + &factory, + &vm2, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e2.prepare(1, g16::hw::client::pb_heap(0), 512).unwrap(); + e2.expose(); + let b2 = p.bind(1, false); + p.hold_alloc(1, &vm2, Some(PbOwnerArena::Base(r_arena2.clone())), Some(uma2.clone())).unwrap(); + p.publish_flight(1); + p.retire_flight(1, &e2, b2, true).unwrap(); + + // Compute unit 0 owned by VM1, displaced by VM2 on unit 1. + let mut units1 = KVec::new(); + for k in 0..COMPUTE_UNITS { + 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, 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())); + s.hold_compute_slot(0, &vm1, &prep1).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc1).unwrap(); + s.retire(&mut cc1).unwrap(); + + let mut units2 = KVec::new(); + 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, 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(); + s.publish(&mut cc2).unwrap(); + s.retire(&mut cc2).unwrap(); + + 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, hw_slots: None }; + + // Drop local arena/epoch/pool handles for VM1 and close VM1. + drop(e1); + drop(pools1); + drop(prep1); + vm1.vm.close(); + + // Reclaim evicts VM1's RenderArena and ComputeArena immediately and retains its + // firmware PB & UMA leases until overwritten. PB slot 0's epoch keeps VM1's VmState + // (TTBAT slot) and page list until a newer epoch retires on slot 0. + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&vm1), 2, "VM1 TTBAT slot stays with its PB epoch"); + assert_eq!(sync::Arc::strong_count(&r_arena1), 1, "VM1 RenderArena/PB heap must release"); + assert_eq!(sync::Arc::strong_count(&c_arena1), 1, "VM1 ComputeArena/32MiB pool must release"); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 3, "pb_mgr_table[0] lease held by epoch + retained_pb"); + assert_eq!(sync::Arc::strong_count(&uma1), 2, "render uma_mgr_table[33] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2, "compute uma_mgr_table[1] lease must stay mapped"); + + // Cancelling an unpublished replacement on slot 0 / unit 0 must NOT release VM1's leases. + let pools3 = PoolSet::new_with_slots(&mut o, &factory, [0, 2]).unwrap(); + let uma3 = pools3.unit(0).unwrap().uma_lease(); + let r_arena3 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3.clone())), Some(uma3.clone())).unwrap(); + p.cancel_alloc(0); + assert_eq!(sync::Arc::strong_count(&uma1), 2); + assert_eq!(sync::Arc::strong_count(&uma3), 2); + assert_eq!(sync::Arc::strong_count(&vm1), 2); + + let mut cc3_cancel = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3_cancel, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.release(&mut cc3_cancel); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2); + + // Once VM3 retires on exact hardware slot 0 / unit 0, firmware tables are overwritten and + // VM1's old FwLeases drop cleanly while VM3's leases become retained. + let e3 = g16::pools::PbEpoch::new( + &factory, + &vm3, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease3 = e3.records_lease(); + e3.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e3.expose(); + let b3 = p.bind(0, false); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3)), Some(uma3.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e3, b3, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 1, "overwritten pb_mgr_table[0] lease dropped"); + assert_eq!(sync::Arc::strong_count(&vm1), 1, "replaced PB epoch releases VM1's TTBAT slot"); + assert_eq!(sync::Arc::strong_count(&uma1), 1, "overwritten render uma_mgr_table[33] lease dropped"); + assert_eq!(sync::Arc::strong_count(&pb_lease3), 3, "new PB lease held by epoch + retained_pb"); + assert_eq!(sync::Arc::strong_count(&uma3), 3, "new render UMA lease held by pool + retained_uma"); + + let mut cc3 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.publish(&mut cc3).unwrap(); + s.retire(&mut cc3).unwrap(); + assert_eq!(sync::Arc::strong_count(&c_uma1), 1, "overwritten compute uma_mgr_table[1] lease dropped"); + assert_eq!(sync::Arc::strong_count(&c_uma3), 3, "new compute UMA lease held by unit + retained_uma"); + let _ = WARM_PB_SLOTS; + } + + + // 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) + // through ctx 46 after the epoch was gone: "write unmapped level 0 unit 0xe0 ctx 46". + #[test]fn closed_vm_pb_epoch_keeps_page_list_and_context_until_slot_replacement_retires(){ + use g16::resources::PbOwnerArena; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + + // VM X (ctx 46) runs and retires on PB slot 3; VM Y then retires on slot 4. + let x = vm(46); + let x_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let ex = epoch(&x, 3); + let x_records = ex.records_lease(); + let bx = p.bind(3, false); + p.hold_alloc(3, &x, Some(PbOwnerArena::Base(x_arena.clone())), None).unwrap(); + p.publish_flight(3); + p.retire_flight(3, &ex, bx, true).unwrap(); + let y = vm(47); + let ey = epoch(&y, 4); + let by = p.bind(4, false); + p.hold_alloc(4, &y, None, None).unwrap(); + p.publish_flight(4); + p.retire_flight(4, &ey, by, true).unwrap(); + + // X closes. Its arena and PB heap go, but not the epoch firmware still names. + x.vm.close(); + assert!(!p.reclaim_closed(), "a retained owner epoch alone must not keep reclaim armed"); + assert!(!p.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&x_arena), 1, "closed VM's render arena reclaimed"); + assert_eq!(sync::Arc::strong_count(&ex), 2, "slot 3 epoch (page list) reclaimed early"); + assert_eq!(sync::Arc::strong_count(&x), 2, "ctx 46 released while its lists are named"); + assert!(sync::Arc::strong_count(&x_records) >= 2); + assert!(p.reusable(3, &x).is_none()); + + // 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_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(); + p.publish_flight(3); + assert!(p.reclaim_closed(), "rebinding render still in flight"); + assert_eq!(sync::Arc::strong_count(&ex), 2); + assert_eq!(sync::Arc::strong_count(&x), 2); + p.retire_flight(3, &ez, bz, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&ex), 1, "replaced epoch released"); + drop(ex); + assert_eq!(sync::Arc::strong_count(&x), 1, "closed VM released after replacement"); + assert_eq!(sync::Arc::strong_count(&x_records), 1); + assert!(!p.reclaim_closed()); + } + } ''' poll_source = (production/'poll.rs').read_text() @@ -1764,6 +2836,9 @@ def module(text, name): assert 'self.enqueue_scrubs(scrubs)' in poll_source, 'poll.rs must enqueue scrubs asynchronously' assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' +assert 'closed_vm_reclaim' in mod_source +assert 'self.shared.closed_vm_reclaim.store(true, Ordering::Release);' in mod_source +assert 'reclaim_closed_vm_slots' in poll_source lifetime_source = (production.parent / 'mmu' / 'lifetime.rs').read_text() is_closed_fn = item(lifetime_source, 'pub(crate) fn is_closed(') assert '.lock()' not in is_closed_fn, 'Vm::is_closed() must be lock-free' @@ -1796,6 +2871,18 @@ 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' +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:') ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 render_burst_lines = ( @@ -1805,8 +2892,11 @@ 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(') ) source = source.replace('__CMD_CLASSES__', '\n'.join(item(graph_source, decl) for decl in ('pub(crate) const fn graph_fw(', 'pub(crate) const fn qinfo_cached(', 'pub(crate) const fn cmd_fw(', 'pub(crate) const fn cmd_shared('))).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) graph_types = '\n'.join( @@ -1824,7 +2914,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 [ @@ -1839,7 +2929,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 35, + 'result': 'pass', 'tests': 41, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes',