diff --git a/Documentation/gpu/asahi-usage-stats.rst b/Documentation/gpu/asahi-usage-stats.rst index e1b0632a9fd0f..fd7e8e0d210fc 100644 --- a/Documentation/gpu/asahi-usage-stats.rst +++ b/Documentation/gpu/asahi-usage-stats.rst @@ -48,10 +48,13 @@ start and end operations. The shared G17 backend runs several commands of one queue at once, so their stages overlap. It charges each engine of a queue the union of that queue's stage intervals (exact, because a queue's stages retire in the order they started), so a queue never counts more than the wall time on one -engine. Queues of one file still add up. The other backends sum their intervals -without merging overlapping commands on the same engine. Missing, zero-start or -reversed intervals are ignored. Failed or cancelled commands do not contribute -incomplete intervals; +engine. Queues of one file still add up on G17. Native G16 executes pipelined +commands and dual-pipe compute across sibling queues of one DRM file, so it +unions overlapping stage intervals per file (``Client::add_union``) to keep each +engine bounded by wall time. The other backends sum their intervals without +merging overlapping commands on the same engine. Missing, zero-start or reversed +intervals are ignored. Failed or cancelled commands do not contribute incomplete +intervals; successful stages that retired before a later failure remain counted. An unexecuted G17 replay contributes only when it eventually retires successfully. There is no submit-to-completion wall-time fallback in the current backends. diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 0883715502766..7e4fc50ed6d90 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -294,34 +294,45 @@ impl SyncItem { let count = in_count.checked_add(out_count).ok_or(EOVERFLOW)?; const STRIDE: usize = core::mem::size_of::(); + const CHUNK: usize = 8; let size = STRIDE.checked_mul(count as usize).ok_or(EOVERFLOW)?; let mut vec = KVec::with_capacity(count as usize, GFP_KERNEL)?; let mut anchor = None; - // Read each record once so validation and use see the same retained bytes. + // Read each record once in small stack chunks so validation and use see the + // same retained bytes without a per-entry copy_from_user. let mut reader = UserSlice::new(UserPtr::from_addr(ptr as usize), size).reader(); + let mut buf = MaybeUninit::<[uapi::drm_asahi_sync; CHUNK]>::uninit(); - for i in 0..count { - let mut sync: MaybeUninit = MaybeUninit::uninit(); + let mut base = 0u32; + while base < count { + let chunk = ((count - base) as usize).min(CHUNK); + let raw = buf.as_mut_ptr().cast::(); - // SAFETY: The size of `sync` is STRIDE + // SAFETY: `buf` holds `CHUNK` contiguous `drm_asahi_sync` entries and + // `chunk <= CHUNK`, so `chunk * STRIDE` bytes are writable. reader.read_raw(unsafe { - core::slice::from_raw_parts_mut(sync.as_mut_ptr().cast::>(), STRIDE) + core::slice::from_raw_parts_mut(raw.cast::>(), chunk * STRIDE) })?; - // SAFETY: All bit patterns in the struct are valid - let sync = unsafe { sync.assume_init() }; + for offset in 0..chunk { + let i = base + offset as u32; + // SAFETY: `read_raw` initialized `chunk` contiguous entries starting at `raw`, + // `offset < chunk`, and all bit patterns in the struct are valid. + let sync = unsafe { raw.add(offset).read() }; - if sync.sync_type == crate::g17::sync_output::SYNC_CUMULATIVE { - if !allow_cumulative || i < in_count || anchor.is_some() { - return Err(EINVAL); + if sync.sync_type == crate::g17::sync_output::SYNC_CUMULATIVE { + if !allow_cumulative || i < in_count || anchor.is_some() { + return Err(EINVAL); + } + anchor = Some(i as usize); } - anchor = Some(i as usize); + vec.push( + Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, + GFP_KERNEL, + )?; } - vec.push( - Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, - GFP_KERNEL, - )?; + base += chunk as u32; } if let Some(anchor) = anchor { let bundle = crate::g17::sync_output::SignalBundle::new( @@ -350,9 +361,42 @@ pub(crate) enum Object { /// queues is given back once the queue itself is gone. pub(crate) struct TableQueue { queue: KBox, + /// Reusable staging buffer for `SUBMIT` command buffers, avoiding per-submit heap + /// allocations and keeping large command buffers off the kernel stack. + cmdbuf: KVec, _share: Option, } +impl TableQueue { + /// Maximum command-buffer capacity retained on a queue between submissions. + const REUSE_CMDBUF_CAP: usize = 4096; + + /// Takes the cached command-buffer staging allocation so userspace copies run outside the + /// queue mutex (preventing `queue.lock()` -> `mmap_lock` lock-order inversion). + fn take_cmdbuf(&mut self) -> KVec { + core::mem::take(&mut self.cmdbuf) + } + + /// Returns a cleared command-buffer allocation to the per-queue cache when within the + /// reuse capacity cap; oversized buffers are dropped. + fn return_cmdbuf(&mut self, mut buf: KVec) { + buf.clear(); + if buf.capacity() > 0 + && buf.capacity() <= Self::REUSE_CMDBUF_CAP + && buf.capacity() >= self.cmdbuf.capacity() + { + self.cmdbuf = buf; + } + } +} + +fn copy_cmdbuf_from_user(buf: &mut KVec, addr: u64, size: usize) -> Result { + buf.clear(); + UserSlice::new(UserPtr::from_addr(addr as usize), size) + .reader() + .read_all(buf, GFP_KERNEL) +} + impl Deref for TableQueue { type Target = dyn queue::Queue; @@ -1751,6 +1795,7 @@ impl File { resv.fill(Arc::pin_init( new_mutex!(TableQueue { queue, + cmdbuf: KVec::new(), _share: share, }), GFP_KERNEL, @@ -1822,28 +1867,37 @@ impl File { data.queue_id, id ); - let mut vec = KVec::new(); - let copy_commands = |bytes: &mut KVec| { - UserSlice::new( - UserPtr::from_addr(data.cmdbuf as usize), - data.cmdbuf_size as usize, - ) - .reader() - .read_all(bytes, GFP_KERNEL) - }; + let cmdbuf_size = data.cmdbuf_size as usize; let guarded = gpu.as_any().is::() || gpu.tracked_submission(); // Once G17 output syncobjs are resolved, its queue must install a fence - // on every failure. Take the fallible userspace snapshot before that point. - if guarded { - copy_commands(&mut vec)?; - } - let syncs = SyncItem::parse_array( + // on every failure. Take the fallible userspace snapshot before that point, + // staging into a buffer taken from the queue's reusable cache so user + // copies never execute under `queue.lock()`. + let mut cmdbuf = if guarded { + let mut buf = queue.lock().take_cmdbuf(); + if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { + queue.lock().return_cmdbuf(buf); + return Err(e); + } + Some(buf) + } else { + None + }; + let syncs = match SyncItem::parse_array( file, data.syncs, data.in_sync_count, data.out_sync_count, gpu.as_any().is::(), - )?; + ) { + Ok(syncs) => syncs, + Err(e) => { + if let Some(buf) = cmdbuf { + queue.lock().return_cmdbuf(buf); + } + return Err(e); + } + }; mod_dev_dbg!( device, @@ -1853,22 +1907,33 @@ impl File { id ); - // Copy the command buffer into the kernel. Because we need to iterate - // the command buffer twice, we do this in one big copy_from_user to - // avoid TOCTOU issues. - if !guarded { - copy_commands(&mut vec)?; - } + // Copy the command buffer into the kernel outside `queue.lock()`. Because we + // need to iterate the command buffer twice, we do this in one big copy_from_user + // to avoid TOCTOU issues. + let cmdbuf = match cmdbuf.take() { + Some(buf) => buf, + None => { + let mut buf = queue.lock().take_cmdbuf(); + if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { + queue.lock().return_cmdbuf(buf); + return Err(e); + } + buf + } + }; let objects = file.inner().objects(); - let ret = queue.lock().submit( + let mut guard = queue.lock(); + let ret = guard.queue.submit( reg_data, id, syncs, data.in_sync_count as usize, - &vec, + cmdbuf.as_slice(), objects, ); + guard.return_cmdbuf(cmdbuf); + drop(guard); if ret.is_ok() { if let Some((util_min, duration_ms)) = gpu.syncobj_wait_hint() { diff --git a/drivers/gpu/drm/asahi/g15/command.rs b/drivers/gpu/drm/asahi/g15/command.rs index 66e52e6981197..c88979e00d47d 100644 --- a/drivers/gpu/drm/asahi/g15/command.rs +++ b/drivers/gpu/drm/asahi/g15/command.rs @@ -146,8 +146,8 @@ pub(crate) struct Context<'a> { pub(crate) usc_base: u64, } -struct CheckedContext<'a> { - vm: &'a mut mmu::VmReadGuard, +struct CheckedContext<'a, 'b> { + vm: &'a mut mmu::VmReadGuard<'b>, usc_base: u64, } @@ -383,7 +383,7 @@ impl Timestamps<'_> { /// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a /// page without the access EACCES. pub(crate) fn cover( - vm: &mut mmu::VmReadGuard, + vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, read: bool, @@ -419,7 +419,7 @@ pub(crate) fn cover( /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. fn check_attachments( - vm: &mut mmu::VmReadGuard, + vm: &mut mmu::VmReadGuard<'_>, list: &[uapi::drm_asahi_attachment], write: bool, ) -> Result { @@ -482,7 +482,7 @@ fn geometry_bytes(cmd: &uapi::drm_asahi_cmd_render) -> (u64, u64) { } /// Per-command render admission. -fn check_render(context: &mut CheckedContext<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { +fn check_render(context: &mut CheckedContext<'_, '_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { let vm = &mut *context.vm; let allowed = PROCESS_EMPTY_TILES | NO_VERTEX_CLUSTERING @@ -567,7 +567,7 @@ fn check_render(context: &mut CheckedContext<'_>, cmd: &uapi::drm_asahi_cmd_rend /// Per-command compute admission. fn check_compute( - context: &mut CheckedContext<'_>, + context: &mut CheckedContext<'_, '_>, cmd: &uapi::drm_asahi_cmd_compute, attachments: &[uapi::drm_asahi_attachment], ) -> Result { diff --git a/drivers/gpu/drm/asahi/g15/gate.rs b/drivers/gpu/drm/asahi/g15/gate.rs index c4c482fb8f89c..c4a233e591799 100644 --- a/drivers/gpu/drm/asahi/g15/gate.rs +++ b/drivers/gpu/drm/asahi/g15/gate.rs @@ -75,7 +75,7 @@ struct Window { impl Window { /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page /// unless the record crosses it). Unreadable memory: EFAULT. - fn words(&mut self, vm: &mut mmu::VmReadGuard, va: u64, count: usize) -> Result<[u32; 10]> { + fn words(&mut self, vm: &mut mmu::VmReadGuard<'_>, va: u64, count: usize) -> Result<[u32; 10]> { let n = count * 4; let cached = self.len != 0 && va >= self.va @@ -112,7 +112,7 @@ struct Checked { /// One page check of `[start, end)` under the walk's page budget: ENOSPC once the budget is /// spent. -fn check(vm: &mut mmu::VmReadGuard, start: u64, end: u64, count: &mut u32) -> Result { +fn check(vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, count: &mut u32) -> Result { if *count >= CDM_MAX_PAGE_CHECKS { return Err(ENOSPC); } @@ -122,7 +122,7 @@ fn check(vm: &mut mmu::VmReadGuard, start: u64, end: u64, count: &mut u32) -> Re /// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. /// The last proven program page is not checked again. -fn program(vm: &mut mmu::VmReadGuard, usc: u64, address: u64, checked: &mut Checked) -> Result { +fn program(vm: &mut mmu::VmReadGuard<'_>, usc: u64, address: u64, checked: &mut Checked) -> Result { if address < usc || address - usc >= USC_WINDOW || address & 63 != 0 { return Err(EINVAL); } @@ -138,7 +138,7 @@ fn program(vm: &mut mmu::VmReadGuard, usc: u64, address: u64, checked: &mut Chec /// An indirect launch's 12 argument bytes: readable. The last proven argument page is not /// checked again; arguments that cross a page are checked each time. -fn arguments(vm: &mut mmu::VmReadGuard, address: u64, checked: &mut Checked) -> Result { +fn arguments(vm: &mut mmu::VmReadGuard<'_>, address: u64, checked: &mut Checked) -> Result { let end = address.checked_add(12).ok_or(EINVAL)?; let page = address & !(mmu::UAT_PGMSK as u64); let within = (end - 1) & !(mmu::UAT_PGMSK as u64) == page; @@ -154,7 +154,7 @@ fn arguments(vm: &mut mmu::VmReadGuard, address: u64, checked: &mut Checked) -> /// VDM admission: a normal root stream opens with the G15 barrier, with or /// without the USC cache invalidate. -pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { +pub(crate) fn vdm(vm: &mut mmu::VmReadGuard<'_>, va: u64) -> Result { if !params::stream_gate() { return Ok(()); } @@ -170,7 +170,7 @@ pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { /// CDM admission: walks the stream from its base through no-return links until TERMINATE, /// admitting only the known G15S records: direct launch (40), indirect launch (36/24), barriers /// (4), link (8). -pub(crate) fn cdm(vm: &mut mmu::VmReadGuard, usc: u64, base: u64) -> Result { +pub(crate) fn cdm(vm: &mut mmu::VmReadGuard<'_>, usc: u64, base: u64) -> Result { if !params::stream_gate() { return Ok(()); } diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index e7cad14e4afe3..65927544b46d1 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -242,6 +242,17 @@ impl core::ops::Deref for Commands { } } +impl core::ops::DerefMut for Commands { + fn deref_mut(&mut self) -> &mut [Command] { + match self { + Self::Empty => &mut [], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + /// Inline storage for the common 1-2 command ordinals, spilling to a heap `KVec` above 2. pub(crate) enum Orders { Empty, @@ -286,58 +297,6 @@ impl core::ops::Deref for Orders { } } -/// Inline storage for transient resolved timestamp destinations during SUBMIT validation. -enum Resolved { - Empty, - One(Option), - Two([Option; 2]), - Heap { - items: KVec>, - index: usize, - }, -} - -impl Resolved { - fn new() -> Self { - Self::Empty - } - - fn push(&mut self, dest: crate::timestamp::Destinations) -> Result { - match self { - Self::Heap { items, .. } => items.push(Some(dest), GFP_KERNEL)?, - Self::Two(_) => { - let mut items = KVec::with_capacity(4, GFP_KERNEL)?; - if let Self::Two([a, b]) = core::mem::replace(self, Self::Empty) { - let _ = items.push_within_capacity(a); - let _ = items.push_within_capacity(b); - let _ = items.push_within_capacity(Some(dest)); - } - *self = Self::Heap { items, index: 0 }; - } - Self::One(_) => { - if let Self::One(a) = core::mem::replace(self, Self::Empty) { - *self = Self::Two([a, Some(dest)]); - } - } - Self::Empty => *self = Self::One(Some(dest)), - } - Ok(()) - } - - fn next(&mut self) -> Option { - match self { - Self::Empty => None, - Self::One(slot) => slot.take(), - Self::Two(slots) => slots[0].take().or_else(|| slots[1].take()), - Self::Heap { items, index } => { - let item = items.get_mut(*index)?.take(); - *index += 1; - item - } - } - } -} - /// A validated SUBMIT. pub(crate) struct Submission { /// The commands, in submission order. @@ -356,12 +315,10 @@ pub(crate) struct Context<'a> { pub(crate) usc_base: u64, } -/// A stream whose timestamps and ordinals are resolved ([`prepare`]), before its spans are -/// checked ([`Prepared::validate`]). -pub(crate) struct Prepared<'a> { - bytes: &'a [u8], - /// CPU views and their backing resolved before scheduler acceptance. - resolved: Resolved, +/// A stream whose timestamps and ordinals are resolved ([`ParsedStream::prepare`]), before its +/// spans are checked ([`Prepared::validate`]). +pub(crate) struct Prepared { + commands: Commands, orders: Orders, counts: [u64; 2], } @@ -520,152 +477,134 @@ fn check_geometry(cmd: &uapi::drm_asahi_cmd_render) -> Result { .validate_capacity(hw::client::TPC_SIZE, hw::client::TILEMAP_SIZE) } -/// Structural validation of a whole command stream, before anything is looked up. -pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { - if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { +fn validate_attachments_header(entry: &Entry<'_>) -> Result { + if entry.barriers != [NONE; 2] + || entry.payload.len() % ATTACHMENT_SIZE != 0 + || entry.payload.len() / ATTACHMENT_SIZE > hw::sizes::MAX_ATTACHMENTS + { return Err(EINVAL); } - let range = hw::USER_RANGE; - let mut counts = [0u32; 2]; - for entry in stream(bytes) { - let entry = entry?; - match entry.kind { - SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { - if entry.barriers != [NONE; 2] - || entry.payload.len() % ATTACHMENT_SIZE != 0 - || entry.payload.len() / ATTACHMENT_SIZE > hw::sizes::MAX_ATTACHMENTS - { - return Err(EINVAL); - } - for bytes in entry.payload.chunks_exact(ATTACHMENT_SIZE) { - let attachment: uapi::drm_asahi_attachment = Reader::new(bytes).read()?; - if attachment.pad != 0 - || attachment.flags != 0 - || !inside(attachment.pointer, attachment.size, &range) - { - return Err(EINVAL); - } - } - continue; - } - _ => {} - } - if (entry.barriers[RENDER] != NONE && u32::from(entry.barriers[RENDER]) > counts[RENDER]) - || (entry.barriers[COMPUTE] != NONE - && u32::from(entry.barriers[COMPUTE]) > counts[COMPUTE]) + Ok(()) +} + +fn validate_attachment(attachment: &uapi::drm_asahi_attachment, range: &Range) -> Result { + if attachment.pad != 0 + || attachment.flags != 0 + || !inside(attachment.pointer, attachment.size, range) + { + return Err(EINVAL); + } + Ok(()) +} + +fn validate_render_entry( + entry: &Entry<'_>, + counts: [u32; 2], + early_tiling: bool, +) -> Result<( + uapi::drm_asahi_cmd_render, + Option, +)> { + 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); + } + if let Some(prefixes) = prefixes { + if (prefixes.ta_vdm_barrier != NONE && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) + || (prefixes.ta_cdm_barrier != NONE + && u32::from(prefixes.ta_cdm_barrier) > counts[COMPUTE]) { return Err(EINVAL); } - match entry.kind { - CMD_RENDER => { - 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); - } - if let Some(prefixes) = prefixes { - if (prefixes.ta_vdm_barrier != NONE - && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) - || (prefixes.ta_cdm_barrier != NONE - && u32::from(prefixes.ta_cdm_barrier) > counts[COMPUTE]) - { - return Err(EINVAL); - } - } - check_render_helpers(cmd)?; - // M4 HAL200 resource words carry all four high halves. - let allowed = PROCESS_EMPTY_TILES - | DBIAS_IS_INT - | RSRC_SPEC_HI - | if early_tiling { - FRAGMENT_BARRIERS | STAGE_PREFIXES - } else { - 0 - }; - if cmd.flags & !allowed != 0 - || !(1..=MAX_DIMENSION).contains(&cmd.width_px) - || !(1..=MAX_DIMENSION).contains(&cmd.height_px) - || !(1..=MAX_LAYERS).contains(&cmd.layers) - || !matches!(cmd.samples, 1 | 2 | 4) - { - return Err(EINVAL); - } - check_geometry(cmd)?; - // Timestamp copies are reserved for another runtime. No copy - // feature is advertised, and zero handles do not waive MBZ offsets. - if cmd - .ts_frag_end_copies - .iter() - .any(|ts| ts.handle != 0 || ts.offset != 0) - { - 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); - } - if cmd.flags & RSRC_SPEC_HI == 0 - && (cmd.bg_eot_rsrc_spec_hi != 0 - || cmd.bg_eot_partial_rsrc_spec_hi != 0 - || cmd.bg_rsrc_spec_hi != 0 - || cmd.bg_partial_rsrc_spec_hi != 0) - { - return Err(EINVAL); - } - counts[RENDER] += 1; - } - CMD_COMPUTE => { - 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 - || !inside( - cmd.cdm_ctrl_stream_base, - cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, - &range, - ) - { - 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); - } - counts[COMPUTE] += 1; - } - _ => return Err(EINVAL), - } - if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { - return Err(EINVAL); - } } - if counts == [0; 2] { + check_render_helpers(cmd)?; + // M4 HAL200 resource words carry all four high halves. + let allowed = PROCESS_EMPTY_TILES + | DBIAS_IS_INT + | RSRC_SPEC_HI + | if early_tiling { + FRAGMENT_BARRIERS | STAGE_PREFIXES + } else { + 0 + }; + if cmd.flags & !allowed != 0 + || !(1..=MAX_DIMENSION).contains(&cmd.width_px) + || !(1..=MAX_DIMENSION).contains(&cmd.height_px) + || !(1..=MAX_LAYERS).contains(&cmd.layers) + || !matches!(cmd.samples, 1 | 2 | 4) + { return Err(EINVAL); } - Ok(()) + check_geometry(cmd)?; + // Timestamp copies are reserved for another runtime. No copy + // feature is advertised, and zero handles do not waive MBZ offsets. + if cmd + .ts_frag_end_copies + .iter() + .any(|ts| ts.handle != 0 || ts.offset != 0) + { + 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); + } + if cmd.flags & RSRC_SPEC_HI == 0 + && (cmd.bg_eot_rsrc_spec_hi != 0 + || cmd.bg_eot_partial_rsrc_spec_hi != 0 + || cmd.bg_rsrc_spec_hi != 0 + || cmd.bg_partial_rsrc_spec_hi != 0) + { + return Err(EINVAL); + } + Ok((packet, prefixes)) +} + +fn validate_compute_entry( + entry: &Entry<'_>, + range: &Range, +) -> Result { + 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 + || !inside( + cmd.cdm_ctrl_stream_base, + cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, + range, + ) + { + 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) } /// Checks that `[start, end)` (rounded out to pages) lies inside the user address range and @@ -693,20 +632,6 @@ fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { Ok((first, last - first)) } -/// Checks that `[start, end)` (rounded out to pages) is user memory mapped with the requested -/// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a -/// page without the access EACCES. -pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { - let (first, size) = align_span(start, end)?; - if vm.covers_range(first, size, read, write) { - Ok(()) - } else if vm.covers_range(first, size, false, false) { - Err(EACCES) - } else { - Err(ENOENT) - } -} - /// 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 { @@ -761,6 +686,26 @@ impl SpanBatch { } Ok(()) } + + fn flush_locked(&mut self, guard: &mut mmu::VmReadGuard<'_>) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + for &(first, size, access) in &self.ranges[..n] { + let read = access & 1 != 0; + let write = access & 2 != 0; + if !guard.covers_range(first, size, read, write) { + return if guard.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + }; + } + } + Ok(()) + } } /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. @@ -788,11 +733,16 @@ fn check_attachments( Ok(()) } -/// Parses the attachment list of a SET_*_ATTACHMENTS command. -fn attachment_list(bytes: &[u8]) -> Result> { +/// Parses the attachment list of a SET_*_ATTACHMENTS command, validating every entry in one pass. +fn attachment_list_checked( + bytes: &[u8], + range: &Range, +) -> Result> { let mut list = KVec::with_capacity(bytes.len() / ATTACHMENT_SIZE, GFP_KERNEL)?; for bytes in bytes.chunks_exact(ATTACHMENT_SIZE) { - list.push(Reader::new(bytes).read()?, GFP_KERNEL)?; + let attachment: uapi::drm_asahi_attachment = Reader::new(bytes).read()?; + validate_attachment(&attachment, range)?; + list.push(attachment, GFP_KERNEL)?; } Ok(list) } @@ -807,6 +757,25 @@ fn copy_list(lists: &[&[uapi::drm_asahi_attachment]]) -> Result, + start: u64, + end: u64, + read: bool, + write: bool, +) -> Result { + let (first, size) = align_span(start, end)?; + if guard.covers_range(first, size, read, write) { + Ok(()) + } else if guard.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + } +} + /// Whether a GVA can be named by a 32-bit compact pointer. fn compact(gva: u64) -> bool { (0x1000000000..0x9000000000).contains(&gva) @@ -1011,140 +980,299 @@ fn check_compute( gate::cdm(vm, context.usc_base, base, end) } -/// Resolves timestamps and exact historical-prefix dependencies of a valid stream -/// ([`check_stream`]) for a queue that accepted `accepted` render and compute commands before -/// this ioctl. -pub(crate) fn prepare<'a>( - bytes: &'a [u8], - accepted: [u64; 2], - objects: Pin<&xarray::XArray>>, -) -> Result> { - let mut resolved = Resolved::new(); - let mut orders = Orders::new(); - let mut preceding = [0u16; 2]; +/// Per-command barrier and stage-prefix metadata captured during single-pass parsing. +#[derive(Copy, Clone)] +struct OrderMeta { + barriers: [u16; 2], + prefixes: Option, +} + +/// Inline storage for 1-2 command barrier metadata records, spilling to a heap `KVec` above 2. +enum OrderMetas { + Empty, + One([OrderMeta; 1]), + Two([OrderMeta; 2]), + Heap(KVec), +} + +impl OrderMetas { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, meta: OrderMeta) -> Result { + match self { + Self::Heap(vec) => vec.push(meta, GFP_KERNEL)?, + Self::Two([a, b]) => { + let (a, b) = (*a, *b); + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(meta); + *self = Self::Heap(vec); + } + Self::One([a]) => *self = Self::Two([*a, meta]), + Self::Empty => *self = Self::One([meta]), + } + Ok(()) + } +} + +impl core::ops::Deref for OrderMetas { + type Target = [OrderMeta]; + + fn deref(&self) -> &[OrderMeta] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + +/// Tracks the active attachment list during single-pass parsing so the first consuming command +/// takes ownership without copying, while later commands sharing the same list clone from it. +enum AttachmentState { + Empty, + Fresh(KVec), + FromCommand(usize), +} + +/// A structurally valid, decoded command stream before timestamp/ordinal resolution and VM checks. +pub(crate) struct ParsedStream { + commands: Commands, + meta: OrderMetas, + counts: [u64; 2], +} + +/// Structurally validates and decodes a command stream in a single pass, before anything is +/// looked up or device state is consulted. +pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { + if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { + return Err(EINVAL); + } + let range = hw::USER_RANGE; + let mut counts = [0u32; 2]; + let mut commands = Commands::new(); + let mut meta = OrderMetas::new(); + let mut vertex = AttachmentState::Empty; + let mut fragment = AttachmentState::Empty; + let mut compute = AttachmentState::Empty; + for entry in stream(bytes) { let entry = entry?; - let (outputs, engine, prior, prefixes) = match entry.kind { + match entry.kind { + SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { + validate_attachments_header(&entry)?; + let list = attachment_list_checked(entry.payload, &range)?; + let state = if list.is_empty() { + AttachmentState::Empty + } else { + AttachmentState::Fresh(list) + }; + match entry.kind { + SET_VERTEX_ATTACHMENTS => vertex = state, + SET_FRAGMENT_ATTACHMENTS => fragment = state, + SET_COMPUTE_ATTACHMENTS => compute = state, + _ => {} + } + continue; + } + _ => {} + } + if (entry.barriers[RENDER] != NONE && u32::from(entry.barriers[RENDER]) > counts[RENDER]) + || (entry.barriers[COMPUTE] != NONE + && u32::from(entry.barriers[COMPUTE]) > counts[COMPUTE]) + { + return Err(EINVAL); + } + let next_idx = commands.len(); + match entry.kind { CMD_RENDER => { - let (packet, prefixes) = render_payload(entry.payload)?; - let outputs = crate::timestamp::Destinations::resolve_aligned( - objects, - &[packet.ts_vtx, packet.ts_frag], - )?; - (outputs, RENDER, [packet.prior_vdm, packet.prior_cdm], prefixes) + let (packet, prefixes) = validate_render_entry(&entry, counts, early_tiling)?; + counts[RENDER] += 1; + if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { + return Err(EINVAL); + } + let take_render = |state: &mut AttachmentState, is_fragment: bool| { + match core::mem::replace(state, AttachmentState::Empty) { + AttachmentState::Empty => Ok(KVec::new()), + AttachmentState::Fresh(list) => { + *state = AttachmentState::FromCommand(next_idx); + Ok(list) + } + AttachmentState::FromCommand(prev_idx) => { + *state = AttachmentState::FromCommand(prev_idx); + match &commands[prev_idx] { + Command::Render(prev) => { + let src = if is_fragment { + &prev.fragment_attachments + } else { + &prev.vertex_attachments + }; + copy_list(&[src]) + } + Command::Compute(_) => Err(EINVAL), + } + } + } + }; + let vertex_attachments = take_render(&mut vertex, false)?; + let fragment_attachments = take_render(&mut fragment, true)?; + commands.push(Command::Render(KBox::new( + RenderCommand { + cmd: packet, + timestamp_outputs: crate::timestamp::Destinations::empty(), + vertex_attachments, + fragment_attachments, + }, + GFP_KERNEL, + )?))?; + meta.push(OrderMeta { + barriers: entry.barriers, + prefixes, + })?; } CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let outputs = - crate::timestamp::Destinations::resolve_aligned(objects, &[packet.ts])?; - (outputs, COMPUTE, [packet.prior_vdm, packet.prior_cdm], None) + let packet = validate_compute_entry(&entry, &range)?; + counts[COMPUTE] += 1; + if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { + return Err(EINVAL); + } + let attachments = match core::mem::replace(&mut compute, AttachmentState::Empty) { + AttachmentState::Empty => KVec::new(), + AttachmentState::Fresh(list) => { + compute = AttachmentState::FromCommand(next_idx); + list + } + AttachmentState::FromCommand(prev_idx) => { + compute = AttachmentState::FromCommand(prev_idx); + match &commands[prev_idx] { + Command::Compute(prev) => copy_list(&[&prev.attachments])?, + Command::Render(_) => return Err(EINVAL), + } + } + }; + commands.push(Command::Compute(KBox::new( + ComputeCommand { + cmd: packet, + attachments, + timestamp_outputs: crate::timestamp::Destinations::empty(), + query_access: packet.flags & COMPUTE_NO_QUERY_ACCESS == 0, + }, + GFP_KERNEL, + )?))?; + meta.push(OrderMeta { + barriers: entry.barriers, + prefixes: None, + })?; } - _ => continue, - }; - resolved.push(outputs)?; - let mut order = Order::new(accepted, preceding, entry.barriers, prior, engine)?; - if let Some(prefixes) = prefixes { - let tiling = Order::new( - accepted, - preceding, - [prefixes.ta_vdm_barrier, prefixes.ta_cdm_barrier], - [prefixes.ta_prior_vdm, prefixes.ta_prior_cdm], - RENDER, - )?; - order.narrow_tiling(&tiling)?; + _ => return Err(EINVAL), } - orders.push(order)?; - preceding[engine] += 1; } - - Ok(Prepared { - bytes, - resolved, - orders, - counts: [u64::from(preceding[RENDER]), u64::from(preceding[COMPUTE])], + if counts == [0; 2] { + return Err(EINVAL); + } + Ok(ParsedStream { + commands, + meta, + counts: [u64::from(counts[RENDER]), u64::from(counts[COMPUTE])], }) } -impl Prepared<'_> { +impl ParsedStream { + /// Resolves timestamps in place and computes exact historical-prefix dependencies for a queue + /// that accepted `accepted` render and compute commands before this ioctl. + pub(crate) fn prepare( + mut self, + accepted: [u64; 2], + objects: Pin<&xarray::XArray>>, + ) -> Result { + let mut orders = Orders::new(); + let mut preceding = [0u16; 2]; + for (command, meta) in self.commands.iter_mut().zip(self.meta.iter()) { + let (engine, prior) = match command { + Command::Render(render) => { + render.timestamp_outputs = crate::timestamp::Destinations::resolve_aligned( + objects, + &[render.cmd.ts_vtx, render.cmd.ts_frag], + )?; + (RENDER, [render.cmd.prior_vdm, render.cmd.prior_cdm]) + } + Command::Compute(compute) => { + compute.timestamp_outputs = crate::timestamp::Destinations::resolve_aligned( + objects, + &[compute.cmd.ts], + )?; + (COMPUTE, [compute.cmd.prior_vdm, compute.cmd.prior_cdm]) + } + }; + let mut order = Order::new(accepted, preceding, meta.barriers, prior, engine)?; + if let Some(prefixes) = meta.prefixes { + let tiling = Order::new( + accepted, + preceding, + [prefixes.ta_vdm_barrier, prefixes.ta_cdm_barrier], + [prefixes.ta_prior_vdm, prefixes.ta_prior_cdm], + RENDER, + )?; + order.narrow_tiling(&tiling)?; + } + orders.push(order)?; + preceding[engine] += 1; + } + Ok(Prepared { + commands: self.commands, + orders, + counts: self.counts, + }) + } +} + +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. pub(crate) fn validate(self, context: &Context<'_>) -> Result { let Prepared { - bytes, - mut resolved, + commands, orders, counts, } = self; - let mut commands = Commands::new(); - let mut vertex = KVec::new(); - let mut fragment = KVec::new(); - let mut compute = KVec::new(); + 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 rem_renders = counts[RENDER]; - let mut rem_computes = counts[COMPUTE]; - for entry in stream(bytes) { - let entry = entry?; - match entry.kind { - SET_VERTEX_ATTACHMENTS => vertex = attachment_list(entry.payload)?, - SET_FRAGMENT_ATTACHMENTS => fragment = attachment_list(entry.payload)?, - SET_COMPUTE_ATTACHMENTS => compute = attachment_list(entry.payload)?, - CMD_RENDER => { - let (packet, _) = render_payload(entry.payload)?; - let cmd = &packet; - let outputs = resolved.next().ok_or(EINVAL)?; - check_render(&mut batch, context, cmd, &vertex, &fragment)?; + 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); } - vdm_vas[vdm_count] = cmd.vdm_ctrl_stream_base; + vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; vdm_count += 1; - rem_renders = rem_renders.checked_sub(1).ok_or(EINVAL)?; - let (vertex_attachments, fragment_attachments) = if rem_renders == 0 { - (core::mem::take(&mut vertex), core::mem::take(&mut fragment)) - } else { - (copy_list(&[&vertex])?, copy_list(&[&fragment])?) - }; - commands.push(Command::Render(KBox::new( - RenderCommand { - cmd: *cmd, - timestamp_outputs: outputs, - vertex_attachments, - fragment_attachments, - }, - GFP_KERNEL, - )?))?; } - CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let cmd = &packet; - check_compute(&mut batch, context, cmd, &compute)?; - let outputs = resolved.next().ok_or(EINVAL)?; - rem_computes = rem_computes.checked_sub(1).ok_or(EINVAL)?; - let attachments = if rem_computes == 0 { - core::mem::take(&mut compute) - } else { - copy_list(&[&compute])? - }; - commands.push(Command::Compute(KBox::new( - ComputeCommand { - cmd: *cmd, - attachments, - timestamp_outputs: outputs, - query_access: cmd.flags & COMPUTE_NO_QUERY_ACCESS == 0, - }, - GFP_KERNEL, - )?))?; + Command::Compute(compute) => { + check_compute(&mut batch, context, &compute.cmd, &compute.attachments)?; } - _ => return Err(EINVAL), } } - if commands.is_empty() { - return Err(EINVAL); + if vdm_count != 0 { + let mut guard = context.vm.read_lock().map_err(|_| EFAULT)?; + batch.flush_locked(&mut guard)?; + gate::vdm_batch_locked(&mut guard, &vdm_vas[..vdm_count])?; + } else { + batch.flush(context.vm)?; } - batch.flush(context.vm)?; - gate::vdm_batch(context.vm, &vdm_vas[..vdm_count])?; Ok(Submission { counts, commands, diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index cfdd218c71b42..f47b4faea4a02 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -136,24 +136,59 @@ impl Progress { } } +/// Resolved in-flight producer target for a hardware ring barrier. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct WaitTarget { + stamp: u32, + /// True if the waited producer flight carries `InitBM` (buffer-manager initialization). + initbm: bool, +} + +/// Selects the hardware ring barrier type for a same-VM handoff. +/// +/// Unlike G15 (`g15/hw.rs: CROSS_ENGINE_HOLD` — "Never both type 0"), G16 (M4 25G83/26B123) +/// does not require a software-job hold on one cross-engine direction when neither side +/// carries `InitBM`. On G16, every stage (CDM, TA, FS) executes its `FINALIZE` +/// micro-sequence — flushing stage caches to the shared coherent fabric — before firmware +/// advances `fw_stamp`, so waiting on `fw_stamp` with `BarrierType::Stamp` (type 0) in both +/// directions (`fs2c` and `c2ta`/`c2fs`) avoids hold bubbles within one VM (same ASID and +/// UAT page tables). Zero-fault M4 J773g runs (13,873 `fs2c` and 20,506 `c2ta` type-0 +/// handoffs) confirm no GPU wedge or hang, while CTS synchronization / pipeline-barrier +/// coverage validates producer-to-consumer memory visibility. +/// +/// Keep `BarrierType::Hold` (type 1) whenever either producer or consumer carries `InitBM` +/// (checked against both the waited target and any live `InitBM` flight). Cross-VM switches, +/// recovery paths, and `query_access` CPU-timestamp waits drain `flights` completely first. +const fn cross_engine_barrier_type(producer_initbm: bool, consumer_initbm: bool) -> BarrierType { + BarrierType::from_stamp_only(!producer_initbm && !consumer_initbm) +} + /// Resolved ring-barrier placement for one render pass (legacy, `FRAGMENT_BARRIERS`, or /// `DRM_ASAHI_RENDER_STAGE_PREFIXES`). #[derive(Copy, Clone, Debug, PartialEq, Eq)] struct RenderBarrierPlan { early: bool, + ta_prev_wait: bool, ta_fs_wait: Option, + fs_render_wait: Option, ta_compute_wait: Option, fs_compute_wait: Option, } /// Computes TA/FS hardware ring barriers for a render command from its flags, prior render -/// FS stamp, and resolved `[ta, fs]` compute wait stamps. +/// FS stamp, resolved render waits (`fs_wait_render`, `ta_wait_fs`), and resolved `[ta, fs]` +/// compute wait stamps. +/// +/// Pipelined renders share one parameter-buffer / UMA epoch (`RENDER_UMA_SLOT`), so TA(N) +/// must still wait on TA(N-1) (`ta_prev_wait`, matching G15's `prev_barrier`) whenever +/// `ta_fs_wait` does not already wait on `prev_fs` (which dominates `prev_ta` via +/// `own_barrier`). Independent FS passes still omit `fs_dep`. fn plan_render_barriers( flags: u32, class_behind: bool, early_tiling: bool, prev_fs: u32, - no_render_barrier: bool, + fs_wait_render: Option, ta_wait_fs: Option, compute_waits: [Option; 2], ) -> RenderBarrierPlan { @@ -161,6 +196,7 @@ fn plan_render_barriers( flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; let frag_only = flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS != 0; + let no_render_barrier = fs_wait_render.is_none(); let early = class_behind && early_tiling && if staged { @@ -168,7 +204,27 @@ fn plan_render_barriers( } else { frag_only || no_render_barrier }; - let ta_fs_wait = if early && staged { ta_wait_fs } else { None }; + let ta_fs_wait = if !class_behind { + None + } else if !early { + if !early_tiling { + Some(prev_fs) + } else if staged { + ta_wait_fs.or(Some(prev_fs)) + } else { + fs_wait_render.or(Some(prev_fs)) + } + } else if staged { + ta_wait_fs + } else { + None + }; + let ta_prev_wait = class_behind && ta_fs_wait != Some(prev_fs); + let fs_render_wait = if class_behind && early && fs_wait_render != ta_fs_wait { + fs_wait_render + } else { + None + }; let [ta_compute_wait, fs_wait] = compute_waits; let fs_compute_wait = if fs_wait != ta_compute_wait { fs_wait @@ -177,7 +233,9 @@ fn plan_render_barriers( }; RenderBarrierPlan { early, + ta_prev_wait, ta_fs_wait, + fs_render_wait, ta_compute_wait, fs_compute_wait, } @@ -234,6 +292,10 @@ pub(crate) struct Flight { pub(crate) uma_submitted: u64, pub(crate) recovery_suspect: bool, pub(crate) recovery_started_ns: u64, + /// First time this suspect flight passed its stage/queue gates with unsettled receipts, and + /// how many consecutive unsettled polls have observed it since then. + pub(crate) gate_passed_ns: Option, + pub(crate) unsettled_polls: u32, /// Publication time, ns. pub(crate) published_ns: u64, /// Published behind another flight. @@ -279,6 +341,8 @@ impl Flight { uma_submitted: 0, recovery_suspect: false, recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, published_ns: 0, behind: false, pb: None, @@ -491,6 +555,10 @@ pub(crate) struct Engine { pub(crate) ta_registered: bool, /// A ready prefix waits only for a record's consumption: repoll sooner. pub(crate) chan_wait: bool, + /// A ready same-VM pending job is blocked solely on flight, pass/compute slot, or work-ring + /// headroom (not cross-VM/InitBM drain, external fences, or CPU timestamp waits): repoll + /// sooner to refill freed slots promptly. + pub(crate) slot_wait: bool, /// An EP 0x20 event arrived with a flight still settling its final receipt: repoll sooner. pub(crate) short_repoll: bool, /// Progress tracking of the oldest compute and render flights. @@ -531,6 +599,7 @@ impl Engine { render_registered: false, ta_registered: false, chan_wait: false, + slot_wait: false, short_repoll: false, progress_flight: [0; 2], progress: [None; 3], @@ -760,6 +829,8 @@ impl Firmware { f.doomed = true; f.recovery_suspect = true; f.recovery_started_ns = now_ns(); + f.gate_passed_ns = None; + f.unsettled_polls = 0; Ok(()) } @@ -786,6 +857,8 @@ impl Firmware { if unfinished { f.recovery_suspect = true; f.recovery_started_ns = now_ns(); + f.gate_passed_ns = None; + f.unsettled_polls = 0; if fault_asid.is_some_and(|asid| asid >= 1 && asid == f.job.vm.slot) { f.doomed = true; } @@ -865,6 +938,7 @@ impl Firmware { let mut batch_published = 0u64; self.engine.chan_wait = false; + self.engine.slot_wait = false; while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() @@ -907,6 +981,11 @@ impl Firmware { match alt { Some(i) => job = self.engine.pending[i].clone(), None => { + self.engine.slot_wait = self + .engine + .pending + .iter() + .any(|cand| self.blocked_on_slot_headroom(cand)); self.engine.stats.hold[0] += 1; break; } @@ -1119,6 +1198,47 @@ impl Firmware { .is_ok_and(|n| self.pools.can_pipeline_within(&job.vm, n))) } + /// Whether `job` is ready to run on the same VM but currently blocked solely on + /// flight-depth or pass/compute-slot headroom (not on cross-VM/InitBM/recovery drain, + /// external sync dependencies, or CPU timestamp-publish waits). + fn blocked_on_slot_headroom(&self, job: &Arc) -> bool { + let e = &self.engine; + if e.flights.is_empty() || self.needs_engine_drain(job) { + return false; + } + let sent = job.progress.sent(); + if job.check_command_dependencies(sent).is_err() { + return false; + } + if e.flights.len() >= super::hw::sizes::FLIGHTS { + return true; + } + match command(job, sent) { + Some(Command::Compute(_)) => { + let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); + compute_count > 0 + && !self.slots.compute_exhausted() + && (compute_count >= params::compute_flights() + || job + .resources + .compute_units() + .is_ok_and(|units| !self.slots.compute_available(units))) + } + Some(Command::Render(_)) => { + let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); + render_count > 0 + && !self.slots.render_exhausted() + && !self.pools.exhausted() + && (render_count >= params::render_flights() + || job + .resources + .render_passes() + .is_ok_and(|passes| !self.slots.pass_available(passes))) + } + None => false, + } + } + /// Whether `job`'s next command may be published behind the flights in flight: /// /// - Compute queues behind healthy same-VM non-InitBM compute and/or render flights (up to @@ -1149,6 +1269,9 @@ impl Firmware { } match command(job, sent) { Some(Command::Compute(c)) => { + // G16 publishes timestamp results into user query-pool BOs on CPU during flight + // 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| { let waits_class = |class: usize| { @@ -1199,17 +1322,17 @@ impl Firmware { } } - /// Resolves a same-queue target stamp 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 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. fn wait_stamp_for_with( &self, job: &Arc, class: usize, target_seq: Option, current: Option<&Flight>, - ) -> Result> { + ) -> Result> { let Some(last) = target_seq else { return Ok(None); }; @@ -1226,7 +1349,10 @@ impl Firmware { if flight.job.command_order(k as u32).is_some_and(|fo| { fo.engine == super::command::COMPUTE && fo.sequence == last }) { - return Ok(Some(*flight.cstamp.get(member).ok_or(EAGAIN)?)); + return Ok(Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + })); } member += 1; } @@ -1235,7 +1361,10 @@ impl Firmware { if j2.command_order(k).is_some_and(|fo| { fo.engine == super::command::COMPUTE && fo.sequence == last }) { - return Ok(Some(*flight.cstamp.get(member).ok_or(EAGAIN)?)); + return Ok(Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + })); } member += 1; } @@ -1243,7 +1372,7 @@ impl Firmware { } return Err(EAGAIN); } - let find_render = |flight: &Flight| -> Option { + let find_render = |flight: &Flight| -> Option { if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { return None; } @@ -1255,17 +1384,20 @@ impl Firmware { .command_order(k) .is_some_and(|fo| fo.engine == super::command::RENDER && fo.sequence == last) { - return Some(flight.r_fs_stamp[member]); + return Some(WaitTarget { + stamp: flight.r_fs_stamp[member], + initbm: flight.initbm, + }); } } None }; - if let Some(stamp) = current.and_then(find_render) { - return Ok(Some(stamp)); + if let Some(target) = current.and_then(find_render) { + return Ok(Some(target)); } for flight in &self.engine.flights { - if let Some(stamp) = find_render(flight) { - return Ok(Some(stamp)); + if let Some(target) = find_render(flight) { + return Ok(Some(target)); } } Err(EAGAIN) @@ -1277,15 +1409,20 @@ impl Firmware { job: &Arc, class: usize, target_seq: Option, - ) -> Result> { + ) -> Result> { self.wait_stamp_for_with(job, class, target_seq, None) } - /// Resolves a same-queue cross-engine barrier target stamp when `job`'s command `index` - /// waits on an in-flight command of `other` engine (`RENDER` -> `fs_target`, `COMPUTE` -> - /// `target`). Returns `Ok(None)` when no cross-engine barrier was requested or the waited - /// prefix has already retired. - fn cross_engine_wait(&self, job: &Arc, index: u32, other: usize) -> Result> { + /// 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. + fn cross_engine_wait( + &self, + job: &Arc, + index: u32, + other: usize, + ) -> Result> { let target_seq = job .command_order(index) .and_then(|o| o.wait_through[other]); @@ -1549,6 +1686,7 @@ impl Firmware { || prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 5 { + self.engine.slot_wait = true; return Err(EAGAIN); } } else { @@ -1557,6 +1695,7 @@ impl Firmware { if c_read >= 256 || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 3 { + self.engine.slot_wait = true; return Err(EAGAIN); } } @@ -1687,14 +1826,14 @@ impl Firmware { }) { return Err(E2BIG); } - let k = self - .slots - .pick_pass_in(&job.resources, &geometry, 0) - .ok_or(EAGAIN)?; + let Some(k) = self.slots.pick_pass_in(&job.resources, &geometry, 0) else { + self.engine.slot_wait = true; + return Err(EAGAIN); + }; f.claims.pass[0] = k as u32; f.claims.pass_count = 1; - f.claims.pass_mask = 1 << k; - self.slots.pass_busy |= 1 << k; + f.claims.pass_mask = 1u64 << k; + self.slots.pass_busy |= 1u64 << k; self.prefix_render(job, r, geometry, &mut prefix, f, behind, class_behind)?; // Batch consecutive ready non-InitBM render passes of the same SUBMIT into // one TA/FS producer advance, one UMA submitted update, and one SubmitRecord. @@ -1756,6 +1895,14 @@ impl Firmware { None, ) .is_err() + || self + .wait_stamp_for_with( + job, + super::command::RENDER, + o2.wait_through[super::command::RENDER], + Some(f), + ) + .is_err() || (staged2 && params::early_tiling() && self @@ -1772,8 +1919,8 @@ impl Firmware { let member = prefix.renders as usize; f.claims.pass[member] = k2 as u32; f.claims.pass_count += 1; - f.claims.pass_mask |= 1 << k2; - self.slots.pass_busy |= 1 << k2; + f.claims.pass_mask |= 1u64 << k2; + self.slots.pass_busy |= 1u64 << k2; self.prefix_render( job, r2, @@ -1825,7 +1972,7 @@ impl Firmware { if render { let a = f.pb_slot as usize; f.pb.as_ref().ok_or(EINVAL)?.expose(); - job.resources.commit_render(); + job.resources.commit_render(f.renders); job.resources .publish_pb_batch(a, f.uma_submitted, f.renders)?; self.pools.publish_flight(a); @@ -2086,25 +2233,36 @@ impl Firmware { )?; } let wait_render = self.cross_engine_wait(job, cmd_index, super::command::RENDER)?; - if let Some(wait_fs) = wait_render { + let fs2c_bar = if let Some(wait_fs) = wait_render { + // Check producer InitBM explicitly in addition to the scheduler drain guard so + // FS -> CDM handoff: downgrade to `BarrierType::Stamp` (type 0) only when neither + // the waited render nor any live flight carries `InitBM`; G16 FS `FINALIZE` flushes + // caches before advancing `fw_stamp[1]` (see `cross_engine_barrier_type`). + let producer_initbm = wait_fs.initbm || self.engine.flights.iter().any(|fl| fl.initbm); + let bar_type = cross_engine_barrier_type(producer_initbm, false); let bar = encode::barrier( self.graph.render.fw_stamp[1].va, - wait_fs, + wait_fs.stamp, 0x71, target, 0, - BarrierType::Hold, + bar_type, ); s.barrier.write(0, &bar)?; - } + Some((wait_fs.stamp, bar_type)) + } else { + None + }; f.uma_submitted = submitted; f.csubmitted[member] = submitted; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); wmb(); - if let Some(wait_fs) = wait_render { + if let Some((wait_fs, bar_type)) = fs2c_bar { g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; - self.engine.stats.fs2c0 += 1; + if bar_type == BarrierType::Stamp { + self.engine.stats.fs2c0 += 1; + } f.cwait[member] = wait_fs; } else { f.cwait[member] = 0; @@ -2140,10 +2298,15 @@ impl Firmware { let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); let has_prior_render = class_behind || member > 0; - let (prev_ta, prev_fs) = if member > 0 { - (pf.last_ta, pf.last_fs) + let prev_ta = if member > 0 { + pf.last_ta } else { - (self.engine.ta_target, self.engine.fs_target) + self.engine.ta_target + }; + let prev_fs = if member > 0 { + pf.last_fs + } else { + self.engine.fs_target }; let order = job.command_order(cmd_index); let staged = cmd.cmd.flags @@ -2161,6 +2324,22 @@ impl Firmware { order.and_then(|o| o.wait_through[super::command::COMPUTE]), None, )?; + let fs_wait_render = if has_prior_render { + match order { + Some(o) => self.wait_stamp_for_with( + job, + super::command::RENDER, + o.wait_through[super::command::RENDER], + Some(f), + )?, + None => Some(WaitTarget { + stamp: prev_fs, + initbm: false, + }), + } + } else { + None + }; let ta_wait_fs = if has_prior_render && staged && params::early_tiling() { self.wait_stamp_for_with( job, @@ -2176,9 +2355,12 @@ impl Firmware { has_prior_render, params::early_tiling(), prev_fs, - order.is_some_and(|o| o.wait_through[super::command::RENDER].is_none()), - ta_wait_fs, - [ta_wait_compute, fs_wait_compute], + fs_wait_render.map(|w| w.stamp), + ta_wait_fs.map(|w| w.stamp), + [ + ta_wait_compute.map(|w| w.stamp), + fs_wait_compute.map(|w| w.stamp), + ], ); // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots @@ -2292,26 +2474,28 @@ impl Firmware { r.ring[0].w64(8 * pf.ta_head as usize, epoch.initbm.va)?; pf.ta_head = (pf.ta_head + 1) % cap; } - // When pipelining behind an in-flight or same-batch same-VM render, insert explicit - // hardware ordering barriers on the TA/FS rings. Fragment-only, barrier-free, or staged - // renders whose TA prefix stops before the prior FS overlap TA(N) with FS(N-1) (TA waits - // on prior TA plus any older in-flight FS named by `ta_wait_through`; FS waits on prior - // FS then own TA); otherwise TA(N) waits on prior FS to preserve full vertex visibility. - if has_prior_render { - // Pipelined same-VM non-InitBM render->render barriers wait on the producer's - // firmware stamp only (type 0), matching `own_barrier` and G15's - // `RENDER_INTERNAL_HOLD = 0`, so consecutive TA/FS stages hand off without a - // software-job hold bubble. Cross-engine barriers (`fs2c`/`c2ta`) stay `Hold`. - let render_bar = BarrierType::from_stamp_only(!init_buffer); - let (wait_va, wait_stamp, wait_event) = if plan.early { - (r.fw_stamp[0].va, prev_ta, 0x70) - } else { - (r.fw_stamp[1].va, prev_fs, 0x71) - }; + // Pipelined same-VM render->render and cross-engine (CDM->TA, CDM->FS) barriers use + // `BarrierType::Stamp` (type 0) only when neither producer, any live flight, nor this + // consumer carries `InitBM`: G16 `FINALIZE` flushes producer caches before advancing + // `fw_stamp` (unlike G15's `CROSS_ENGINE_HOLD`; see `cross_engine_barrier_type`). + // Cross-VM transitions and recovery paths drain completely before publishing. + let producer_initbm = pf.initbm + || self.engine.flights.iter().any(|fl| fl.initbm) + || ta_wait_compute.is_some_and(|w| w.initbm) + || fs_wait_compute.is_some_and(|w| w.initbm) + || fs_wait_render.is_some_and(|w| w.initbm) + || ta_wait_fs.is_some_and(|w| w.initbm); + let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer); + // Pipelined renders share one parameter-buffer / UMA epoch (`RENDER_UMA_SLOT`), so keep + // the TA(N-1)->TA(N) `prev_barrier` (matching G15) whenever `plan.ta_fs_wait` does not + // already serialize behind `prev_fs`. Emit `ta_fs_barrier` only when `plan.ta_fs_wait` + // names an in-flight FS stamp, and `fs_dep` only when `plan.fs_render_wait` names an + // in-flight FS dependency not already dominated by TA. + if plan.ta_prev_wait { let prev = encode::barrier( - wait_va, - wait_stamp, - wait_event, + r.fw_stamp[0].va, + prev_ta, + 0x70, target, work::barrier::RENDER_WAIT_UUID, render_bar, @@ -2319,33 +2503,35 @@ impl Firmware { p.prev_barrier.write(0, &prev)?; r.ring[0].w64(8 * pf.ta_head as usize, p.prev_barrier.va)?; pf.ta_head = (pf.ta_head + 1) % cap; - if plan.early { - if let Some(older_fs) = plan.ta_fs_wait { - let ta_fs = encode::barrier( - r.fw_stamp[1].va, - older_fs, - 0x71, - target, - work::barrier::RENDER_WAIT_UUID, - render_bar, - ); - p.ta_fs_barrier.write(0, &ta_fs)?; - r.ring[0].w64(8 * pf.ta_head as usize, p.ta_fs_barrier.va)?; - pf.ta_head = (pf.ta_head + 1) % cap; - } - let dep = encode::barrier( - r.fw_stamp[1].va, - prev_fs, - 0x71, - target, - work::barrier::RENDER_WAIT_UUID, - render_bar, - ); - p.fs_dep.write(0, &dep)?; - r.ring[1].w64(8 * pf.fs_head as usize, p.fs_dep.va)?; - pf.fs_head = (pf.fs_head + 1) % cap; - self.engine.stats.early += 1; - } + } + if let Some(wait_fs) = plan.ta_fs_wait { + let ta_fs = encode::barrier( + r.fw_stamp[1].va, + wait_fs, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.ta_fs_barrier.write(0, &ta_fs)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.ta_fs_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + } + if let Some(wait_fs) = plan.fs_render_wait { + let dep = encode::barrier( + r.fw_stamp[1].va, + wait_fs, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.fs_dep.write(0, &dep)?; + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_dep.va)?; + pf.fs_head = (pf.fs_head + 1) % cap; + } + if plan.early { + self.engine.stats.early += 1; } if let Some(wait_c) = plan.ta_compute_wait { let cbar = encode::barrier( @@ -2354,12 +2540,14 @@ impl Firmware { 15, target, work::barrier::RENDER_WAIT_UUID, - BarrierType::Hold, + render_bar, ); p.compute_barrier.write(0, &cbar)?; r.ring[0].w64(8 * pf.ta_head as usize, p.compute_barrier.va)?; pf.ta_head = (pf.ta_head + 1) % cap; - self.engine.stats.c2ta0 += 1; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } } if let Some(wait_c) = plan.fs_compute_wait { let fcbar = encode::barrier( @@ -2368,12 +2556,14 @@ impl Firmware { 15, target, work::barrier::RENDER_WAIT_UUID, - BarrierType::Hold, + render_bar, ); p.fs_compute_barrier.write(0, &fcbar)?; r.ring[1].w64(8 * pf.fs_head as usize, p.fs_compute_barrier.va)?; pf.fs_head = (pf.fs_head + 1) % cap; - self.engine.stats.c2ta0 += 1; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } } // The paired fragment always requires the native explicit TA dependency. let own = encode::barrier( diff --git a/drivers/gpu/drm/asahi/g16/event.rs b/drivers/gpu/drm/asahi/g16/event.rs index f4fd9b723b634..6716d3332a539 100644 --- a/drivers/gpu/drm/asahi/g16/event.rs +++ b/drivers/gpu/drm/asahi/g16/event.rs @@ -104,13 +104,46 @@ impl Events { // SAFETY: ktime_get has no preconditions. let now = unsafe { bindings::ktime_get() } as u64; let mut error = None; + let mut drained = false; + let flush_read = |ring: &Ring, read: u32| -> Result { + mb(); + ring.state.w32(STATE_READ, read)?; + wmb(); + Ok(()) + }; while read != producer { - let words = Self::words(ring, read)?; - match words[0] { + let base = read as usize * rings::EVENT_RECORD; + let kind = match ring.ring.r32(base) { + Ok(kind) => kind, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; + match kind { 1 => { + // Type 1 carries 128 completion bits across words 1..=4; STAGE_EVENTS + // ([0x70, 0x71, 15]) only inspects word 1 (compute 15) and word 4 (TA/FS). + let (w1, w4) = match ring.ring.r32(base + 4).and_then(|w1| { + Ok((w1, ring.ring.r32(base + 16)?)) + }) { + Ok(pair) => pair, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; for (stage, event) in STAGE_EVENTS.iter().enumerate() { - let word = 1 + *event as usize / 32; - if words[word] & (1u32 << (*event % 32)) == 0 { + let bits = match 1 + *event as usize / 32 { + 1 => w1, + 4 => w4, + _ => continue, + }; + if bits & (1u32 << (*event % 32)) == 0 { continue; } self.event_ns[stage] = now; @@ -123,6 +156,15 @@ impl Events { } } 4 => { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; self.recovery_started_ns.get_or_insert(now); self.last_error = Some(ErrorEvent { kind: 4, @@ -133,6 +175,15 @@ impl Events { dev_warn!(dev, "M4 firmware recovery event: {:08x?}\n", words); } kind => { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; // The qualified M4 provider accepts only stage and recovery events. // Do not apply another firmware's context-kill or PB-growth protocol. dev_err!( @@ -146,19 +197,46 @@ impl Events { } } read = (read + 1) % RING_SLOTS; - mb(); - ring.state.w32(STATE_READ, read)?; - wmb(); + drained = true; } + flush_read(ring, read)?; error.map_or(Ok(()), Err) } /// Preserve recovery statistics instead of silently discarding their notification. pub(crate) fn drain_statistics(&mut self, dev: &device::Device, ring: &Ring) -> Result { let (mut read, producer) = Self::indices(ring)?; + if read == producer { + return Ok(()); + } + let mut drained = false; + let flush_read = |ring: &Ring, read: u32| -> Result { + mb(); + ring.state.w32(STATE_READ, read)?; + wmb(); + Ok(()) + }; while read != producer { - let words = Self::words(ring, read)?; - if words[0] == 0x16 { + let base = read as usize * rings::EVENT_RECORD; + let kind = match ring.ring.r32(base) { + Ok(kind) => kind, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; + if kind == 0x16 { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; // SAFETY: ktime_get has no preconditions. let now = unsafe { bindings::ktime_get() } as u64; self.recovery_started_ns.get_or_insert(now); @@ -167,10 +245,9 @@ impl Events { dev_warn!(dev, "M4 firmware recovery statistics: {:08x?}\n", words); } read = (read + 1) % RING_SLOTS; - mb(); - ring.state.w32(STATE_READ, read)?; - wmb(); + drained = true; } + flush_read(ring, read)?; Ok(()) } } diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 1bbc1fafa0b10..18a3c8065537a 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -425,8 +425,15 @@ const GLOBALS_FIXED: &[(usize, u32)] = &[ (0x9b8, 2), (0x9bc, 40), (0x9c0, 5), - (0x9c8, 40), - (0x9cc, 50), + // Firmware DM2 (compute) progress-watchdog thresholds (~4 ms/tick): + // - 0x9c8 (26B123 0x9cc): secondary DM2 soft-preempt watchdog, raised from 40 (~0.16 s) + // to 750 (~3.0 s) so legitimate long/contended compute dispatches (e.g. 1.5 s solo + // workloads) complete without premature kill while staying below the 5 s host fail-stop. + // - 0x9cc (26B123 0x9d0): primary DM2 recovery watchdog, raised from 50 (~0.20 s) to 800 + // (~3.2 s) so legitimate compute dispatches complete while real hangs still trigger + // firmware recovery well before the 5 s host fail-stop deadline. + (0x9c8, 750), + (0x9cc, 800), ]; /// Fixed 25G83 POWER_PERFORMANCE offsets remapped into every ABI; shared by `encode_for` and diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index f3dfc62c0566d..f3017f1f125ca 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -17,7 +17,7 @@ use core::sync::atomic::{AtomicU32, Ordering}; use kernel::prelude::*; -use super::{command::cover, command::USC_WINDOW, params}; +use super::{command::cover_locked, command::USC_WINDOW, params}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; @@ -59,18 +59,31 @@ struct Window { impl Window { /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page - /// unless the record crosses it). Unreadable memory: EFAULT. - fn words(&mut self, vm: &mmu::Vm, va: u64, count: usize) -> Result<[u32; 10]> { + /// or an optional root-stream `limit` unless the record crosses it) under an already-held + /// VM read lock. Unreadable memory: EFAULT. + fn words( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + va: u64, + count: usize, + limit: Option, + ) -> Result<[u32; 10]> { let n = count.checked_mul(4).filter(|&n| n <= 40).ok_or(EINVAL)?; let end = va.checked_add(n as u64).ok_or(EINVAL)?; let cached = self.len != 0 && va >= self.va && end <= self.va + self.len as u64; if !cached { let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); - let len = n.max(self.bytes.len().min(in_page)); + let mut max_len = self.bytes.len().min(in_page); + if let Some(limit_va) = limit { + let rem = usize::try_from(limit_va.saturating_sub(va)).unwrap_or(usize::MAX); + max_len = max_len.min(rem); + } + let len = n.max(max_len); let cover_end = va.checked_add(len as u64).ok_or(EINVAL)?; - cover(vm, va, cover_end, true, false)?; + cover_locked(guard, va, cover_end, true, false)?; self.len = 0; - vm.read_user(va, &mut self.bytes[..len]) + guard + .read_user(va, &mut self.bytes[..len]) .map_err(|_| EFAULT)?; self.va = va; self.len = len; @@ -89,7 +102,12 @@ impl Window { /// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. /// `checked` caches the last proven program page. -fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> Result { +fn program( + guard: &mut mmu::VmReadGuard<'_>, + usc: u64, + address: u64, + checked: &mut Option, +) -> Result { if address < usc || address - usc >= USC_WINDOW || address & 63 != 0 { return Err(EINVAL); } @@ -98,29 +116,29 @@ fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> R if *checked == Some(page) { return Ok(()); } - cover(vm, address, address + 64, true, false)?; + cover_locked(guard, address, address + 64, true, false)?; *checked = Some(page); Ok(()) } -/// VDM admission for a batch of root streams under a single VM read lock, caching up to -/// 256 intra-page bytes across adjacent VDM roots (for example in a multi-pass render SUBMIT). -/// Each normal root stream opens with the G16 barrier, with or without the USC cache -/// invalidate. -pub(crate) fn vdm_batch(vm: &mmu::Vm, vas: &[u64]) -> Result { +/// VDM admission for a batch of root streams under an already-held VM read lock. +/// Reads only the 4-byte root word for a single pass to minimize PoC cache maintenance, +/// and caches up to 256 intra-page bytes across multi-pass batches. Each normal root stream +/// opens with the G16 barrier, with or without the USC cache invalidate. +pub(crate) fn vdm_batch_locked(guard: &mut mmu::VmReadGuard<'_>, vas: &[u64]) -> Result { if vas.is_empty() || !params::stream_gate() { return Ok(()); } - let mut guard = vm.read_lock().map_err(|_| EFAULT)?; let mut win_va = 0u64; let mut win_len = 0usize; let mut buf = [0u8; 256]; + let max_read = if vas.len() == 1 { 4 } else { buf.len() }; for &va in vas { let end = va.checked_add(4).ok_or(EINVAL)?; let cached = win_len != 0 && va >= win_va && end <= win_va + win_len as u64; if !cached { let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); - let len = buf.len().min(in_page); + let len = max_read.min(in_page); if len < 4 { return Err(EINVAL); } @@ -165,6 +183,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { let mut power = 1u64; let mut first = true; let mut resched = 0; + let mut guard: Option> = None; loop { if first { first = false; @@ -180,10 +199,13 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } } if resched == 0 { - // No VM lock is held between reads. Keep a long userspace stream - // preemptible and allow its submitting task to be interrupted. + // Release the VM lock and clear cached window/program proofs before + // rescheduling so any mapping change while unlocked is re-verified. // might_sleep() includes might_resched() (cond_resched on voluntary kernels). // It is a real scheduling point, not only a debug assertion. + guard = None; + window.len = 0; + checked = None; kernel::task::might_sleep(); if kernel::current!().signal_pending() { return Err(ERESTARTSYS); @@ -191,14 +213,19 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { resched = CDM_RESCHED_RECORDS; } resched -= 1; + let guard = match guard.as_mut() { + Some(guard) => guard, + None => guard.insert(vm.read_lock().map_err(|_| EFAULT)?), + }; let root_bytes = |va: u64, bytes: u64| -> Result { if !linked && (va < base || va.checked_add(bytes).is_none_or(|at| at > end)) { return Err(EINVAL); } Ok(()) }; + let limit = (!linked).then_some(end); root_bytes(va, 4)?; - let w = window.words(vm, va, 1)?; + let w = window.words(guard, va, 1, limit)?; if w[0] == CDM_TERMINATE { return Ok(()); } @@ -218,7 +245,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } if w[0] & 0xffff0000 == CDM_LINK { root_bytes(va, 8)?; - let w = window.words(vm, va, 2)?; + let w = window.words(guard, va, 2, limit)?; let target = (u64::from(w[0] & 0xffff) << 32) | u64::from(w[1]); if target & 3 != 0 || target == va { return Err(reject("CDM link", va, &w)); @@ -238,9 +265,9 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { _ => return Err(reject("CDM launch mode", va, &w)), }; root_bytes(va, (words * 4) as u64)?; - let w = window.words(vm, va, words)?; + let w = window.words(guard, va, words, limit)?; let address = (u64::from(w[1] >> 22) << 38) | (u64::from(w[2]) << 6); - match program(vm, usc, address, &mut checked) { + match program(guard, usc, address, &mut checked) { Err(error) if error == EINVAL => return Err(reject("CDM program", va, &w)), result => result?, } @@ -260,8 +287,8 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { if indirect & 3 != 0 { return Err(reject("CDM indirect parameters", va, &w)); } - cover( - vm, + cover_locked( + guard, indirect, indirect.checked_add(bytes).ok_or(EINVAL)?, true, diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 684d96df83bdc..d1215627955c4 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -640,17 +640,23 @@ pub(crate) mod client { pub(crate) const PB_PAGE_LIST: u64 = 0x7012040000; pub(crate) const PB_PAGE_LIST_SIZE: u64 = 0x8000; - // Host-chosen client VA layout for render pass slots within 0x7020000000..0x7040000000 - // (512 MiB). Firmware takes explicit 64-bit VAs for each pass object rather than - // indexing by stride. One pass slot spans +0x0..+0x1c00000 (28 MiB: TILEMAP at +0x1400000 - // plus TILEMAP_SIZE = 0x800000), rounded up to a 32 MiB power-of-two stride (4 MiB guard) - // so 16 slots fill the 512 MiB window (matching COMPUTE_UNITS = 16). + // Host-chosen client VA layout for render pass resources within 0x7020000000..0x7040000000 + // (512 MiB). Firmware takes explicit 64-bit VAs for each pass object rather than indexing + // by stride: + // - Base slots `0..BASE_RENDER_SLOTS` keep 32 MiB intervals with full 16 MiB TPC / 8 MiB + // tilemap capacity for worst-case geometries. + // - Extension slots `BASE_RENDER_SLOTS..RENDER_SLOTS` pack into 8 MiB intervals starting at + // `EXT_PASS_BASE` (`0x7024000000`) with 2 MiB TPC / 1 MiB tilemap capacity, fitting 48 + // total pass slots (`0x7020000000..0x703b000000`, leaving 80 MiB free below 0x7040000000). pub(crate) const FS_WORK_PAGE: u64 = 0x7020000000; pub(crate) const FS_WORK_OFF: u64 = 0; pub(crate) const TA_WORK_PAGE: u64 = 0x7020004000; pub(crate) const TA_WORK_OFF: u64 = 0; pub(crate) const WORK_STRIDE: u64 = 0x02000000; pub(crate) const PASS_STRIDE: u64 = WORK_STRIDE; + pub(crate) const EXT_PASS_STRIDE: u64 = 0x00800000; + pub(crate) const EXT_PASS_BASE: u64 = + FS_WORK_PAGE + (super::sizes::BASE_RENDER_SLOTS as u64) * PASS_STRIDE; pub(crate) const PRE0_PAGE: u64 = 0x7020080000; pub(crate) const PRE1_PAGE: u64 = 0x70200a0000; pub(crate) const PRE2_PAGE: u64 = 0x70200c0000; @@ -669,6 +675,27 @@ pub(crate) mod client { pub(crate) const TPC_SLOT_SIZE: u64 = 0x200000; pub(crate) const TILEMAP_SLOT_SIZE: u64 = 0x100000; pub(crate) const TPC_SLOT_STRIDE: u64 = WORK_STRIDE; + pub(crate) const EXT_TILEMAP_OFF: u64 = (TPC - FS_WORK_PAGE) + TPC_SLOT_SIZE; + + pub(crate) const fn pass_base(i: u64) -> u64 { + if i < super::sizes::BASE_RENDER_SLOTS as u64 { + FS_WORK_PAGE + i * PASS_STRIDE + } else { + EXT_PASS_BASE + (i - super::sizes::BASE_RENDER_SLOTS as u64) * EXT_PASS_STRIDE + } + } + + pub(crate) const fn pass_off(i: u64) -> u64 { + pass_base(i) - FS_WORK_PAGE + } + + pub(crate) const fn pass_tilemap(i: u64) -> u64 { + if i < super::sizes::BASE_RENDER_SLOTS as u64 { + TILEMAP + i * PASS_STRIDE + } else { + pass_base(i) + EXT_TILEMAP_OFF + } + } pub(crate) const CT: u64 = 0x7080000000; pub(crate) const CT_STRIDE: u64 = 0x1000000; pub(crate) const CT_SIZE: u64 = 0x400000; @@ -695,12 +722,27 @@ pub(crate) mod sizes { assert!(super::client::render_descriptor(3) + 0x4000 <= super::client::FS_WORK_PAGE); const _: () = assert!(super::client::render_descriptor(5) + 0x4000 <= super::client::render_base(0)); + /// Worst-case firmware work-ring entries consumed per pipelined render pass on TA + /// (`prev_barrier`, `ta_fs_barrier`, `compute_barrier`, `ta_work`) and FS (`fs_dep`, + /// `fs_compute_barrier`, `own_barrier`, `fs_work`). `InitBM` runs only on an idle engine + /// (`initbm` + `ta_work` = 2 entries). + pub(crate) const MAX_RENDER_RING_ENTRIES: usize = 4; + /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + `work`). + pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 2; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; - /// Retained render pass slots per VM at most (host client-VA budget: 512 MiB / 32 MiB - /// stride = 16, not a firmware limit). A slot is reused only after a later render retired - /// (displacing it), so `n` slots keep up to `n - 1` renders in flight. - pub(crate) const RENDER_SLOTS: usize = 16; + /// Retained render pass slots per VM at most. A slot is reused only after a later render + /// retired (displacing it), so `n` slots keep up to `n - 1` renders in flight. + /// + /// Sized inside both the host client-VA window (`0x7020000000..0x7040000000`) and firmware + /// queue/recovery capacities: `47` in-flight passes consume at most `47 * 4 = 188` entries of + /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable, ring cap `63`), share + /// hardware UMA slot `RENDER_UMA_SLOT` (33) via the active PB/UMA descriptor, post at most + /// `FLIGHTS = 32` `SubmitRecord`s (vs `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay + /// far below the firmware recovery `snapshot_entries = 448` limit. + pub(crate) const RENDER_SLOTS: usize = 48; + const _: () = assert!(RENDER_SLOTS >= BASE_RENDER_SLOTS && RENDER_SLOTS <= 64); + const _: () = assert!((RENDER_SLOTS - 1) * MAX_RENDER_RING_ENTRIES < QUEUE_CAP as usize); const _: () = assert!(super::client::AUX + 0x20000 <= super::client::SCENE_LIST); const _: () = assert!(super::client::SCENE_LIST + 0x4000 <= super::client::TPC); const _: () = assert!(super::client::TPC + super::client::TPC_SIZE <= super::client::TILEMAP); @@ -709,13 +751,14 @@ pub(crate) mod sizes { <= super::client::FS_WORK_PAGE + super::client::PASS_STRIDE ); const _: () = assert!( - super::client::FS_WORK_PAGE + (RENDER_SLOTS as u64) * super::client::PASS_STRIDE - <= 0x7040000000 + super::client::EXT_TILEMAP_OFF + super::client::TILEMAP_SLOT_SIZE + <= super::client::EXT_PASS_STRIDE ); + const _: () = assert!(super::client::pass_base(RENDER_SLOTS as u64) <= 0x7040000000); pub(crate) const CT_BUFS: usize = 0; pub(crate) const CLUSTER_PB_PAGES: u32 = 0x3c; pub(crate) const MAX_ATTACHMENTS: usize = 16; - pub(crate) const MAX_CLIENT: usize = 320; + pub(crate) const MAX_CLIENT: usize = 512; pub(crate) const PB_PAGES: u32 = 8192; pub(crate) const PB_BLOCKS: u32 = 2048; pub(crate) const PB_LIST_RECORDS: u32 = 4096; @@ -724,10 +767,19 @@ pub(crate) mod sizes { /// each other on their engine rings while cross-VM and cross-engine transitions drain. pub(crate) const FLIGHTS: usize = 32; /// Retained compute units per VM at most; each unit owns its own hardware UMA slot - /// (`COMPUTE_UMA_SLOT + index`). A unit is reused only after a later publication retired - /// (it displaced the unit), so `n` units keep up to `n - 1` compute commands in flight. - pub(crate) const COMPUTE_UNITS: usize = 16; + /// (`COMPUTE_UMA_SLOT + index`, fitting in `1..RENDER_UMA_SLOT = 33`). A unit is reused + /// only after a later publication retired (it displaced the unit), so `n` units keep up to + /// `n - 1` compute commands in flight (`17 * 2 = 34` entries of the 256-entry compute work + /// ring `QUEUE_CAP`, well inside `AHEAD_RECORDS = 128`, `RING_SLOTS = 256`, and recovery + /// `snapshot_entries = 448`). + pub(crate) const COMPUTE_UNITS: usize = 18; + const _: () = assert!(COMPUTE_UNITS >= 2); + const _: () = assert!((COMPUTE_UNITS - 1) * MAX_COMPUTE_RING_ENTRIES < QUEUE_CAP as usize); const _: () = assert!(super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP); + const _: () = assert!( + super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) + <= super::engine::RENDER_UMA_SLOT + ); /// Maximum jobs folded into one barrier-free compute horizon prefix. pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; /// Jobs admitted to the engine per logical queue: enough to keep a queue's commands diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 98dc58c951296..1464f1151738f 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -302,6 +302,7 @@ impl Job { // before signalling; later accepted ordinals must not jump this hole. self.queue.cancel(&self.orders, self.progress.sent()); self.finish(Err(ECANCELED), false); + shared.wake_publish(); return; } // `Shared::submit`: enqueue, publish and rearm under the device lock, diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 024acf667f1ac..6be4c343beba1 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -81,9 +81,10 @@ use core::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicU64, use kernel::{ c_str, device::{self, Core}, - impl_has_delayed_work, impl_has_work, new_delayed_work, new_mutex, new_work, of, platform, + impl_has_delayed_work, impl_has_work, new_delayed_work, new_mutex, new_spinlock, new_work, of, + platform, prelude::*, - sync::{aref::ARef, Arc, Mutex}, + sync::{aref::ARef, Arc, Mutex, SpinLock}, time::hrtimer::{ArcHrTimerHandle, HrTimer}, uapi, workqueue::{DelayedWork, OwnedQueue, Work, WorkItem}, @@ -191,6 +192,8 @@ impl platform::Driver for Driver { const POLL_WORK: u64 = 0; /// Work item ID of the submitter-pinned fast event poll work. const FAST_POLL_WORK: u64 = 1; +/// Work item ID of the asynchronous displaced pass-slot scrub work. +const SCRUB_WORK: u64 = 2; /// Capacity hint for `drm_syncobj_wait` during active submit bursts (mirroring G17's wait hint). const WAIT_UTIL_MIN: u32 = 512; const WAIT_HINT_MS: u32 = 8; @@ -212,6 +215,9 @@ pub(crate) struct Shared { pub(crate) crashed: AtomicBool, /// Set by the firmware's EP 0x20 event message; consumed by the poll work. pub(crate) evented: AtomicBool, + /// 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, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, /// Monotonic timestamp (ns) of the previous submit, for active-burst wait hints. @@ -252,12 +258,18 @@ pub(crate) struct Shared { sleep_commit: AtomicPtr, /// Dedicated high-priority per-CPU workqueue for immediate completion polling. pub(crate) events: OwnedQueue, + /// Dedicated unbound workqueue for asynchronous off-lock pass-slot WC scrubbing. + pub(crate) scrub_wq: OwnedQueue, #[pin] pub(crate) orphan: Mutex>>, #[pin] pub(crate) poll: DelayedWork, #[pin] pub(crate) fast_poll: Work, + #[pin] + pub(crate) scrub_queue: SpinLock, + #[pin] + pub(crate) scrub_work: Work, // --- The completion/repoll hrtimer and the handle of its current expiry (dropping it // cancels the expiry; see `Shared::rearm`). --- #[pin] @@ -277,6 +289,10 @@ impl_has_work! { impl HasWork for Shared { self.fast_poll } } +impl_has_work! { + impl HasWork for Shared { self.scrub_work } +} + impl WorkItem for Shared { type Pointer = Arc; fn run(this: Arc) { @@ -299,6 +315,13 @@ impl WorkItem for Shared { } } +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + this.run_scrubs(); + } +} + impl Shared { /// Records the submitting CPU and burst cadence for completion placement and wait hints. pub(crate) fn note_submitter(&self) { @@ -341,6 +364,15 @@ impl Shared { self.poll_now(); } + /// Marks external publish-relevant state dirty and queues a poll so pending jobs re-evaluate + /// without waiting for the 1 ms housekeeping tick. + pub(crate) fn wake_publish(self: &Arc) { + self.publish_wake.store(true, Ordering::Release); + if self.started.load(Ordering::Acquire) && !self.sleeping.load(Ordering::Acquire) { + self.poll_now(); + } + } + /// Latches the fail-stop state. pub(crate) fn fail_stop(&self, error: Error) { let _ = @@ -473,6 +505,7 @@ impl Gpu { // the platform-device field. Retain the typed DRM device before that point. let drm_device: ARef = dev.into(); let events = OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)?; + let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -481,6 +514,7 @@ impl Gpu { wedged_notified: AtomicBool::new(false), crashed: AtomicBool::new(false), evented: AtomicBool::new(false), + publish_wake: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), last_submit_ns: AtomicU64::new(0), wait_hint_streak: AtomicU32::new(0), @@ -500,9 +534,12 @@ impl Gpu { sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, + scrub_wq, orphan <- new_mutex!(None, "g16::Shared::orphan"), poll <- new_delayed_work!("g16::Shared::poll"), fast_poll <- new_work!("g16::Shared::fast_poll"), + scrub_queue <- new_spinlock!(slots::ScrubQueue::new(), "g16::Shared::scrub_queue"), + scrub_work <- new_work!("g16::Shared::scrub_work"), resnap <- HrTimer::new(), resnap_handle <- new_mutex!(None, "g16::Shared::resnap_handle"), state <- new_mutex!(None, "g16::Shared::state"), @@ -731,6 +768,7 @@ impl gpu::Gpu for Gpu { } fn vm_closed(&self, vm: &mmu::Vm) { self.vms.close(vm.id()); + self.shared.wake_publish(); } fn new_queue( diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index c44e1ff5b0c0c..6439a9a6ce637 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -40,7 +40,7 @@ pub(crate) fn pb_posted_blocks(heap_blocks: u32) -> u32 { /// Compute units of a VM that submits compute back to back. pub(crate) fn compute_units() -> usize { - 16usize.clamp(2, hw::sizes::COMPUTE_UNITS) + hw::sizes::COMPUTE_UNITS } /// Compute commands in flight at most. @@ -48,11 +48,18 @@ pub(crate) fn compute_flights() -> usize { 32usize.clamp(1, hw::sizes::FLIGHTS) } -/// Render commands in flight at most (`RENDER_SLOTS - 1` so one slot holds displacement). +/// Render commands in flight at most: bounded by both retained pass slots +/// (`RENDER_SLOTS - 1`, leaving one slot for displacement) and firmware TA/FS work-ring +/// capacity (`(QUEUE_CAP - 1) / MAX_RENDER_RING_ENTRIES`, worst case 4 ring entries per pass). +/// Decoupled from `hw::sizes::FLIGHTS` because multi-pass render batches pack multiple passes +/// into one `Flight`. pub(crate) fn render_flights() -> usize { + let ring_cap = + (hw::sizes::QUEUE_CAP as usize).saturating_sub(1) / hw::sizes::MAX_RENDER_RING_ENTRIES; hw::sizes::RENDER_SLOTS .saturating_sub(1) - .clamp(1, hw::sizes::FLIGHTS) + .min(ring_cap) + .max(1) } /// Repoll while a ready prefix waits for record consumption, us. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index f00ee3ab3fbe1..4ed5e8b49fac0 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -36,14 +36,14 @@ use super::engine::{complete, now_ns, rmb, Flight, Lap}; use super::fw::graph::{notifier, notifier_page, qstate}; use super::fw::work::compute; use super::job::{self, Completions, Job}; -use super::recovery::logic::Retirement; +use super::recovery::logic::{Retirement, ABORT_GRACE_NS}; use super::regs::EngineState; -use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK}; +use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK, SCRUB_WORK}; use crate::module_parameters; /// Cadence of periodic housekeeping (power governor, window health, administrative hang check). const HOUSEKEEPING_NS: u64 = 1_000_000; -/// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/5 us, ~48 us total). +/// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/3/4/5 us, 45 us total). const EVENT_RETIRE_POLLS: u32 = 11; /// Minimum interval between 1-jiffy delayed-work safety backup rearms (2 ms). const BACKUP_REARM_NS: u64 = 2_000_000; @@ -145,19 +145,21 @@ impl Shared { self.fail_stop(error); } } - let allow_stage = firmware.recovery.failed().is_none() && !firmware.engine.frozen; + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); } job::complete_all(done); - if scrubs.run() { - self.poll_now(); - } + self.enqueue_scrubs(scrubs); if !retry_tail { break; } let delay_us = match step { 0 => 1, 1 => 2, + 2 => 3, + 3 => 4, _ => 5, }; tail -= 1; @@ -215,7 +217,7 @@ impl Shared { pub_res = firmware.session.transport().and_then(|()| { let retired_any = firmware.retire_once(done)?; firmware.answer_growth()?; - if firmware.recovery.receipt_fault || firmware.recovery_pending()? { + if firmware.recovery.receipt_fault || recovery_pending { firmware.check_hangs(done)?; } if was_evented && !retired_any && !firmware.engine.flights.is_empty() { @@ -224,7 +226,7 @@ impl Shared { && firmware.oldest_terminal_events() == term_before && !firmware.oldest_stamp_reached() && !firmware.recovery.receipt_fault - && !firmware.recovery_pending().unwrap_or(true); + && !recovery_pending; if !non_terminal_only { self.evented.store(true, Ordering::Release); } @@ -273,13 +275,13 @@ impl Shared { let mut state = self.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; let res = self.submit_locked(firmware, job, &mut done); - let allow_stage = firmware.recovery.failed().is_none() && !firmware.engine.frozen; + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); (res, firmware.slots.stage_and_take_scrubs(allow_stage)) }; job::complete_all(done); - if scrubs.run() { - self.poll_now(); - } + self.enqueue_scrubs(scrubs); drop(signalling); self.notify_wedged(); accepted @@ -304,8 +306,9 @@ impl Shared { match state.as_deref_mut() { Some(firmware) => { let res = self.submit_locked(firmware, job, &mut done); - let allow_stage = - firmware.recovery.failed().is_none() && !firmware.engine.frozen; + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); res } @@ -313,14 +316,49 @@ impl Shared { } }; job::complete_all(done); - if scrubs.run() { - self.poll_now(); - } + self.enqueue_scrubs(scrubs); drop(signalling); self.notify_wedged(); Some(accepted) } + /// Hands staged displaced pass scrubs to the dedicated unbound scrub workqueue so SUBMIT + /// and completion polling never stall on write-combining zeroing. + pub(crate) fn enqueue_scrubs(self: &Arc, batch: super::slots::ScrubBatch) { + if batch.is_empty() { + return; + } + let mut queue = self.scrub_queue.lock(); + if self.sleeping.load(Ordering::Acquire) { + drop(queue); + drop(batch); + return; + } + if queue.push_batch(batch) { + // Queue under `scrub_queue` so `sleep.rs::join_workers()` cannot overlap + // `scrub_wq.drain()` with a concurrent enqueue once `sleeping` is set. + let _ = self + .scrub_wq + .enqueue::, SCRUB_WORK>(self.clone()); + } + } + + /// Drains queued displaced pass scrubs on the dedicated unbound scrub workqueue. + pub(crate) fn run_scrubs(self: &Arc) { + loop { + let Some(mut item) = self.scrub_queue.lock().pop() else { + break; + }; + if self.sleeping.load(Ordering::Acquire) { + drop(item); + break; + } + if item.run_one() && !self.sleeping.load(Ordering::Acquire) { + self.poll_now(); + } + } + } + /// Deliver userspace notification outside the device mutex and fence completion path. fn notify_wedged(&self) { if self.wedged.load(Ordering::Acquire) && !self.wedged_notified.swap(true, Ordering::AcqRel) @@ -348,9 +386,15 @@ impl Shared { } /// Disarms the completion hrtimer when idle or entering system sleep. + /// + /// Always takes `resnap_handle` rather than checking a lock-free shadow flag so + /// `sleep::join_workers()` strictly orders with any concurrent `rearm()`: `sleep_down()` + /// stores `sleeping = true` before calling `cancel_resnap()`, and `rearm()` re-checks + /// `sleeping` under `resnap_handle.lock()` before installing a new handle. pub(crate) fn cancel_resnap(&self) { + let mut handle = self.resnap_handle.lock(); self.resnap_deadline_ns.store(0, Ordering::Release); - drop(self.resnap_handle.lock().take()); + drop(handle.take()); } /// Queues the backup poll on `system_highpri_wq` after `delay` jiffies, or moves an already @@ -375,6 +419,9 @@ impl Shared { /// Re-checks a published command soon: hrtimer, with a throttled 1-jiffy backup; sooner while /// a ready prefix waits for record consumption or a post-event receipt tail is settling. pub(crate) fn rearm(self: &Arc, soon: bool) { + if self.sleeping.load(Ordering::Acquire) { + return; + } let mut us = params::resnap_us(); if soon && module_parameters::g16_repoll_us.value() != 0 { us = params::repoll_us(); @@ -384,9 +431,15 @@ impl Shared { let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); if armed_ns == 0 || armed_ns <= now || target_ns.saturating_add(5_000) < armed_ns { let mut handle = self.resnap_handle.lock(); - drop(handle.take()); - self.resnap_deadline_ns.store(target_ns, Ordering::Release); - *handle = Some(self.clone().start(Delta::from_micros(i64::from(us)))); + if self.sleeping.load(Ordering::Acquire) { + return; + } + let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); + if armed_ns == 0 || armed_ns <= now || target_ns.saturating_add(5_000) < armed_ns { + drop(handle.take()); + self.resnap_deadline_ns.store(target_ns, Ordering::Release); + *handle = Some(self.clone().start(Delta::from_micros(i64::from(us)))); + } } let backup_ns = self.backup_deadline_ns.load(Ordering::Acquire); if now >= backup_ns { @@ -464,6 +517,7 @@ impl Firmware { return Ok(false); } } + let was_frozen = self.engine.frozen; let stage_before = self.events.stage_events; let term_before = self.oldest_terminal_events(); let mut lap = Lap::start(); @@ -471,13 +525,35 @@ impl Firmware { let retired_any = self.retire_once(done)?; lap.lap(&mut self.engine.prof.retire_ns); self.answer_growth()?; - if self.recovery.receipt_fault || self.recovery_pending()? { + let recovery_pending = self.recovery.receipt_fault || self.recovery_pending()?; + if recovery_pending { self.check_hangs(done)?; } - let published = if self.engine.pending.is_empty() { - Ok(()) - } else { + let unfrozen = was_frozen && !self.engine.frozen; + let scrub_woke = self.slots.take_scrub_woke(); + let publish_woke = self + .engine + .shared + .as_ref() + .is_some_and(|shared| shared.publish_wake.swap(false, Ordering::AcqRel)); + // 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), + // while `publish_woke` covers external state changes (VM close, unstarted queue + // cancellation) so pending jobs never wait on the 1 ms housekeeping tick. + let should_publish = !self.engine.pending.is_empty() + && (retired_any + || !had_flights + || self.engine.flights.is_empty() + || self.engine.chan_wait + || unfrozen + || scrub_woke + || publish_woke + || housekeeping_due); + let published = if should_publish { self.publish_checked(done) + } else { + Ok(()) }; if self.engine.flights.is_empty() { self.power.report_work(false); @@ -501,7 +577,7 @@ impl Firmware { && self.oldest_terminal_events() == term_before && !self.oldest_stamp_reached() && !self.recovery.receipt_fault - && !self.recovery_pending().unwrap_or(true); + && !recovery_pending; // After an EP 0x20 event, retry up to `EVENT_RETIRE_POLLS` times (outside the device // lock) only while no flight has retired yet and flights remain in flight. Once any // flight retires, stop spinning so deeper queues do not burn tail waits per interrupt. @@ -526,12 +602,13 @@ impl Firmware { } } // If a terminal EP 0x20 event arrived with flights outstanding and nothing retired within - // the trailing polls, repoll at `repoll_us` instead of sleeping `resnap_us`. - self.engine.short_repoll = evented - && had_flights - && !retired_any + // the trailing polls, or a ready same-VM pending job is blocked on slot/flight/work-ring + // headroom, repoll at `repoll_us` instead of sleeping `resnap_us`. + self.engine.short_repoll = !self.engine.flights.is_empty() + && !self.engine.frozen && !non_terminal_only - && !self.engine.flights.is_empty(); + && ((evented && had_flights && !retired_any) + || (!self.engine.pending.is_empty() && self.engine.slot_wait)); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() @@ -656,6 +733,9 @@ impl Firmware { if self.recovery.receipt_fault || self.recovery_pending()? { self.check_hangs(done)?; } + if self.engine.flights.is_empty() { + return Ok(false); + } let mut retired_any = false; let (mut check_compute, mut check_render) = (true, true); let mut ret = self.retired_flight_classes(&mut check_compute, &mut check_render); @@ -686,7 +766,7 @@ impl Firmware { unit: &super::slots::ComputeSlot, ) -> Result<(u64, u64)> { let (start, end) = (unit.its.r64(0)?, unit.its.r64(8)?); - if start != 0 && end > start { + if start != 0 && end >= start { return Ok((start, end)); } let Some((start_off, end_off)) = work_ticks else { @@ -887,6 +967,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; full &= stamp_reached(stamp, f.target, e.target) && (stamp != f.target @@ -897,6 +978,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; } @@ -916,7 +998,7 @@ impl Firmware { break; } let (start, end) = self.compute_ticks(unit)?; - if start == 0 || end <= start { + if start == 0 || end < start { full = false; break; } @@ -946,6 +1028,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); let fs_stamp = g.notifier.r32(notifier_page::FS_STAMP)?; let ta_stamp = g.notifier.r32(notifier_page::TA_STAMP)?; full &= stamp_reached(fs_stamp, f.fs_target, e.fs_target) @@ -980,6 +1063,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); full &= g.notifier.r32(notifier_page::FS_STAMP)? == f.fs_target && g.notifier.r32(notifier_page::TA_STAMP)? == f.ta_target && g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot @@ -1001,9 +1085,9 @@ impl Firmware { ticks = [ta_start, ta_end, fs_start, fs_end]; } full &= ta_start != 0 - && ta_end > ta_start + && ta_end >= ta_start && fs_start != 0 - && fs_end > fs_start; + && fs_end >= fs_start; if !full { break; } @@ -1014,13 +1098,27 @@ impl Firmware { self.engine.retired_ticks = ticks; return Ok(Retirement::Full); } - if f.recovery_suspect && now_ns().saturating_sub(f.recovery_started_ns) >= 20_000_000 { - // Queues, pipes and every participating stage passed the retained command. - // The firmware recovered it without normal completion: fail and quarantine. - if let Some(f) = self.engine.flights.get_mut(index) { - f.doomed = true; + if f.recovery_suspect { + // Queues, pipes and every participating stage passed the retained command, yet normal + // receipts have not settled. Measure the abort grace from this first gate-passed poll + // and require a second unsettled poll so an innocent suspect flight finishing > 20 ms + // after recovery cannot race a transient WC/notifier write into a false abort. + let now = now_ns(); + let aborted = if let Some(f) = self.engine.flights.get_mut(index) { + let first = *f.gate_passed_ns.get_or_insert(now); + f.unsettled_polls = f.unsettled_polls.saturating_add(1); + if f.unsettled_polls >= 2 && now.saturating_sub(first) >= ABORT_GRACE_NS { + f.doomed = true; + true + } else { + false + } + } else { + false + }; + if aborted { + return Ok(Retirement::Aborted); } - return Ok(Retirement::Aborted); } Ok(Retirement::Pending) } @@ -1460,7 +1558,7 @@ impl Firmware { f.job .queue .usage - .add(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); + .add_union(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); *sum = sum.saturating_add(end - start); lo = lo.min(start); hi = hi.max(end); diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 5150716b563d1..bb6866e5fdf01 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -48,7 +48,7 @@ pub(crate) struct QueueState { /// Host priority: `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it (MEDIUM 2, /// LOW 3; `file.rs` refuses HIGH and REALTIME). Smaller is served first. pub(crate) priority: u32, - /// Completed stage time of the DRM file that created this queue. + /// Completed stage time of the DRM file that created this queue (deduplicated per file). pub(crate) usage: Arc, /// USC executable window base. pub(crate) usc_base: u64, @@ -203,14 +203,14 @@ impl Queue { if sync_count > command::MAX_SYNCS { return Err(EINVAL); } - command::check_stream(bytes, params::early_tiling())?; + let parsed = command::parse_stream(bytes, params::early_tiling())?; if self.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } if self.vm.status.get() != 0 { return Err(EIO); } - let prepared = command::prepare(bytes, self.accepted, objects)?; + let prepared = parsed.prepare(self.accepted, objects)?; // The job reference first, so that the mappings checked below stay retained. let guard = self.vm.vm.retain_first_job()?; let submission = prepared.validate(&command::Context { diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 0f12d12b373eb..1bd581ee22a16 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -80,13 +80,34 @@ impl ComputeArena { } /// Render pass slots every VM gets with its first render command; extension slots -/// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are added lazily once the VM actually -/// pipelines renders or submits a multi-pass/burst frame. +/// (`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; -const EXT_RENDER_SLOTS: usize = super::hw::sizes::RENDER_SLOTS - 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 +/// multi-pass bursts (160 client mappings <= `MAX_CLIENT`). +pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 4] = [ + (BASE_RENDER_SLOTS, 8), + (8, 18), + (18, 32), + (32, super::hw::sizes::RENDER_SLOTS), +]; +const _: () = assert!(EXT_RENDER_TIERS[0].0 == BASE_RENDER_SLOTS); +const _: () = assert!(EXT_RENDER_TIERS[0].1 == EXT_RENDER_TIERS[1].0); +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; -/// Single-submission render command count that expands extension slots immediately: +/// Single-submission render command count that expands Tier 0 extension slots immediately: /// `BASE_RENDER_SLOTS` holds only one active render once displacement occupies a slot. const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; @@ -123,33 +144,57 @@ fn should_expand_compute_ext( base_quarantined || *burst >= BURST_SUBMITS || computes >= BURST_COMMANDS } -/// Updates the consecutive-render burst counter and reports whether this submission -/// qualifies to allocate extension pass slots (`RenderExtArena`). +/// Updates the consecutive-render burst counter and returns the target render pass slot count +/// (`BASE_RENDER_SLOTS..=hw::sizes::RENDER_SLOTS`) this VM should have backed before admission. /// /// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives -/// (`active_renders == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay -/// on the two base pass slots. Extension slots allocate when a base pass slot is quarantined, -/// a VM actually overlaps an in-flight render (`active_renders != 0`, including multi-ms -/// 1080p/4K pipelined frames), submits a multi-pass command stream -/// (`render_count >= BASE_RENDER_SLOTS`), or sustains a sub-2 ms back-to-back burst. -fn should_expand_render_ext( +/// (`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, +/// 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. +fn target_render_slots( last_render_ns: &mut u64, render_burst: &mut u32, now: u64, render_count: usize, - active_renders: u32, + active_passes: u32, base_quarantined: bool, -) -> bool { + current_slots: usize, +) -> usize { *render_burst = if *last_render_ns != 0 && now.wrapping_sub(*last_render_ns) < BURST_GAP_NS { render_burst.saturating_add(1) } else { 0 }; *last_render_ns = now; - base_quarantined - || active_renders != 0 - || *render_burst >= BURST_SUBMITS - || render_count >= RENDER_BURST_COMMANDS + let live_need = (active_passes as usize) + .saturating_add(render_count) + .saturating_add(1); + let want = if current_slots <= BASE_RENDER_SLOTS { + if base_quarantined + || active_passes != 0 + || *render_burst >= BURST_SUBMITS + || render_count >= RENDER_BURST_COMMANDS + { + live_need.max(BASE_RENDER_SLOTS + 1) + } else { + BASE_RENDER_SLOTS + } + } else { + live_need + }; + let mut target = current_slots.max(BASE_RENDER_SLOTS); + for &(start, end) in &EXT_RENDER_TIERS { + if target >= want { + break; + } + if target < end && want > start { + target = end; + } + } + target.min(super::hw::sizes::RENDER_SLOTS) } pub(crate) struct RenderArena(crate::cleanup::Deferred); @@ -206,9 +251,8 @@ impl RenderArena { } } -/// Extension render pass slots (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`), allocated lazily -/// for VMs that submit renders back to back so idle or single-pass VMs keep only the two base -/// pass slots. +/// One demand-grown tier of extension render pass slots (`slots`), allocated lazily so idle, +/// single-pass, and shallow multi-pass VMs back only the tiers their concurrency requires. pub(crate) struct RenderExtArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderExtArena { type Target = RenderExtInner; @@ -217,9 +261,10 @@ impl core::ops::Deref for RenderExtArena { } } pub(crate) struct RenderExtInner { + pub(crate) start: usize, pub(crate) passes: KVec, - pub(crate) tpc_dirty: [AtomicU64; EXT_RENDER_SLOTS], - pub(crate) tilemap_dirty: [AtomicU64; EXT_RENDER_SLOTS], + pub(crate) tpc_dirty: KVec, + pub(crate) tilemap_dirty: KVec, _objects: Objects, _bind: mmu::VmBind, _live: Arc, @@ -230,18 +275,25 @@ impl RenderExtArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + slots: core::ops::Range, ) -> Result> { + let count = slots.len(); let mut objects = factory.objects(vm); - let mut passes = KVec::with_capacity(EXT_RENDER_SLOTS, GFP_KERNEL)?; - for k in BASE_RENDER_SLOTS..super::hw::sizes::RENDER_SLOTS { + let mut passes = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tpc_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tilemap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + for k in slots.clone() { passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; + tpc_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; + tilemap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; } objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderExtInner { + start: slots.start, passes, - tpc_dirty: [const { AtomicU64::new(0) }; EXT_RENDER_SLOTS], - tilemap_dirty: [const { AtomicU64::new(0) }; EXT_RENDER_SLOTS], + tpc_dirty, + tilemap_dirty, _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -312,7 +364,7 @@ impl PassOwnerArena { match self { Self::Base(arena) => Some((arena.passes.get(k)?, arena.tilemap_dirty.get(k)?)), Self::Ext(arena) => { - let idx = k.checked_sub(BASE_RENDER_SLOTS)?; + let idx = k.checked_sub(arena.start)?; Some((arena.passes.get(idx)?, arena.tilemap_dirty.get(idx)?)) } } @@ -325,8 +377,8 @@ struct Ready { /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. compute_ext: Option>, render: Option>, - /// Pass slots from [`BASE_RENDER_SLOTS`] on, for a VM that keeps renders queued. - render_ext: Option>, + /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). + render_ext: [Option>; EXT_RENDER_TIERS.len()], /// Recovery PB/UMA allocator slots (`BASE_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. pb_ext: [Option>; EXT_PB_SLOTS], /// Last compute submission and the back-to-back run it continues. @@ -360,8 +412,8 @@ pub(crate) struct Cache { standby_available: CondVar, /// The VM's client closed: no arena or surplus spare is kept here any more. closed: AtomicBool, - /// Prepared render jobs on this VM that have not yet retired and dropped. - active_renders: AtomicU32, + /// Render passes across prepared jobs on this VM that have not yet retired and dropped. + active_render_passes: AtomicU32, pub(crate) factory: Factory, bind: mmu::VmBind, live: Arc, @@ -387,7 +439,7 @@ impl Cache { ), standby_available <- new_condvar!(), closed: AtomicBool::new(false), - active_renders: AtomicU32::new(0), + active_render_passes: AtomicU32::new(0), factory, bind, live, budget }), GFP_KERNEL, ) @@ -503,7 +555,7 @@ impl Cache { ready.compute.take(), ready.compute_ext.take(), ready.render.take(), - ready.render_ext.take(), + core::mem::take(&mut ready.render_ext), core::mem::take(&mut ready.pb_ext), ) }; @@ -601,25 +653,54 @@ impl Cache { } } } - if ready.render_ext.is_none() && EXT_RENDER_SLOTS != 0 { + let current_slots = BASE_RENDER_SLOTS + + ready + .render_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.passes.len()) + .sum::(); + if current_slots < super::hw::sizes::RENDER_SLOTS { // SAFETY: ktime_get has no preconditions. let now = unsafe { kernel::bindings::ktime_get() } as u64; let state = &mut *ready; - let active = self.active_renders.load(Ordering::Acquire); - if should_expand_render_ext( + let active_passes = self.active_render_passes.load(Ordering::Acquire); + let target = target_render_slots( &mut state.last_render_ns, &mut state.render_burst, now, render_count as usize, - active, + active_passes, hints.expand_render_ext, - ) { - // Best effort: without extension slots the VM keeps two base pass slots. - state.render_ext = - RenderExtArena::new(&self.factory, &self.bind, &vm.vm, &self.live).ok(); + current_slots, + ); + for (idx, &(start, end)) in EXT_RENDER_TIERS.iter().enumerate() { + if start >= target { + break; + } + if state.render_ext[idx].is_none() { + // Best effort: stop on allocation failure, keeping lower tiers. + state.render_ext[idx] = RenderExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + start..end, + ) + .ok(); + if state.render_ext[idx].is_none() { + break; + } + } } } } + let render_ext = if render { + core::array::from_fn(|idx| ready.render_ext[idx].clone()) + } else { + [const { None }; EXT_RENDER_TIERS.len()] + }; let pb_ext = if render { core::array::from_fn(|idx| ready.pb_ext[idx].clone()) } else { @@ -629,7 +710,7 @@ impl Cache { if compute { ready.compute.clone() } else { None }, if compute { ready.compute_ext.clone() } else { None }, if render { ready.render.clone() } else { None }, - if render { ready.render_ext.clone() } else { None }, + render_ext, pb_ext, ) }; @@ -718,7 +799,8 @@ impl Cache { return Err(EIO); } let cache = if render_count != 0 { - self.active_renders.fetch_add(1, Ordering::AcqRel); + self.active_render_passes + .fetch_add(render_count, Ordering::AcqRel); Some(self.clone()) } else { None @@ -729,6 +811,7 @@ impl Cache { render: render_arena, render_ext, pb_ext, + total_renders: render_count, unpublished_renders: AtomicU32::new(render_count), cache, }) @@ -741,10 +824,12 @@ pub(crate) struct Prepared { /// The VM's extension compute units when the job was prepared. pub(crate) compute_ext: Option>, pub(crate) render: Option>, - /// The VM's extension render pass slots when the job was prepared. - pub(crate) render_ext: Option>, + /// 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 lazily allocated recovery PB/UMA allocator slots when the job was prepared. pub(crate) pb_ext: [Option>; EXT_PB_SLOTS], + /// Total render commands accounted against `Cache::active_render_passes`. + total_renders: u32, /// Render commands of this job whose standby reservation has not yet been committed. unpublished_renders: AtomicU32, /// The VM cache holding the standby PB epoch pool. @@ -756,8 +841,10 @@ impl Drop for Prepared { let Some(cache) = self.cache.take() else { return; }; - let previous = cache.active_renders.fetch_sub(1, Ordering::AcqRel); - debug_assert!(previous != 0); + let previous = cache + .active_render_passes + .fetch_sub(self.total_renders, Ordering::AcqRel); + debug_assert!(previous >= self.total_renders); let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); cache.release_reserved(remaining); } @@ -836,20 +923,35 @@ impl Prepared { .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone())) } } + 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) { + if idx < tier.passes.len() { + return Some((tier, idx)); + } + } + } + None + } /// Render pass slots this job can use. pub(crate) fn render_passes(&self) -> Result { - Ok(self.render()?.passes.len() - + self.render_ext.as_deref().map_or(0, |e| e.passes.len())) + let ext: usize = self + .render_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.passes.len()) + .sum(); + Ok(self.render()?.passes.len() + ext) } - /// Render pass slot `k`: the VM's base slots, then its extension slots. + /// Render pass slot `k`: the VM's base slots, then its demand-grown extension tiers. pub(crate) fn render_pass(&self, k: usize) -> Result<&PassSlot> { let base = &self.render()?.passes; match base.get(k) { Some(pass) => Ok(pass), None => self - .render_ext - .as_deref() - .and_then(|e| e.passes.get(k - base.len())) + .render_ext_for(k) + .and_then(|(tier, idx)| tier.passes.get(idx)) .ok_or(EINVAL), } } @@ -859,12 +961,8 @@ impl Prepared { if k < base.passes.len() { Ok((&base.tpc_dirty[k], &base.tilemap_dirty[k])) } else { - let ext = self.render_ext.as_deref().ok_or(EINVAL)?; - let idx = k - base.passes.len(); - if idx >= ext.passes.len() { - return Err(EINVAL); - } - Ok((&ext.tpc_dirty[idx], &ext.tilemap_dirty[idx])) + let (tier, idx) = self.render_ext_for(k).ok_or(EINVAL)?; + Ok((&tier.tpc_dirty[idx], &tier.tilemap_dirty[idx])) } } /// Updates dirty high-water marks for pass slot `k` (base or extension). @@ -884,7 +982,8 @@ impl Prepared { if k < base.passes.len() { Some(PassOwnerArena::Base(base.clone())) } else { - self.render_ext.as_ref().map(|e| PassOwnerArena::Ext(e.clone())) + self.render_ext_for(k) + .map(|(tier, _)| PassOwnerArena::Ext(tier.clone())) } } /// Compute unit `k`: the VM's base units, then its extension units. @@ -910,15 +1009,21 @@ impl Prepared { cache.return_standby(epoch); } } - /// Commits one render command's standby reservation once it reaches firmware visibility. - pub(crate) fn commit_render(&self) { + /// Commits `count` render commands' standby reservations once they reach firmware visibility. + pub(crate) fn commit_render(&self, count: u32) { + if count == 0 { + return; + } if let Some(cache) = &self.cache { - if self - .unpublished_renders - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) - .is_ok() - { - cache.release_reserved(1); + if let Ok(prev) = self.unpublished_renders.fetch_update( + Ordering::AcqRel, + Ordering::Acquire, + |n| Some(n.saturating_sub(count)), + ) { + let released = prev.min(count); + if released != 0 { + cache.release_reserved(released); + } } } } diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index ae23cc8e0dc56..2f555c3af3fbe 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -114,6 +114,15 @@ impl Shared { drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); } self.events.drain(); + // `sleeping` is already set, so taking the 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); + self.scrub_wq.drain(); } /// Waits for what's been published to retire. The poll work keeps running meanwhile. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 5e8e3c93d18b1..68d48b717d70b 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -8,7 +8,7 @@ //! Private backing and old VM leases survive until a distinct replacement fully retires. //! Aborted storage remains mapped and quarantined. Pool cursors are never scrubbed. -use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; use super::encode::{Geometry, PassRefs}; @@ -143,10 +143,8 @@ pub(crate) struct PassSlot { /// Part of the slot's firmware layout; the host does not use it. _uts: Arc, pub(crate) own_barrier: Arc, - #[allow(dead_code)] pub(crate) prev_barrier: Arc, pub(crate) ta_fs_barrier: Arc, - #[allow(dead_code)] pub(crate) fs_dep: Arc, pub(crate) compute_barrier: Arc, pub(crate) fs_compute_barrier: Arc, @@ -156,7 +154,7 @@ 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 { let sh = Class::Shared; - let (ps, ws) = (i * client::PASS_STRIDE, i * client::WORK_STRIDE); + let off = client::pass_off(i); let tpc = if i >= sizes::BASE_RENDER_SLOTS as u64 { client::TPC_SLOT_SIZE } else { @@ -169,32 +167,25 @@ impl PassSlot { }; let _ = pre_records; - let aux = alloc( - o, - 0x20000, - sh, - Client::nc(client::AUX + i * client::AUX_STRIDE), - 0, - false, - )?; + let aux = alloc(o, 0x20000, sh, Client::nc(client::AUX + off), 0, false)?; let mut pre = KVec::with_capacity(3, GFP_KERNEL)?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE0_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE0_PAGE + off), 0, false)?, GFP_KERNEL, )?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE1_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE1_PAGE + off), 0, false)?, GFP_KERNEL, )?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE2_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE2_PAGE + off), 0, false)?, GFP_KERNEL, )?; let tpc = alloc( o, tpc as usize, sh, - Client::nc(client::TPC + i * client::TPC_SLOT_STRIDE), + Client::nc(client::TPC + off), 0, false, )?; @@ -202,7 +193,7 @@ impl PassSlot { o, tilemap as usize, sh, - Client::nc(client::TILEMAP + i * client::TPC_SLOT_STRIDE), + Client::nc(client::pass_tilemap(i)), 0, false, )?; @@ -210,7 +201,7 @@ impl PassSlot { o, 0x4000, sh, - Client::nc(client::HEAP_META_PAGE + ps), + Client::nc(client::HEAP_META_PAGE + off), 0, false, )?; @@ -218,7 +209,7 @@ impl PassSlot { o, 0x10000, sh, - Client::nc(client::SCENE_USER + ps), + Client::nc(client::SCENE_USER + off), 0, false, )?; @@ -226,7 +217,7 @@ impl PassSlot { o, super::fw::buffer::SCENE_LIST_SIZE, sh, - Client::nc(client::SCENE_LIST + ps), + Client::nc(client::SCENE_LIST + off), 0, false, )?; @@ -234,20 +225,20 @@ impl PassSlot { o, 0x10000, sh, - Client::nc(client::FS_SCRATCH + ps), + Client::nc(client::FS_SCRATCH + off), 0, false, )?; let fs_work = alloc_work( o, fs::WORK_SIZE, - client::FS_WORK_PAGE + ws, + client::FS_WORK_PAGE + off, client::FS_WORK_OFF as usize, )?; let ta_work = alloc_work( o, ta::WORK_SIZE, - client::TA_WORK_PAGE + ws, + client::TA_WORK_PAGE + off, client::TA_WORK_OFF as usize, )?; Ok(Self { @@ -375,7 +366,7 @@ pub(crate) struct Claims { pub(crate) slot_count: u32, pub(crate) pass: [u32; sizes::RENDER_SLOTS], pub(crate) pass_count: u32, - pub(crate) pass_mask: u32, + pub(crate) pass_mask: u64, #[allow(dead_code)] pub(crate) ct: [u32; sizes::RENDER_SLOTS], pub(crate) ct_count: u32, @@ -446,17 +437,23 @@ pub(crate) struct ComputeOwners { } /// Bitmask of valid render pass slot indices (`0..sizes::RENDER_SLOTS`). -const PASS_MASK: u32 = (1u32 << sizes::RENDER_SLOTS) - 1; +const PASS_MASK: u64 = u64::MAX >> (64 - sizes::RENDER_SLOTS); /// Shared atomic coordination between `Shared::state` slot selection/claims and off-lock /// pre-scrubbing of displaced render pass slots. struct ScrubState { /// Pass slots currently being scrubbed outside `Shared::state`; never picked or claimed. - scrubbing: AtomicU32, + scrubbing: AtomicU64, /// Displaced pass slots whose clean same-VM spans were zeroed off-lock. - clean_mask: AtomicU32, + clean_mask: AtomicU64, + /// Incremented by [`Self::clear_all_clean`] on recovery so an in-flight async scrub that + /// started before recovery can never publish a stale `clean_mask` bit afterwards. + generation: AtomicU64, /// Set if slot selection found eligible slots blocked only by an in-flight off-lock scrub. waiter: AtomicBool, + /// Set when an off-lock scrub finished while `waiter` was pending so the next `poll_step()` + /// retries `publish_checked()` even if no flight retired. + woke: AtomicBool, /// Off-lock scrub counters folded into [`SlotStats`] on subsequent locked access. pass_scrubs: AtomicU64, tilemap_clear_bytes: AtomicU64, @@ -465,33 +462,36 @@ struct ScrubState { impl ScrubState { const fn new() -> Self { Self { - scrubbing: AtomicU32::new(0), - clean_mask: AtomicU32::new(0), + scrubbing: AtomicU64::new(0), + clean_mask: AtomicU64::new(0), + generation: AtomicU64::new(0), waiter: AtomicBool::new(false), + woke: AtomicBool::new(false), pass_scrubs: AtomicU64::new(0), tilemap_clear_bytes: AtomicU64::new(0), } } fn is_scrubbing(&self, k: usize) -> bool { - self.scrubbing.load(Ordering::Acquire) & (1u32 << k) != 0 + self.scrubbing.load(Ordering::Acquire) & (1u64 << k) != 0 } fn is_clean(&self, k: usize) -> bool { - self.clean_mask.load(Ordering::Acquire) & (1u32 << k) != 0 + self.clean_mask.load(Ordering::Acquire) & (1u64 << k) != 0 } fn take_clean(&self, k: usize) -> bool { - let bit = 1u32 << k; + let bit = 1u64 << k; self.clean_mask.fetch_and(!bit, Ordering::AcqRel) & bit != 0 } fn clear_clean(&self, k: usize) { - self.clean_mask.fetch_and(!(1u32 << k), Ordering::Release); + self.clean_mask.fetch_and(!(1u64 << k), Ordering::Release); } fn clear_all_clean(&self) { - self.clean_mask.store(0, Ordering::Release); + self.generation.fetch_add(1, Ordering::SeqCst); + self.clean_mask.store(0, Ordering::SeqCst); } } @@ -500,16 +500,21 @@ pub(crate) struct PendingScrub { slot: usize, arena: super::resources::PassOwnerArena, state: Arc, + generation: u64, done: bool, } impl PendingScrub { - fn run_one(&mut self) -> bool { - let bit = 1u32 << self.slot; - let ok = if let Some((pass, tilemap_dirty)) = self.arena.pass_and_tilemap_dirty(self.slot) { + pub(crate) fn run_one(&mut self) -> bool { + let bit = 1u64 << self.slot; + let ok = if self.state.generation.load(Ordering::Acquire) != self.generation { + false + } else if let Some((pass, tilemap_dirty)) = self.arena.pass_and_tilemap_dirty(self.slot) { let dirty = tilemap_dirty.load(Ordering::Acquire); match pass.scrub_clean(1, dirty) { Ok(()) => { + // Order scrubbed WC bytes before clearing dirty / publishing clean_mask. + super::engine::wmb(); tilemap_dirty.store(0, Ordering::Release); self.state.pass_scrubs.fetch_add(1, Ordering::Relaxed); self.state @@ -522,19 +527,26 @@ impl PendingScrub { } else { false }; - if ok { - self.state.clean_mask.fetch_or(bit, Ordering::Release); + if ok && self.state.generation.load(Ordering::SeqCst) == self.generation { + self.state.clean_mask.fetch_or(bit, Ordering::SeqCst); + if self.state.generation.load(Ordering::SeqCst) != self.generation { + self.state.clean_mask.fetch_and(!bit, Ordering::SeqCst); + } } self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); self.done = true; - self.state.waiter.swap(false, Ordering::SeqCst) + let woke = self.state.waiter.swap(false, Ordering::SeqCst); + if woke { + self.state.woke.store(true, Ordering::Release); + } + woke } } impl Drop for PendingScrub { fn drop(&mut self) { if !self.done { - let bit = 1u32 << self.slot; + let bit = 1u64 << self.slot; self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); } } @@ -554,6 +566,10 @@ impl ScrubBatch { } } + pub(crate) fn is_empty(&self) -> bool { + self.len == 0 + } + fn push(&mut self, item: PendingScrub) -> bool { if self.len >= sizes::RENDER_SLOTS { return false; @@ -562,16 +578,45 @@ impl ScrubBatch { self.len += 1; true } +} + +/// Zero-allocation slot-indexed queue handed to the async pass-scrub workqueue. +/// +/// Each pass slot `0..sizes::RENDER_SLOTS` keeps its `scrubbing` bit set while a +/// [`PendingScrub`] is queued or running, so at most one entry per slot exists at once. +pub(crate) struct ScrubQueue { + slots: [Option; sizes::RENDER_SLOTS], +} + +impl ScrubQueue { + pub(crate) const fn new() -> Self { + Self { + slots: [const { None }; sizes::RENDER_SLOTS], + } + } - /// Runs every staged off-lock pass scrub. Returns `true` if a waiting submitter needs wakeup. - pub(crate) fn run(mut self) -> bool { - let mut wake = false; - for slot in &mut self.items[..self.len] { - if let Some(mut item) = slot.take() { - wake |= item.run_one(); + /// 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; + for slot in &mut batch.items[..batch.len] { + if let Some(item) = slot.take() { + let idx = item.slot; + self.slots[idx] = Some(item); + pushed = true; } } - wake + batch.len = 0; + pushed + } + + /// Pops the next queued pass scrub, if any. + pub(crate) fn pop(&mut self) -> Option { + for slot in &mut self.slots { + if slot.is_some() { + return slot.take(); + } + } + None } } @@ -599,7 +644,7 @@ pub(crate) struct RenderOwners { pub(crate) struct Slots { pub(crate) cursor: u32, - pub(crate) pass_busy: u32, + pub(crate) pass_busy: u64, pub(crate) pass_cursor: u32, scrub_gen: u64, pub(crate) stats: SlotStats, @@ -732,6 +777,10 @@ impl Slots { pub(crate) fn scrubbing_active(&self) -> bool { self.scrub.scrubbing.load(Ordering::Acquire) != 0 } + /// Consumes the wakeup flag set when an off-lock scrub unblocks a waiting render submitter. + pub(crate) fn take_scrub_woke(&self) -> bool { + self.scrub.woke.swap(false, Ordering::AcqRel) + } /// Total pass scrubs including completed off-lock pre-scrubs. pub(crate) fn pass_scrubs_total(&self) -> u64 { self.stats @@ -761,7 +810,7 @@ impl Slots { self.render.scrub_pending = false; self.fold_scrub_stats(); for k in 0..sizes::RENDER_SLOTS { - let bit = 1u32 << k; + let bit = 1u64 << k; if self.pass_busy & bit != 0 || !self.render.lifetime.available(k) || self.render.scrub_full[k] @@ -774,10 +823,12 @@ impl Slots { continue; }; self.scrub.scrubbing.fetch_or(bit, Ordering::SeqCst); + let generation = self.scrub.generation.load(Ordering::Acquire); let item = PendingScrub { slot: k, arena, state: self.scrub.clone(), + generation, done: false, }; if !self.render.staged.push(item) { @@ -900,7 +951,7 @@ impl Slots { &self, arena: &super::resources::RenderArena, geo: &Geometry, - picked: u32, + picked: u64, ) -> Option { let n = arena.passes.len().min(sizes::RENDER_SLOTS); let mut fallback = None; @@ -908,7 +959,7 @@ impl Slots { for i in 0..n { let k = (self.pass_cursor as usize + i) % n; let p = &arena.passes[k]; - if (self.pass_busy | picked) & (1 << k) == 0 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 @@ -931,7 +982,7 @@ impl Slots { for i in 0..n { let k = (self.pass_cursor as usize + i) % n; let p = &arena.passes[k]; - if (self.pass_busy | picked) & (1 << k) == 0 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && !self.scrub.is_scrubbing(k) && geo.tpc_bytes <= p.tpc.size as u64 @@ -948,7 +999,7 @@ impl Slots { &self, resources: &super::resources::Prepared, geo: &Geometry, - picked: u32, + picked: u64, ) -> Option { let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); let mut fallback = None; @@ -958,7 +1009,7 @@ impl Slots { let Ok(p) = resources.render_pass(k) else { continue; }; - if (self.pass_busy | picked) & (1 << k) == 0 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 @@ -983,7 +1034,7 @@ impl Slots { let Ok(p) = resources.render_pass(k) else { continue; }; - if (self.pass_busy | picked) & (1 << k) == 0 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && !self.scrub.is_scrubbing(k) && geo.tpc_bytes <= p.tpc.size as u64 @@ -1154,12 +1205,12 @@ impl Slots { return Err(EINVAL); } if f.pass_count != 0 { - let mut mask = 0u32; + let mut mask = 0u64; for &k in &f.pass[..f.pass_count as usize] { if k as usize >= sizes::RENDER_SLOTS { return Err(EINVAL); } - let bit = 1u32 << k; + let bit = 1u64 << k; if mask & bit != 0 { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 3cca4f5a37fe6..9e087092c7bf0 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -512,11 +512,10 @@ fn lock_vm( } #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] -pub(crate) struct VmReadGuard(VmExecGuard); +pub(crate) struct VmReadGuard<'a>(gpuvm::GpuVmInnerGuard<'a, VmInner>); #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] -impl VmReadGuard { - #[cfg(CONFIG_DRM_ASAHI_G15)] +impl VmReadGuard<'_> { pub(crate) fn covers_range(&mut self, address: u64, size: u64, read: bool, write: bool) -> bool { Vm::covers_range_locked(&mut self.0, address, size, read, write) } @@ -2632,15 +2631,18 @@ impl Vm { /// Every page must be mapped GPU-readable and be RAM; otherwise EFAULT. The lines are cleaned /// and invalidated to the point of coherency first (never only invalidated: CPU-written lines /// may be dirty), so the copy sees what the GPU or a write-combined CPU view stored. The - /// mappings cannot change during the copy (GPUVM exec lock). + /// mappings cannot change during the copy (VM reservation lock). #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] pub(crate) fn read_user(&self, va: u64, buf: &mut [u8]) -> Result { self.read_lock()?.read_user(va, buf) } #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] - pub(crate) fn read_lock(&self) -> Result { - Ok(VmReadGuard(lock_vm(&self.gpuvm, None, false)?)) + pub(crate) fn read_lock(&self) -> Result> { + // Every mapping change holds the VM reservation, so read-only page-table walks and + // user-memory copies need only that reservation. The full exec lock would allocate a + // `drm_gpuvm_exec` context and lock every external BO, making each submit O(external BOs). + Ok(VmReadGuard(self.gpuvm.lock_inner())) } #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] @@ -2660,7 +2662,7 @@ impl Vm { } let phys = inner.page_table.translate_iova(page).map_err(|_| EFAULT)?; // SAFETY: `phys` is checked to be a RAM page; it stays mapped (and its backing pinned) - // while the exec lock is held, and is only read here. + // while the VM reservation lock is held, and is only read here. let ram = unsafe { kernel::page::Page::borrow_phys(&phys) }.ok_or(EFAULT)?; let target = &mut buf[done..done + count]; ram.with_pointer_into_page(within, count, |p| { diff --git a/drivers/gpu/drm/asahi/timestamp.rs b/drivers/gpu/drm/asahi/timestamp.rs index 7118cffde3301..04c0cc1162610 100644 --- a/drivers/gpu/drm/asahi/timestamp.rs +++ b/drivers/gpu/drm/asahi/timestamp.rs @@ -203,6 +203,12 @@ pub(crate) struct Destinations(Option Self { + Self(None) + } + /// No timestamp is written for this command. #[allow(dead_code)] pub(crate) fn is_empty(&self) -> bool { diff --git a/drivers/gpu/drm/asahi/usage.rs b/drivers/gpu/drm/asahi/usage.rs index 949039d91cfae..36a7f3ed17e69 100644 --- a/drivers/gpu/drm/asahi/usage.rs +++ b/drivers/gpu/drm/asahi/usage.rs @@ -31,6 +31,7 @@ pub(crate) enum Engine { /// One ledger per DRM file, shared by all of its queues and VMs. pub(crate) struct Client { ns: [AtomicU64; NUM_ENGINES], + covered: [AtomicU64; NUM_ENGINES], queues: AtomicU32, } @@ -38,6 +39,7 @@ impl Client { pub(crate) const fn new() -> Self { Self { ns: [const { AtomicU64::new(0) }; NUM_ENGINES], + covered: [const { AtomicU64::new(0) }; NUM_ENGINES], queues: AtomicU32::new(0), } } @@ -98,17 +100,48 @@ impl Client { } } + /// As [`Self::add`], deduplicating overlapping stage intervals across all queues of this + /// DRM file (including sibling queues running concurrently on multiple hardware pipes). + /// Only the part of `start..end` after the file's per-engine mark is charged, and the + /// mark advances to `end`. + pub(crate) fn add_union(&self, engine: Engine, start: u64, end: u64, frequency_hz: u32) { + if let Some(from) = union_mark(&self.covered[engine as usize], start, end, frequency_hz) { + self.add(engine, from, end, frequency_hz); + } + } + /// Vertex, fragment and compute, in ns. No cross-engine atomic snapshot is promised. pub(crate) fn snapshot(&self) -> [u64; NUM_ENGINES] { self.ns.each_ref().map(|ns| ns.load(Ordering::Relaxed)) } } -/// A stage this far behind its lane's mark is not an overlap, since no stage runs this -/// long: the timestamps jumped, so the mark restarts at the stage instead of holding every +/// A stage this far behind its mark is not an overlap, since no stage runs this long: +/// the timestamps jumped, so the mark restarts at the stage instead of holding every /// later charge back. const DISCONTINUITY_S: u64 = 60; +/// Advances `mark` to cover `start..end`, returning the uncovered sub-interval start `from` +/// when `from < end`, or `None` when the interval is invalid or already covered. +fn union_mark(mark: &AtomicU64, start: u64, end: u64, frequency_hz: u32) -> Option { + if start == 0 || end <= start || frequency_hz == 0 { + return None; + } + let limit = u64::from(frequency_hz).saturating_mul(DISCONTINUITY_S); + let mut covered = mark.load(Ordering::Relaxed); + loop { + let jumped = covered.saturating_sub(start) > limit; + let from = if jumped { start } else { start.max(covered) }; + if from >= end { + return None; + } + match mark.compare_exchange_weak(covered, end, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return Some(from), + Err(value) => covered = value, + } + } +} + /// The engine time of one queue, charged to its file's [`Client`]. /// /// Firmware can run several commands of one queue at once. A queue that keeps several @@ -134,24 +167,9 @@ impl> Lane

{ /// As [`Client::add`], for one retired stage of this lane's queue: only the part of /// `start..end` after the engine's mark is charged, and the mark moves to `end`. pub(crate) fn add(&self, engine: Engine, start: u64, end: u64, frequency_hz: u32) { - if start == 0 || end <= start || frequency_hz == 0 { - return; + if let Some(from) = union_mark(&self.covered[engine as usize], start, end, frequency_hz) { + self.client.add(engine, from, end, frequency_hz); } - let limit = u64::from(frequency_hz).saturating_mul(DISCONTINUITY_S); - let mark = &self.covered[engine as usize]; - let mut covered = mark.load(Ordering::Relaxed); - let from = loop { - let jumped = covered.saturating_sub(start) > limit; - let from = if jumped { start } else { start.max(covered) }; - if from >= end { - return; - } - match mark.compare_exchange_weak(covered, end, Ordering::Relaxed, Ordering::Relaxed) { - Ok(_) => break from, - Err(value) => covered = value, - } - }; - self.client.add(engine, from, end, frequency_hz); } } @@ -303,6 +321,33 @@ mod tests { assert_eq!(client.snapshot(), [0, 0, 4_000]); } + #[test] + fn client_union_deduplicates_dual_pipe_siblings_and_isolates_files() { + let file_a = Client::new(); + let file_b = Client::new(); + // Two sibling queues on the same DRM file overlapping across two CDM pipes + // (e.g., 543 us dispatches at depth 4). + const PERIOD: u64 = 13_032; // 543 us at 24 MHz + for i in 0..100u64 { + let p0_start = 1_000 + i * PERIOD; + let p1_start = p0_start + PERIOD / 4; + file_a.add_union(Engine::Compute, p0_start, p0_start + PERIOD, HZ); + file_a.add_union(Engine::Compute, p1_start, p1_start + PERIOD, HZ); + } + let wall = ticks_to_ns(99 * PERIOD + PERIOD / 4 + PERIOD, HZ); + assert_eq!(file_a.snapshot()[2], wall); + // Separate DRM file keeps its own union mark. + file_b.add_union(Engine::Compute, 1_000, 1_000 + PERIOD, HZ); + assert_eq!(file_b.snapshot()[2], ticks_to_ns(PERIOD, HZ)); + // Timestamp jump > 60 s behind the mark restarts the file mark cleanly. + let far = 61 * u64::from(HZ); + file_b.add_union(Engine::Compute, 1, far, HZ); + let before = file_b.snapshot()[2]; + file_b.add_union(Engine::Compute, 24, 48, HZ); + file_b.add_union(Engine::Compute, 36, 72, HZ); + assert_eq!(file_b.snapshot()[2] - before, 2_000); + } + #[test] fn a_timestamp_jump_restarts_the_mark() { let client = Client::new(); diff --git a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py index b0c3105235f7b..571ad60f59e70 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py +++ b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py @@ -114,7 +114,7 @@ pub const UAT_PGSZ: usize = 0x4000; pub const UAT_PGMSK: usize = UAT_PGSZ - 1; pub struct Vm(pub Vec); - pub type VmReadGuard = Vm; + pub type VmReadGuard<'a> = Vm; impl Vm { pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { let start = usize::try_from(va).map_err(|_| EFAULT)?; @@ -134,7 +134,7 @@ /// cover() calls: the page checks the walk made. pub static COVERS: Cell = Cell::new(0); } - pub fn cover(vm: &mut mmu::VmReadGuard, start: u64, end: u64, _: bool, _: bool) -> Result { + pub fn cover(vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, _: bool, _: bool) -> Result { COVERS.with(|c| c.set(c.get() + 1)); if start >= SYNTHETIC { return Ok(()); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs index 4809b1d85de46..d766bcdbb9646 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs @@ -421,6 +421,10 @@ fn main() { assert!(main[0x640 + 28 * 0x28..0x640 + 29 * 0x28].iter().all(|&b| b == 0)); let power = object(&v26, l, id::POWER_PERFORMANCE); assert_eq!(r64(power, 0x3b98), input().va[id::TEMPERATURE]); + assert_eq!(r32(object(&v25, &wire::V25G83, id::GLOBALS), 0x9c8), 750); + assert_eq!(r32(object(&v26, l, id::GLOBALS), 0x9cc), 750); + assert_eq!(r32(object(&v25, &wire::V25G83, id::GLOBALS), 0x9cc), 800); + assert_eq!(r32(object(&v26, l, id::GLOBALS), 0x9d0), 800); std::fs::write(out.join("initdata-25g83.bin"), &v25).unwrap(); std::fs::write(out.join("initdata-26b123.bin"), &v26).unwrap(); render(&out); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs index 03ab056cc5e46..bf002c5a59764 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs @@ -63,6 +63,14 @@ fn main() { expected[at..at+4].copy_from_slice(&value.to_le_bytes()); } }} + // Substitute calibrated DM2 compute watchdogs (40 -> 750, 50 -> 800) in the frozen C + // golden. + let globals: usize = initdata::OBJECT_SIZE[..initdata::id::GLOBALS].iter().sum(); + for (offset, old, new) in [(0x9c8usize, 40u32, 750u32), (0x9ccusize, 50u32, 800u32)] { + let wd = globals + offset; + assert_eq!(u32::from_le_bytes(expected[wd..wd+4].try_into().unwrap()), old); + expected[wd..wd+4].copy_from_slice(&new.to_le_bytes()); + } if let Some(offset) = got.iter().zip(&expected).position(|(a, b)| a != b) { panic!("initdata variant {variant} differs at {offset:#x}: C={:#x}, Rust={:#x}", expected[offset], got[offset]); } 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 e654fbbb95bed..1d42a67358760 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 @@ -51,6 +51,21 @@ if errors: raise RuntimeError('Kernel UAPI ABI differs from the M5 bindings: ' + json.dumps(errors)) command = SOURCE.read_text() +queue_src = (SOURCE.parent / 'queue.rs').read_text() +poll_src = (SOURCE.parent / 'poll.rs').read_text() +assert 'command::parse_stream(bytes, params::early_tiling())?' in queue_src +assert 'parsed.prepare(self.accepted, objects)?' in queue_src +assert 'command::check_stream(' not in queue_src +parse_idx = command.index('pub(crate) fn parse_stream(') +prep_idx = command.index('impl ParsedStream {') +assert 'stream(bytes)' in command[parse_idx:prep_idx] +assert 'stream(bytes)' not in command[prep_idx:] +assert 'resnap_has_handle' not in poll_src +assert 'let mut handle = self.resnap_handle.lock();' in poll_src +assert 'if self.sleeping.load(Ordering::Acquire)' in poll_src +assert 'fn check_stream(' not in command +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)) names = ['drm_asahi_cmd_header', 'drm_asahi_attachment', 'drm_asahi_cmd_render', @@ -58,8 +73,13 @@ 'drm_asahi_timestamp', 'drm_asahi_timestamps', 'drm_asahi_helper_program', 'drm_asahi_render_ray_query_stage'] constants = command[command.index('/// Largest command buffer.'):command.index('/// A validated render command.')] +parse_types = command[command.index('/// A validated render command.'):command.index('/// Inline storage for the common 1-2 command ordinals')] inline_containers = command[command.index('/// Inline storage for the common 1-2 command submission'):command.index('/// A validated SUBMIT.')] -parser = command[command.index('/// One command of the stream.'):command.index('/// Checks that `[start, end)`')] +parser = ( + command[command.index('/// One command of the stream.'):command.index('/// Checks that `[start, end)`')] + + command[command.index('/// Parses the attachment list'):command.index('/// Checks that `[start, end)` (rounded out to pages) is user memory mapped')] + + command[command.index('/// Per-command barrier and stage-prefix metadata'):command.index('impl ParsedStream {')] +) render_admission = ( command[command.index('/// Checks that `[start, end)`'):command.index('/// Parses the attachment list')] + command[command.index('/// Whether a GVA can be named by a 32-bit compact pointer.'):command.index('/// Per-command compute admission.')] @@ -77,12 +97,29 @@ const EINVAL: i32 = -22; const EOVERFLOW: i32 = -75; const E2BIG: i32 = -7; +const GFP_KERNEL: u32 = 0; struct Error; impl Error { fn from_errno(error:i32)->i32 { error } } extern crate self as kernel; // 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(crate) mod timestamp { + pub(crate) struct Destinations; + impl Destinations { pub(crate) const fn empty() -> Self { Self } } +} +pub(crate) struct KBox(Box); +impl KBox { fn new(v: T, _: u32) -> Result { Ok(Self(Box::new(v))) } } +impl core::ops::Deref for KBox { type Target = T; fn deref(&self) -> &T { &self.0 } } +pub(crate) struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn with_capacity(cap: usize, _: u32) -> Result { Ok(Self(Vec::with_capacity(cap))) } + fn push(&mut self, v: T, _: 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 } } mod uapi { include!("FULL_UAPI"); } mod file { pub const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; } mod hw { @@ -98,9 +135,13 @@ READER IMPLS PRODUCTION_CONSTANTS +PARSE_TYPES PRODUCTION_PARSER +fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { + parse_stream(bytes, early_tiling).map(|_| ()) +} mod g17 { - use super::{uapi, AnyBitPattern, Reader, Result, EINVAL, size_of, offset_of, Range}; + use super::{uapi, AnyBitPattern, Reader, Result, EINVAL, size_of, Range}; G17_CONSTANTS const STAGE_PREFIXES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; @@ -548,15 +589,17 @@ 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 } + } INLINE_CONTAINERS #[test] - fn inline_commands_orders_and_resolved_skip_heap_up_to_two_and_spill_safely() { + fn inline_commands_and_orders_skip_heap_up_to_two_and_spill_safely() { ALLOCS.with(|a| a.set(0)); let mut cmds = Commands::new(); let mut orders = Orders::new(); - let mut resolved = Resolved::new(); let o0 = Order::new([0, 0], [0, 0], [NONE; 2], [0; 2], COMPUTE).unwrap(); let o1 = Order::new([0, 0], [0, 1], [NONE; 2], [0; 2], RENDER).unwrap(); let o2 = Order::new([0, 0], [1, 1], [NONE; 2], [0; 2], COMPUTE).unwrap(); @@ -564,8 +607,6 @@ cmds.push(Command(2)).unwrap(); orders.push(o0).unwrap(); orders.push(o1).unwrap(); - resolved.push(timestamp::Destinations(11)).unwrap(); - resolved.push(timestamp::Destinations(22)).unwrap(); assert_eq!(ALLOCS.with(|a| a.get()), 0); assert_eq!(&*cmds, &[Command(1), Command(2)]); assert_eq!(&*orders, &[o0, o1]); @@ -577,21 +618,14 @@ FAIL_NEXT.with(|f| f.set(true)); assert_eq!(orders.push(o2), Err(ENOMEM)); assert_eq!(&*orders, &[o0, o1]); - FAIL_NEXT.with(|f| f.set(true)); - assert_eq!(resolved.push(timestamp::Destinations(33)), Err(ENOMEM)); assert_eq!(ALLOCS.with(|a| a.get()), 0); - // Spill to heap preserves exact FIFO order across all 3 containers. + // Spill to heap preserves exact FIFO order across both containers. cmds.push(Command(3)).unwrap(); orders.push(o2).unwrap(); - resolved.push(timestamp::Destinations(33)).unwrap(); - assert_eq!(ALLOCS.with(|a| a.get()), 3); + assert_eq!(ALLOCS.with(|a| a.get()), 2); assert_eq!(&*cmds, &[Command(1), Command(2), Command(3)]); assert_eq!(&*orders, &[o0, o1, o2]); - assert_eq!(resolved.next(), Some(timestamp::Destinations(11))); - assert_eq!(resolved.next(), Some(timestamp::Destinations(22))); - assert_eq!(resolved.next(), Some(timestamp::Destinations(33))); - assert_eq!(resolved.next(), None); } } mod render_admission_tests { @@ -617,11 +651,20 @@ } pub(crate) mod mmu { pub(crate) const UAT_PGMSK: usize = 0x3fff; + pub(crate) struct VmReadGuard<'a>(&'a Vm); + impl VmReadGuard<'_> { + pub(crate) fn covers_range(&mut self, start: u64, size: u64, read: bool, write: bool) -> bool { + self.0.covers_range(start, size, read, write) + } + } pub(crate) struct Vm { pub(crate) maps: Vec<(u64, u64, bool, bool)>, pub(crate) batch_calls: std::cell::Cell, } impl Vm { + pub(crate) fn read_lock(&self) -> super::Result> { + Ok(VmReadGuard(self)) + } pub(crate) fn covers_range(&self, start: u64, size: u64, read: bool, write: bool) -> bool { let Some(end) = start.checked_add(size) else { return false }; self.maps.iter().any(|&(s, e, r, w)| { @@ -790,6 +833,11 @@ assert_eq!(vm.batch_calls.get(), 0); assert_eq!(batch.flush(&vm), Ok(())); assert_eq!(vm.batch_calls.get(), 1); + let mut guard = vm.read_lock().unwrap(); + assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); + assert_eq!(batch.flush_locked(&mut guard), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + drop(guard); // Unmapped or read-only span on a later pass still reports exact ENOENT / EACCES. let mut bad_unmapped = base_cmd(); @@ -812,7 +860,8 @@ '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'), 'IMPLS': '\n'.join('unsafe impl AnyBitPattern for uapi::' + name + ' {}' for name in names), - 'PRODUCTION_CONSTANTS': constants, 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), + 'PRODUCTION_CONSTANTS': constants, 'PARSE_TYPES': parse_types, + 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), '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-job-failure.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py index a178d24d2288d..d7058193d5739 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 @@ -109,6 +109,7 @@ def function(text, name): Arc::new(Self{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),recovering:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) } fn note_submitter(&self) {} + fn wake_publish(&self) {} fn submit(&self,job:Arc)->Result { self.submitted.lock().unwrap().push(job.id); self.submit_result } 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 38a0e6112d8b0..5befe96f289b7 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 @@ -6,18 +6,32 @@ import subprocess production = kernel_root() / 'drivers/gpu/drm/asahi/g16/poll.rs' +queue_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/queue.rs').read_text() +event_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/event.rs').read_text() +mod_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() source = production.read_text() output = output_dir() +assert 'const EVENT_RETIRE_POLLS: u32 = 11;' in source, 'EVENT_RETIRE_POLLS expected to be 11' +assert ( + 'OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)' in mod_source +), 'aurora_g16_events must use new_percpu_reclaim(..., true)' +assert ( + 'pub(crate) usage: Arc' in queue_source +), 'QueueState::usage must reference the per-file usage::Client' +assert ( + '.add_union(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32)' in source +), 'G16 poll retirement must deduplicate per-file intervals via Client::add_union' -def item(declaration): - start = source.index(declaration) - at = source.index('{', start) + +def item(declaration, text=source): + start = text.index(declaration) + at = text.index('{', start) depth, end = 1, at + 1 while depth: - depth += (source[end] == '{') - (source[end] == '}') + depth += (text[end] == '{') - (text[end] == '}') end += 1 - return source[start:end] + return text[start:end] harness = r''' @@ -118,6 +132,7 @@ def item(declaration): target: u32, fs_target: u32, chan_wait: bool, + slot_wait: bool, short_repoll: bool, frozen: bool, stats: Stats, @@ -170,20 +185,26 @@ def item(declaration): struct Shared { sleeping: AtomicBool, evented: AtomicBool, + publish_wake: AtomicBool, rearmed: Cell, + idle_power_polls: Cell, } impl Shared { fn new() -> Arc { Arc::new(Self { sleeping: AtomicBool::new(false), evented: AtomicBool::new(false), + publish_wake: AtomicBool::new(false), rearmed: Cell::new(0), + idle_power_polls: Cell::new(0), }) } fn rearm(&self, _soon: bool) { self.rearmed.set(self.rearmed.get() + 1); } - fn arm_idle_power_poll(&self, _firmware: &Firmware) {} + fn arm_idle_power_poll(&self, _firmware: &Firmware) { + self.idle_power_polls.set(self.idle_power_polls.get() + 1); + } fn fail_stop(&self, _e: Error) {} __SUBMIT_LOCKED__ } @@ -191,12 +212,27 @@ def item(declaration): #[derive(Default)] struct Power { ramp: bool, + idle_reports: u32, } impl Power { fn needs_ramp(&self, _now: u64) -> bool { self.ramp } - fn report_work(&mut self, _in_flight: bool) {} + fn report_work(&mut self, in_flight: bool) { + if !in_flight { + self.idle_reports += 1; + } + } +} + +#[derive(Default)] +struct Slots { + scrub_woke: AtomicBool, +} +impl Slots { + fn take_scrub_woke(&self) -> bool { + self.scrub_woke.swap(false, Ordering::AcqRel) + } } struct Firmware { @@ -207,9 +243,11 @@ def item(declaration): events: Events, recovery: Recovery, power: Power, + slots: Slots, last_housekeeping_ns: u64, // Test script knobs for retire_once / publish / housekeeping observation. retire_on_call: bool, + unfreeze_on_hang_check: bool, drain_stage_delta: u32, drain_fs_delta: u32, drain_compute_delta: u32, @@ -240,6 +278,7 @@ def item(declaration): target: 0, fs_target: 0, chan_wait: false, + slot_wait: false, short_repoll: false, frozen: false, stats: Stats::default(), @@ -248,8 +287,10 @@ def item(declaration): events: Events::default(), recovery: Recovery::default(), power: Power::default(), + slots: Slots::default(), last_housekeeping_ns: 0, retire_on_call: false, + unfreeze_on_hang_check: false, drain_stage_delta: 0, drain_fs_delta: 0, drain_compute_delta: 0, @@ -282,6 +323,10 @@ def item(declaration): Ok(()) } fn check_hangs(&mut self, _done: &mut Completions) -> Result { + if self.unfreeze_on_hang_check { + self.engine.frozen = false; + self.recovery.pending = false; + } Ok(()) } fn fail_stop(&mut self, error: Error, _done: &mut Completions) { @@ -484,15 +529,532 @@ def item(declaration): assert_eq!(fr.graph.render.fw_stamp[0].reads.get(), 0); assert_eq!(fr.graph.render.fw_stamp[1].reads.get(), 1); } + +#[test] +fn poll_step_skips_publish_when_pending_blocked_and_nothing_retired() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.fs_target = 0x100; + fw.drain_stage_delta = 1; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + + // Waking via scrub_woke triggers publish_checked once. + fw.slots.scrub_woke.store(true, Ordering::Release); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + + // Waking via chan_wait triggers publish_checked. + fw.engine.chan_wait = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + fw.engine.chan_wait = false; + + // Waking via unfreeze triggers publish_checked. + fw.engine.frozen = true; + fw.recovery.pending = true; + fw.unfreeze_on_hang_check = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 3); + + // Waking via external publish_wake (e.g. VM close or unstarted queue cancel) triggers + // publish_checked once while flights remain active, then skips again on the next busy poll. + let shared = Shared::new(); + fw.engine.shared = Some(shared.clone()); + shared.publish_wake.store(true, Ordering::Release); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 4); + assert!(!shared.publish_wake.load(Ordering::Acquire)); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 4); + + // Waking via retirement triggers publish_checked (and returns false since flights drained). + fw.retire_on_call = true; + assert!(!fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 5); +} + +#[test] +fn pending_slot_wait_arms_short_repoll_without_breaking_ta_only_or_frozen() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 11, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + + // No pending work on a timer poll -> keep normal resnap_us interval. + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + + // Pending job NOT blocked on slot headroom (e.g. external fence / cross-VM / InitBM) -> + // keep normal resnap_us interval without arming short_repoll. + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.slot_wait = false; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + + // Pending job waiting on slot headroom on a non-event poll -> arm short_repoll. + fw.engine.slot_wait = true; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(fw.engine.short_repoll); + + // TA-only EP 0x20 event still suppresses short_repoll. + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 0; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + fw.drain_stage_delta = 0; + + // Frozen engine suppresses short_repoll even with pending work. + fw.engine.frozen = true; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); +} + +mod boot { + pub fn eproto() -> super::Error { + super::Error(-71) + } +} + +mod event_drain_test { + use super::{Error, Result}; + use std::cell::{Cell, RefCell}; + + const EIO: Error = Error(-5); + const STATE_READ: usize = 0; + const STATE_WRITE: usize = 0x40; + const RING_SLOTS: u32 = 128; + const RECORD_WORDS: usize = 18; + const STAGE_EVENTS: [u32; 3] = [0x70, 0x71, 15]; + mod rings { + pub const EVENT_RECORD: usize = 0x48; + } + mod bindings { + pub unsafe fn ktime_get() -> i64 { + 12345 + } + } + mod device { + pub struct Device; + } + macro_rules! dev_warn { ($dev:expr, $($arg:tt)*) => {{ let _ = ($dev, format_args!($($arg)*)); }}; } + macro_rules! dev_err { ($dev:expr, $($arg:tt)*) => {{ let _ = ($dev, format_args!($($arg)*)); }}; } + fn rmb() {} + fn wmb() {} + fn mb() {} + + struct Mem { + words: RefCell>, + reads: Cell, + writes: Cell, + fail_at_offset: Cell>, + } + impl Mem { + fn new(n_words: usize) -> Self { + Self { + words: RefCell::new(vec![0u32; n_words]), + reads: Cell::new(0), + writes: Cell::new(0), + fail_at_offset: Cell::new(None), + } + } + fn r32(&self, off: usize) -> Result { + self.reads.set(self.reads.get() + 1); + if self.fail_at_offset.get() == Some(off) { + return Err(EIO); + } + Ok(self.words.borrow()[off / 4]) + } + fn w32(&self, off: usize, val: u32) -> Result { + self.writes.set(self.writes.get() + 1); + self.words.borrow_mut()[off / 4] = val; + Ok(()) + } + } + + struct Ring { + state: Mem, + ring: Mem, + } + impl Ring { + fn new() -> Self { + Self { + state: Mem::new(0x40), + ring: Mem::new(RING_SLOTS as usize * RECORD_WORDS), + } + } + fn put_record(&self, slot: u32, words: &[u32]) { + let mut buf = self.ring.words.borrow_mut(); + let base = slot as usize * RECORD_WORDS; + for (i, &w) in words.iter().enumerate() { + buf[base + i] = w; + } + } + fn set_indices(&self, read: u32, write: u32) { + let mut st = self.state.words.borrow_mut(); + st[STATE_READ / 4] = read; + st[STATE_WRITE / 4] = write; + } + fn read_idx(&self) -> u32 { + self.state.words.borrow()[STATE_READ / 4] + } + } + + #[derive(Clone, Copy)] + struct ErrorEvent { + kind: u32, + slot: i32, + raw: [u32; RECORD_WORDS], + } + + #[derive(Default)] + struct Events { + stage_events: u32, + ta_events: u32, + fs_events: u32, + compute_events: u32, + event_ns: [u64; 3], + errors: u32, + channel_errors: u32, + recovery_started_ns: Option, + last_error: Option, + last_statistics: Option<[u32; RECORD_WORDS]>, + recovery_statistics: u32, + } + + impl Events { + fn indices(ring: &Ring) -> Result<(u32, u32)> { + let read = ring.state.r32(STATE_READ)?; + let producer = ring.state.r32(STATE_WRITE)?; + if read >= RING_SLOTS || producer >= RING_SLOTS { + return Err(EIO); + } + rmb(); + Ok((read, producer)) + } + fn words(ring: &Ring, slot: u32) -> Result<[u32; RECORD_WORDS]> { + let base = slot as usize * rings::EVENT_RECORD; + let mut out = [0u32; RECORD_WORDS]; + for (i, word) in out.iter_mut().enumerate() { + *word = ring.ring.r32(base + i * 4)?; + } + Ok(out) + } + __EVENT_DRAIN__ + __EVENT_DRAIN_STATS__ + } + + #[test] + fn event_drain_batches_state_read_and_minimizes_wc_reads() { + let ring = Ring::new(); + // 3 consecutive type-1 stage events: TA (0x70 -> word 4 bit 16), FS (0x71 -> word 4 bit 17), Compute (15 -> word 1 bit 15). + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 1; + r0[4] = 1 << 16; + let mut r1 = [0u32; RECORD_WORDS]; + r1[0] = 1; + r1[4] = 1 << 17; + let mut r2 = [0u32; RECORD_WORDS]; + r2[0] = 1; + r2[1] = 1 << 15; + ring.put_record(0, &r0); + ring.put_record(1, &r1); + ring.put_record(2, &r2); + ring.set_indices(0, 3); + + let mut ev = Events::default(); + ev.drain(&device::Device, &ring).unwrap(); + assert_eq!(ev.event_ns[0], 12345); + assert_eq!(ev.fs_events, 1); + assert_eq!(ev.compute_events, 1); + assert_eq!(ev.stage_events, 3); + assert_eq!(ring.read_idx(), 3); + // Exactly ONE STATE_READ write for all 3 records! + assert_eq!(ring.state.writes.get(), 1); + // Exactly 3 WC reads per type-1 record (kind, word 1, word 4) = 9 reads (not 54)! + assert_eq!(ring.ring.reads.get(), 9); + } + + #[test] + fn event_drain_flushes_progress_on_mid_burst_error() { + let ring = Ring::new(); + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 1; + r0[4] = 1 << 17; + ring.put_record(0, &r0); + ring.set_indices(0, 2); + // Fail reading record 1's kind word. + ring.ring.fail_at_offset.set(Some(rings::EVENT_RECORD)); + let mut ev = Events::default(); + assert_eq!(ev.drain(&device::Device, &ring), Err(EIO)); + // Record 0 progress must still have been flushed to STATE_READ = 1. + assert_eq!(ring.read_idx(), 1); + assert_eq!(ring.state.writes.get(), 1); + assert_eq!(ev.fs_events, 1); + } + + #[test] + fn stats_drain_batches_state_read_and_reads_single_word_for_non_recovery() { + let ring = Ring::new(); + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 0x10; + let mut r1 = [0u32; RECORD_WORDS]; + r1[0] = 0x11; + let mut r2 = [0u32; RECORD_WORDS]; + r2[0] = 0x16; + ring.put_record(0, &r0); + ring.put_record(1, &r1); + ring.put_record(2, &r2); + ring.set_indices(0, 3); + + let mut ev = Events::default(); + ev.drain_statistics(&device::Device, &ring).unwrap(); + assert_eq!(ev.recovery_statistics, 1); + assert!(ev.last_statistics.is_some()); + assert_eq!(ring.read_idx(), 3); + assert_eq!(ring.state.writes.get(), 1); + // 1 read each for r0, r1 + 1 (kind) + 18 (full words) for r2 = 21 reads (vs 54). + assert_eq!(ring.ring.reads.get(), 21); + } +} + +mod resnap_sync_test { + use std::sync::{ + Arc, Barrier, Mutex, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + }; + + const BACKUP_REARM_NS: u64 = 1_000_000; + static CLOCK: AtomicU64 = AtomicU64::new(0); + fn now_ns() -> u64 { + CLOCK.load(Ordering::Acquire) + } + + mod params { + pub fn resnap_us() -> u32 { + 100 + } + pub fn repoll_us() -> u32 { + 25 + } + } + #[allow(non_upper_case_globals)] + mod module_parameters { + pub struct Param(u32); + impl Param { + pub fn value(&self) -> u32 { + self.0 + } + } + pub static g16_repoll_us: Param = Param(25); + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + struct Delta(i64); + impl Delta { + fn from_micros(us: i64) -> Self { + Self(us) + } + } + + struct Handle { + drops: Arc, + } + impl Drop for Handle { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::AcqRel); + } + } + + struct Lock(Mutex); + impl Lock { + fn new(v: T) -> Self { + Self(Mutex::new(v)) + } + fn lock(&self) -> std::sync::MutexGuard<'_, T> { + self.0.lock().unwrap() + } + } + + struct Shared { + sleeping: AtomicBool, + resnap_deadline_ns: AtomicU64, + backup_deadline_ns: AtomicU64, + resnap_handle: Lock>, + starts: AtomicU32, + drops: Arc, + mod_polls: AtomicU32, + } + + impl Shared { + fn new() -> Arc { + Arc::new(Self { + sleeping: AtomicBool::new(false), + resnap_deadline_ns: AtomicU64::new(0), + backup_deadline_ns: AtomicU64::new(0), + resnap_handle: Lock::new(None), + starts: AtomicU32::new(0), + drops: Arc::new(AtomicU32::new(0)), + mod_polls: AtomicU32::new(0), + }) + } + fn start(self: Arc, _delta: Delta) -> Handle { + self.starts.fetch_add(1, Ordering::AcqRel); + Handle { + drops: self.drops.clone(), + } + } + fn mod_poll(self: &Arc, _delay: u64) { + self.mod_polls.fetch_add(1, Ordering::AcqRel); + } + + __CANCEL_RESNAP__ + __REARM__ + } + + #[test] + fn resnap_rearm_coalesces_and_cancel_disarms_unconditionally() { + CLOCK.store(100_000, Ordering::Release); + let shared = Shared::new(); + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 200_000); + assert!(shared.resnap_handle.lock().is_some()); + + // Same-window rearm coalesces without cancelling/restarting the handle. + CLOCK.store(102_000, Ordering::Release); + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + + // Sooner repoll (>5 us earlier) replaces the handle cleanly. + shared.rearm(true); + assert_eq!(shared.starts.load(Ordering::Acquire), 2); + assert_eq!(shared.drops.load(Ordering::Acquire), 1); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 127_000); + + // cancel_resnap unconditionally clears deadline and drops handle. + shared.cancel_resnap(); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + assert!(shared.resnap_handle.lock().is_none()); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + } + + #[test] + fn sleep_cancel_resnap_never_leaves_handle_armed_under_concurrent_rearm() { + CLOCK.store(1_000_000, Ordering::Release); + for _ in 0..200 { + let shared = Shared::new(); + shared.rearm(false); + let start = Arc::new(Barrier::new(2)); + let s1 = shared.clone(); + let b1 = start.clone(); + let t = std::thread::spawn(move || { + b1.wait(); + for _ in 0..32 { + s1.rearm(true); + } + }); + start.wait(); + // Exact sleep_down() + join_workers() sequence: sleeping = true, then cancel_resnap(). + shared.sleeping.store(true, Ordering::Release); + shared.cancel_resnap(); + t.join().unwrap(); + assert!( + shared.resnap_handle.lock().is_none(), + "rearm leaked an hrtimer handle past sleep_down() + cancel_resnap()" + ); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + } + } +} + +#[path = "__USAGE_PATH__"] +mod usage; + +#[test] +fn per_file_usage_union_deduplicates_pipelined_and_dual_pipe_siblings() { + let client = Arc::new(usage::Client::new()); + const HZ: u32 = 24_000_000; + // Two pipelined renders whose TA and FS intervals overlap across flights. + client.add_union(usage::Engine::Vertex, 24_000, 48_000, HZ); + client.add_union(usage::Engine::Fragment, 40_000, 88_000, HZ); + client.add_union(usage::Engine::Vertex, 36_000, 72_000, HZ); + client.add_union(usage::Engine::Fragment, 64_000, 120_000, HZ); + // Two sibling queues on the same DRM file overlapping across dual CDM pipes. + client.add_union(usage::Engine::Compute, 100_000, 124_000, HZ); + client.add_union(usage::Engine::Compute, 106_000, 130_000, HZ); + let [v_ns, f_ns, c_ns] = client.snapshot(); + // Vertex union: [24k, 72k] = 48k ticks = 2_000_000 ns (not 60k ticks = 2.5 ms). + assert_eq!(v_ns, 2_000_000); + // Fragment union: [40k, 120k] = 80k ticks = 3_333_333 ns (distinct from Vertex). + assert_eq!(f_ns, 3_333_333); + assert_ne!(v_ns, f_ns); + // Compute union: [100k, 130k] = 30k ticks = 1_250_000 ns (not 48k ticks = 2.0 ms). + assert_eq!(c_ns, 1_250_000); +} ''' +harness = harness.replace( + '__USAGE_PATH__', str(kernel_root() / 'drivers/gpu/drm/asahi/usage.rs') +) + for token, decl in { '__SUBMIT_LOCKED__': 'fn submit_locked(', '__POLL_STEP__': 'pub(crate) fn poll_step(', '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', + '__CANCEL_RESNAP__': 'pub(crate) fn cancel_resnap(', + '__REARM__': 'pub(crate) fn rearm(', }.items(): harness = harness.replace(token, item(decl)) +for token, decl in { + '__EVENT_DRAIN__': 'pub(crate) fn drain(', + '__EVENT_DRAIN_STATS__': 'pub(crate) fn drain_statistics(', +}.items(): + harness = harness.replace(token, item(decl, event_source)) unit = output / 'poll-retire.rs' unit.write_text(harness) @@ -511,7 +1073,7 @@ def item(declaration): json.dumps( { 'passed': True, - 'tests': 4, + 'tests': 12, '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-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 9dd42f19a2c50..b909d40dffb1a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -45,15 +45,33 @@ def item(declaration): assert 'const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32;' in hw_src prefix_render_fn = item('fn prefix_render(') prefix_compute_fn = item('fn prefix_compute(') -assert 'let render_bar = BarrierType::from_stamp_only(!init_buffer);' in prefix_render_fn -assert prefix_render_fn.count('render_bar,') == 3, prefix_render_fn +can_queue_behind_fn = item('fn can_queue_behind(') +assert 'let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);' in prefix_render_fn +assert ( + prefix_render_fn.index('let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);') + < prefix_render_fn.index('if plan.ta_prev_wait') +), 'render_bar must be hoisted ahead of barrier emission' +assert prefix_render_fn.count('render_bar,') == 5, prefix_render_fn +assert 'p.prev_barrier.write(0, &prev)?;' in prefix_render_fn assert 'p.ta_fs_barrier.write(0, &ta_fs)?;' in prefix_render_fn +assert 'p.fs_dep.write(0, &dep)?;' in prefix_render_fn assert 'p.compute_barrier.write(0, &cbar)?;' in prefix_render_fn assert 'p.fs_compute_barrier.write(0, &fcbar)?;' in prefix_render_fn -assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('plan.ta_compute_wait'):prefix_render_fn.index('p.compute_barrier.write')] -assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('plan.fs_compute_wait'):prefix_render_fn.index('p.fs_compute_barrier.write')] +c2ta_slice = prefix_render_fn[ + prefix_render_fn.index('plan.ta_compute_wait'):prefix_render_fn.index('p.compute_barrier.write') +] +c2fs_slice = prefix_render_fn[ + prefix_render_fn.index('plan.fs_compute_wait'):prefix_render_fn.index('p.fs_compute_barrier.write') +] +fs2c_slice = prefix_compute_fn[ + prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write') +] +assert 'render_bar,' in c2ta_slice and 'BarrierType::Hold' not in c2ta_slice +assert 'render_bar,' in c2fs_slice and 'BarrierType::Hold' not in c2fs_slice assert 'BarrierType::Stamp,' in prefix_render_fn[prefix_render_fn.index('let own = encode::barrier'):prefix_render_fn.index('p.own_barrier.write')] -assert 'BarrierType::Hold,' in prefix_compute_fn[prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write')] +assert 'cross_engine_barrier_type(producer_initbm, false)' in fs2c_slice +assert 'bar_type,' in fs2c_slice and 'BarrierType::Hold' not in fs2c_slice +assert 'let waits_for_timestamps = c.query_access' in can_queue_behind_fn assert 'DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2' in params_src @@ -93,7 +111,7 @@ def item(declaration): struct Claims; struct Flight{job:Arc,claims:Claims,group:Vec>,doomed:bool,recovery_suspect:bool,initbm:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],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} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool} impl Engine { __PICK__ __UNPEND__ @@ -179,6 +197,12 @@ def item(declaration): fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} fn sync_quarantine_hints(&self){} __NEEDS_ENGINE_DRAIN__ + fn blocked_on_slot_headroom(&self,job:&Arc)->bool{ + if self.engine.flights.is_empty()||self.needs_engine_drain(job){return false;} + if job.check_command_dependencies(job.progress.sent()).is_err(){return false;} + (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(())))) + ||(self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_)))) + } fn can_queue_behind(&self,job:&Arc)->bool{ if !self.allow_behind{return false;} if self.needs_engine_drain(job){return false;} @@ -235,7 +259,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, - engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false} @@ -509,7 +533,7 @@ def item(declaration): type Job = QueueBehindJob; type Flight = QueueBehindFlight; fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} - mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{15} } + mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{47} } #[allow(non_upper_case_globals)] mod kernel { pub mod uapi { @@ -518,9 +542,24 @@ def item(declaration): } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] + enum BarrierType { + Stamp = 0, + Hold = 1, + } + impl BarrierType { + const fn from_stamp_only(stamp_only: bool) -> Self { + if stamp_only { Self::Stamp } else { Self::Hold } + } + } + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + __WAIT_TARGET__ + __CROSS_ENGINE_BARRIER_TYPE__ + #[derive(Copy, Clone, Debug, PartialEq, Eq)] __RENDER_BARRIER_PLAN__ __PLAN_RENDER_BARRIERS__ impl QueueBehindHost { + __NEEDS_ENGINE_DRAIN__ + __BLOCKED_ON_SLOT_HEADROOM__ __CAN_QUEUE_BEHIND__ __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ @@ -666,8 +705,8 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; // Same-queue FS -> CDM barrier resolves render's fs_target; CDM -> TA resolves compute's target. - assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(Some(0x500))); - assert_eq!(p.cross_engine_wait(&r2_after_c1,0,command::COMPUTE),Ok(Some(0x700))); + assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(Some(WaitTarget{stamp:0x500,initbm:false}))); + assert_eq!(p.cross_engine_wait(&r2_after_c1,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x700,initbm:false}))); // No-barrier / independent-queue submits emit no cross-engine barrier. assert_eq!(p.cross_engine_wait(&c_nobarrier,0,command::RENDER),Ok(None)); assert_eq!(p.cross_engine_wait(&c_other_q,0,command::RENDER),Ok(None)); @@ -700,10 +739,47 @@ def item(declaration): slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; - assert_eq!(pm.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(0x200))); - assert_eq!(pm.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(0x300))); + assert_eq!(pm.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(pm.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); assert_eq!(pm.cross_engine_wait(&r_wait_missing,0,command::COMPUTE),Err(EAGAIN)); } + #[test]fn cross_engine_barrier_keeps_hold_when_producer_or_consumer_carries_initbm(){ + // Healthy same-VM non-InitBM handoffs downgrade to BarrierType::Stamp (type 0). + assert_eq!(cross_engine_barrier_type(false, false), BarrierType::Stamp); + // Any InitBM on either producer (including FS -> CDM) or consumer keeps BarrierType::Hold. + assert_eq!(cross_engine_barrier_type(true, false), BarrierType::Hold); + assert_eq!(cross_engine_barrier_type(false, true), BarrierType::Hold); + assert_eq!(cross_engine_barrier_type(true, true), BarrierType::Hold); + + // Verify wait_stamp_for_with / cross_engine_wait propagate producer flight.initbm. + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let r_initbm=mk(1,true,1,[None,None]); + let c_after_r=mk(2,false,1,[Some(1),None]); + let r_after_r=mk(3,true,2,[Some(1),None]); + let host=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{ + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,target:0, + cstamp:[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, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true}, + }; + let fs2c = host.cross_engine_wait(&c_after_r, 0, command::RENDER).unwrap().unwrap(); + assert_eq!(fs2c, WaitTarget { stamp: 0x900, initbm: true }); + assert_eq!(cross_engine_barrier_type(fs2c.initbm, false), BarrierType::Hold); + let r2r = host.wait_stamp_for(&r_after_r, command::RENDER, Some(1)).unwrap().unwrap(); + assert_eq!(r2r, WaitTarget { stamp: 0x900, initbm: true }); + assert_eq!(cross_engine_barrier_type(r2r.initbm, false), BarrierType::Hold); + } #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); let mut done=vec![]; @@ -778,8 +854,8 @@ def item(declaration): slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; - assert_eq!(p.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(0x200))); - assert_eq!(p.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(0x300))); + assert_eq!(p.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(p.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); // Active computes sum flight.computes: 16 batched computes saturates compute_flights(). assert!(p.can_queue_behind(&c4)); p.engine.flights[0].computes=16; @@ -818,9 +894,9 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; // Lookup into published multi-pass render flight resolves interior and tail passes. - assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(1)),Ok(Some(0x100))); - assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(2)),Ok(Some(0x200))); - assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(3)),Ok(Some(0x300))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(1)),Ok(Some(WaitTarget{stamp:0x100,initbm:false}))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(2)),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(3)),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(4)),Err(EAGAIN)); // Lookup against an in-progress same-batch flight resolves earlier pass before publish. let mut cur_fs=[0u32;16]; @@ -829,92 +905,275 @@ def item(declaration): job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[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(0x400))); - // Active renders sum flight.renders: 15 batched renders saturates render_flights(). + assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); + // Active renders sum flight.renders: 44 passes (4x11-pass postfx) still pipelines + // behind, while 47 batched renders saturates render_flights(). assert!(p.can_queue_behind(&next_r)); - p.engine.flights[0].renders=15; + p.engine.flights[0].renders=44; + assert!(p.can_queue_behind(&next_r)); + p.engine.flights[0].renders=47; assert!(!p.can_queue_behind(&next_r)); } + #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:2}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm,queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, + extra_orders:vec![],dependency:dep,resources:Resources, + }); + let r_live=mk(1,vm1.clone(),true,Ok(()),false,[None,None]); + let r_same=mk(2,vm1.clone(),true,Ok(()),false,[None,None]); + let r_cross_vm=mk(3,vm2.clone(),true,Ok(()),false,[None,None]); + let r_ext_fence=mk(4,vm1.clone(),true,Err(EAGAIN),false,[None,None]); + let c_ts_wait=mk(5,vm1.clone(),false,Ok(()),true,[Some(1),None]); + let mut p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[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, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true}, + }; + // Not blocked on slots when pass_available is true and render_flights has headroom. + assert!(!p.blocked_on_slot_headroom(&r_same)); + // Waiting on CPU timestamp publish (query_access) is NOT a slot-headroom block. + assert!(!p.can_queue_behind(&c_ts_wait)); + assert!(!p.blocked_on_slot_headroom(&c_ts_wait)); + // Render pass slot exhaustion IS a slot-headroom block for a ready same-VM render... + p.slots.pass_available=false; + assert!(p.blocked_on_slot_headroom(&r_same)); + // ...but NOT for cross-VM, external-fence, or InitBM/PB-unprimed jobs. + assert!(!p.blocked_on_slot_headroom(&r_cross_vm)); + assert!(!p.blocked_on_slot_headroom(&r_ext_fence)); + p.pools.can_pipeline=false; + assert!(!p.blocked_on_slot_headroom(&r_same)); + p.pools.can_pipeline=true; + p.engine.flights[0].initbm=true; + assert!(!p.blocked_on_slot_headroom(&r_same)); + p.engine.flights[0].initbm=false; + // Render flight cap (47) also counts as a slot-headroom block. + p.slots.pass_available=true; + p.engine.flights[0].renders=47; + assert!(p.blocked_on_slot_headroom(&r_same)); + + // End-to-end publish_checked: cross-VM drain leaves slot_wait=false; same-VM slot block sets slot_wait=true. + let v1=mk_vm(1); + let v2=mk_vm(2); + let mut fc=firmware(vec![job_on_vm(2,v2,true,0,Ok(()))],vec![]); + fc.engine.flights.push(super::Flight::new(job_on_vm(1,v1.clone(),true,0,Ok(())))); + fc.allow_behind=true; + let mut done=vec![]; + assert_eq!(fc.publish_checked(&mut done),Ok(())); + assert!(!fc.engine.slot_wait); + + let mut fs=firmware(vec![job_on_vm(2,v1.clone(),true,0,Ok(()))],vec![]); + fs.engine.flights.push(super::Flight::new(job_on_vm(1,v1,true,0,Ok(())))); + fs.allow_behind=true; + fs.block_render_behind=true; + assert_eq!(fs.publish_checked(&mut done),Ok(())); + assert!(fs.engine.slot_wait); + } #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; - // 1. Compute->FS-only wait (common texture-write-by-compute -> fragment-read): - // TA runs immediately (no TA compute barrier); FS gets fs_compute_barrier. + // 1. Cross-VM / InitBM / empty render pipe (`class_behind = false`): zero render barriers, + // compute->FS-only wait routes directly to fs_compute_barrier. assert_eq!( - plan_render_barriers(STAGED, false, true, 0, false, None, [None, Some(0x700)]), + plan_render_barriers(STAGED, false, true, 0, None, None, [None, Some(0x700)]), RenderBarrierPlan { early: false, + ta_prev_wait: false, ta_fs_wait: None, + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: Some(0x700), } ); - // 2. Same compute target on TA and FS: only TA waits (FS is ordered via own_barrier). + // 2. Independent multi-pass render (`fs_wait_render = None`, e.g. compress.bw array / + // render.shadow or already-retired predecessor): overlaps early while keeping + // TA(N-1)->TA(N) `prev_barrier` on the shared PB/UMA epoch, with ZERO FS->TA and + // ZERO FS->FS barriers (only own_barrier on FS). + for flags in [0u32, FRAG, STAGED] { + assert_eq!( + plan_render_barriers(flags, true, true, 0x200, None, None, [None, None]), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + } + // 3. Same compute target on TA and FS: only TA waits (FS is ordered via own_barrier); + // shared-PB TA->TA `prev_barrier` is kept and dependent FS wait on 0x200 emits fs_dep. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, None, [Some(0x700), Some(0x700)]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + None, + [Some(0x700), Some(0x700)], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: None, + fs_render_wait: Some(0x200), ta_compute_wait: Some(0x700), fs_compute_wait: None, } ); - // 3. Different compute targets on TA (0x600) vs FS (0x700): TA waits on 0x600, FS waits on 0x700. + // 4. Different compute targets on TA (0x600) vs FS (0x700) with no FS render dep: + // TA waits on prev_ta and 0x600, FS waits on 0x700, zero FS->FS render barriers. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, None, [Some(0x600), Some(0x700)]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + None, + None, + [Some(0x600), Some(0x700)], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: None, + fs_render_wait: None, ta_compute_wait: Some(0x600), fs_compute_wait: Some(0x700), } ); - // 4. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200): - // overlaps TA with 0x200's FS while waiting on 0x100's FS via ta_fs_barrier. + // 5. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200) + // while FS depends on 0x200: TA waits on prev_ta and 0x100, FS waits on 0x200. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + Some(0x100), + [None, None], + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: Some(0x200), + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 6. Staged render where TA and FS wait on the same older in-flight FS (0x100): + // TA still waits on prev_ta for the shared PB, and TA wait dominates FS wait via + // own_barrier so fs_render_wait is omitted. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, Some(0x100), [None, None]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x100), + Some(0x100), + [None, None], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: Some(0x100), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } ); - // 5. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): - // no early overlap; prev_barrier waits on 0x200 directly. + // 7. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): + // no early overlap; TA waits on 0x200 directly (which dominates prev_ta) and omits both + // prev_barrier and fs_dep. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, Some(0x200), [None, None]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + Some(0x200), + [None, None], + ), RenderBarrierPlan { early: false, - ta_fs_wait: None, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } ); - // 6. Legacy FRAGMENT_BARRIERS and plain render remain unchanged. + // 8. Dependent FRAGMENT_BARRIERS render (e.g. render.postfx): TA runs early with + // shared-PB prev_barrier; FS waits on exact fs_wait_render (0x200). assert_eq!( - plan_render_barriers(FRAG, true, true, 0x200, false, None, [Some(0x700), Some(0x700)]), + plan_render_barriers( + FRAG, + true, + true, + 0x200, + Some(0x200), + None, + [Some(0x700), Some(0x700)], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: None, + fs_render_wait: Some(0x200), ta_compute_wait: Some(0x700), fs_compute_wait: None, } ); + // 9. Legacy dependent render (flags = 0, fs_wait_render = Some(0x200)): + // TA waits on 0x200 (FS->TA, dominating prev_ta); prev_barrier and fs_dep omitted. assert_eq!( - plan_render_barriers(0, true, true, 0x200, false, None, [None, None]), + plan_render_barriers(0, true, true, 0x200, Some(0x200), None, [None, None]), RenderBarrierPlan { early: false, - ta_fs_wait: None, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } ); + // 10. Legacy dependent render waiting on an older FS (0x100 != prev_fs 0x200): + // TA still needs prev_barrier on the shared PB in addition to ta_fs_wait(0x100). assert_eq!( - plan_render_barriers(0, true, true, 0x200, true, None, [None, None]), + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, [None, None]), RenderBarrierPlan { - early: true, - ta_fs_wait: None, + early: false, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 11. Conservative `early_tiling = false` serializes TA behind prev_fs even when + // fs_wait_render is None, dominating prev_ta and omitting fs_dep. + assert_eq!( + plan_render_barriers(FRAG, true, false, 0x200, None, None, [None, None]), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } @@ -1225,6 +1484,8 @@ def item(declaration): doomed: bool, recovery_suspect: bool, recovery_started_ns: u64, + gate_passed_ns: Option, + unsettled_polls: u32, } struct RecEngine { flights: Vec, ta_target: u32 } struct RecState { last_retired: recovery::logic::RetiredStamps } @@ -1254,6 +1515,8 @@ def item(declaration): doomed: false, recovery_suspect: false, recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, }], ta_target: 0, }, @@ -1296,6 +1559,8 @@ def item(declaration): doomed: false, recovery_suspect: false, recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, }], ta_target: 0x300, }, @@ -1356,12 +1621,15 @@ def item(declaration): '__PUBLISH__': 'pub(crate) fn publish(&mut self', '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', '__NEEDS_ENGINE_DRAIN__': 'fn needs_engine_drain(', + '__BLOCKED_ON_SLOT_HEADROOM__': 'fn blocked_on_slot_headroom(', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', + '__WAIT_TARGET__': 'struct WaitTarget {', + '__CROSS_ENGINE_BARRIER_TYPE__': 'const fn cross_engine_barrier_type(', '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): @@ -1378,7 +1646,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 60, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 61, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production publication wrapper, selection, error isolation and descriptor-error containment branch; wire encoder, descriptor failure injection and transport replaced by CPU recorders.', 'source_sha256': sha(production), }, 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 9806d05718bf2..6098ef1a133d5 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -176,6 +176,14 @@ def module(text, name): __RENDER_BURST__ } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} + pub mod engine { + use core::sync::atomic::{AtomicU32, Ordering}; + pub static WMB_CALLS: AtomicU32 = AtomicU32::new(0); + pub fn wmb() { + WMB_CALLS.fetch_add(1, Ordering::SeqCst); + core::sync::atomic::fence(Ordering::SeqCst); + } + } // Arenas here have the two base units. pub mod params {pub fn compute_units()->usize{2}pub fn pb_heap_blocks()->u32{2048}pub fn pb_posted_blocks(heap:u32)->u32{heap}} pub struct Events{pub grow:crate::KVec<[u32;18]>} @@ -193,6 +201,7 @@ def module(text, name): Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS]}} } 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} #[test]fn render_reuse_clears_only_previous_write_spans(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); s.claim_pass(&arena.render,0).unwrap(); @@ -564,7 +573,9 @@ def module(text, name): assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); } - #[test]fn eight_render_passes_and_sixteen_compute_units_are_disjoint_in_mesa_hole(){ + #[test]fn forty_eight_render_passes_and_eighteen_compute_units_are_disjoint_in_mesa_hole(){ + assert_eq!(g16::hw::sizes::RENDER_SLOTS, 48); + assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 18); 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 { @@ -575,6 +586,7 @@ def module(text, name): g16::slots::ComputeSlot::new(&mut o,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 va=pass.refs().scene_list; @@ -582,6 +594,18 @@ def module(text, name): assert!(!scene_lists.contains(&va),"each pass slot must own a distinct scene_list"); scene_lists.push(va); } + // Every demand-grown extension tier stays strictly within MAX_CLIENT (512) per batch. + 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(); + } + let tier_maps = count_client(&ot); + assert!( + tier_maps <= g16::hw::sizes::MAX_CLIENT, + "tier {start}..{end} client maps {tier_maps} > MAX_CLIENT" + ); + } let mut aliases=Vec::new(); for a in &o.objects { if let Some(g)=a.gva { @@ -794,7 +818,7 @@ def module(text, name): assert_eq!(arena.render.passes[0].scene.fills.lock().unwrap().len(),2); } - #[test]fn pipelined_render_pass_slots_keep_fifteen_in_flight(){ + #[test]fn pipelined_render_pass_slots_keep_forty_seven_in_flight(){ 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 { @@ -816,23 +840,31 @@ def module(text, name): let a=vm(1); let b=vm(2); let mut live:Vec=Vec::new(); - // Publish 15 concurrent passes in flight (slots 0..15). - for k in 0..15usize { + // Publish 47 concurrent passes in flight (slots 0..47), covering 4x11-pass and 6x7-pass + // multi-pass bursts and exercising 64-bit pass_mask bits above bit 31. + for k in 0..47usize { let mut c=Claims::new(); - c.pass[0]=k as u32;c.pass_mask=1< slot 0 is displaced and reusable while 13 others remain in flight. + assert_eq!(s.render_published(),47); + assert!(s.pass_available(48)); // slot 47 is still fresh + assert!(!s.pass_available(47)); + // Retire 0 and 1 -> slot 0 is displaced and reusable while 45 others remain in flight. s.retire(&mut live[0]).unwrap(); - assert!(!s.pass_available(15)); // slot 0 not displaced yet + assert!(!s.pass_available(47)); // slot 0 not displaced yet s.retire(&mut live[1]).unwrap(); - assert!(s.pass_available(15)); // slot 0 displaced by slot 1! + assert!(s.pass_available(47)); // slot 0 displaced by slot 1! + // Claim and publish bit 47 (slot 47) explicitly to prove zero 64-bit mask overflow. + let mut c47=Claims::new(); + c47.pass[0]=47;c47.pass_count=1;c47.pass_mask=1u64<<47; + s.claim_pass_for(&arena,47,Some(a.id)).unwrap(); + s.hold_vm(&c47,&a).unwrap(); + s.publish(&mut c47).unwrap(); // Clean same-VM reuse of displaced slot 0 does not need full work write. s.claim_pass_for(&arena,0,Some(a.id)).unwrap(); assert!(!s.render_needs_full_work(0)); @@ -845,6 +877,7 @@ def module(text, name): for c in live.iter_mut().skip(2) { s.retire(c).unwrap(); } + s.retire(&mut c47).unwrap(); assert_eq!(s.render_published(),0); } @@ -864,7 +897,7 @@ def module(text, name): s.retire(&mut c0).unwrap(); s.stage_displaced_pass_scrubs(); assert!(!s.scrubbing_active()); - assert!(!s.take_staged_scrubs().run()); + assert!(!drain_scrubs(s.take_staged_scrubs())); // Publish and retire slot 1: displaces slot 0, staging slot 0 for off-lock scrub. let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); @@ -877,7 +910,7 @@ def module(text, name): assert_eq!(s.pick_pass_in(&prep,&geo,0),None); assert_eq!(s.claim_pass_in(&prep,0,Some(a.id),0x4000),Err(EBUSY)); let batch=s.take_staged_scrubs(); - assert!(batch.run()); + assert!(drain_scrubs(batch)); assert!(!s.scrubbing_active()); assert!(render.passes[0].tilemap.snapshot()[..0x4000].iter().all(|&b|b==0)); assert!(render.passes[0].its.snapshot()[..32].iter().all(|&b|b==0)); @@ -916,7 +949,7 @@ def module(text, name): // Failed off-lock scrub preserves tilemap_dirty and falls back synchronously. s.stage_displaced_pass_scrubs(); render.passes[0].tilemap.fail_fill.store(true,std::sync::atomic::Ordering::Relaxed); - assert!(!s.take_staged_scrubs().run()); + assert!(!drain_scrubs(s.take_staged_scrubs())); assert_eq!(render.tilemap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0x2000); let fills_before=render.passes[0].tilemap.fills.lock().unwrap().len(); s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); @@ -929,7 +962,7 @@ def module(text, name): s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); - let _=s.take_staged_scrubs().run(); + let _=drain_scrubs(s.take_staged_scrubs()); s.invalidate_scrub(); s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); assert!(s.render_needs_full_work(0)); @@ -939,7 +972,7 @@ def module(text, name): s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); - let _=s.take_staged_scrubs().run(); + let _=drain_scrubs(s.take_staged_scrubs()); s.claim_pass_in(&prep,0,Some(b.id),0x2000).unwrap(); assert!(s.render_needs_full_work(0)); } @@ -967,17 +1000,17 @@ def module(text, name): assert!(s.pass_available(2)); assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); // Disallowed staging (fail-stop / frozen) stages nothing and clears pending flag. - assert!(!s.stage_and_take_scrubs(false).run()); + assert!(!drain_scrubs(s.stage_and_take_scrubs(false))); assert!(!s.scrubbing_active()); // Allowed staging after publication stages idle displaced slot 0 and scrubs it off-lock. s.note_render_retired(); let batch=s.stage_and_take_scrubs(true); assert!(s.scrubbing_active()); - assert!(!batch.run()); + assert!(!drain_scrubs(batch)); assert!(!s.scrubbing_active()); assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&b|b==0)); // Calling stage_and_take_scrubs again without a new render retirement is a no-op. - assert!(!s.stage_and_take_scrubs(true).run()); + assert!(!drain_scrubs(s.stage_and_take_scrubs(true))); assert!(!s.scrubbing_active()); } #[test]fn multi_unit_compute_horizon_claims_publish_retire_and_release(){ @@ -1032,23 +1065,23 @@ def module(text, name): },0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; let a=vm(1); - // Wrapped submission order [14, 15, 0]: retiring in order leaves slot 0 as last_retired - // while slots 14 and 15 are displaced and reusable immediately. - let order=[14usize,15,0]; + // 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. + let order=[46usize,47,0]; let mut c=Claims::new(); for (i,&k) in order.iter().enumerate() { s.claim_pass_in(&prep,k,Some(a.id),0x1000).unwrap(); c.pass[i]=k as u32; c.pass_count+=1; - c.pass_mask|=1<= 1) and expand immediately. + // A 2-pass compositor or shallow depth-2 overlap grows ONLY to Tier 0 (8 slots), + // never allocating Tier 1 or Tier 2 until live concurrency actually requires them. + let mut last = 0u64; + let mut burst = 0u32; + assert_eq!( + target_render_slots(&mut last, &mut burst, 100_000_000, 2, 0, false, BASE_RENDER_SLOTS), + tier0_end + ); + // Back-to-back 2-pass frames with 2 active passes (need = 2 + 2 + 1 = 5 <= 8) stay on Tier 0. + assert_eq!( + target_render_slots(&mut last, &mut burst, 108_333_333, 2, 2, false, tier0_end), + tier0_end + ); + + // Heavy multi-ms pipelined renders (5 ms and 16.6 ms apart) overlap an already-active + // pass and grow progressively: Tier 0 -> Tier 1 -> Tier 2 only as depth climbs. let mut last = 0u64; let mut burst = 0u32; - assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0, false)); - assert!(should_expand_render_ext(&mut last, &mut burst, 6_000_000, 1, 1, false)); - assert!(should_expand_render_ext(&mut last, &mut burst, 22_600_000, 1, 1, false)); + let mut backed = BASE_RENDER_SLOTS; + backed = target_render_slots(&mut last, &mut burst, 1_000_000, 1, 0, false, backed); + assert_eq!(backed, BASE_RENDER_SLOTS); + backed = target_render_slots(&mut last, &mut burst, 6_000_000, 1, 1, false, backed); + assert_eq!(backed, tier0_end); + backed = target_render_slots(&mut last, &mut burst, 22_600_000, 1, 6, false, backed); + assert_eq!(backed, tier0_end); // 6 + 1 + 1 == 8 fits in Tier 0 + backed = target_render_slots(&mut last, &mut burst, 39_200_000, 1, 7, false, backed); + assert_eq!(backed, tier1_end); // 7 + 1 + 1 == 9 grows to Tier 1 (18 slots) + backed = target_render_slots(&mut last, &mut burst, 55_800_000, 1, 16, false, backed); + assert_eq!(backed, tier1_end); // 16 + 1 + 1 == 18 fits in Tier 1 + backed = target_render_slots(&mut last, &mut burst, 72_400_000, 1, 17, false, backed); + assert_eq!(backed, tier2_end); // 17 + 1 + 1 == 19 grows to Tier 2 (32 slots) + backed = target_render_slots(&mut last, &mut burst, 89_000_000, 1, 30, false, backed); + assert_eq!(backed, tier2_end); // 30 + 1 + 1 == 32 fits in Tier 2 + backed = target_render_slots(&mut last, &mut burst, 105_600_000, 1, 31, false, backed); + assert_eq!(backed, full_end); // 31 + 1 + 1 == 33 grows to Tier 3 (48 slots) - // Sub-2 ms back-to-back single-pass bursts still expand after 3 consecutive gaps. + // Sub-2 ms back-to-back single-pass bursts grow only to Tier 0 after 3 consecutive gaps. let mut last = 0u64; let mut burst = 0u32; - assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0, false)); - assert!(!should_expand_render_ext(&mut last, &mut burst, 2_000_000, 1, 0, false)); - assert!(!should_expand_render_ext(&mut last, &mut burst, 3_000_000, 1, 0, false)); - assert!(should_expand_render_ext(&mut last, &mut burst, 4_000_000, 1, 0, false)); + assert_eq!(target_render_slots(&mut last, &mut burst, 1_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 2_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 3_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 4_000_000, 1, 0, false, BASE_RENDER_SLOTS), tier0_end); assert_eq!(burst, 3); + assert_eq!(target_render_slots(&mut last, &mut burst, 5_000_000, 1, 0, false, tier0_end), tier0_end); - // A single multi-pass SUBMIT with >= BASE_RENDER_SLOTS (2) renders expands immediately. + // Multi-pass pipelined workloads stop at Tier 2 (32 slots) for 20-31 pass demand and + // grow into Tier 3 (48 slots) only when live demand exceeds 32 slots: + // 11-pass render.postfx: depth 2 (23) -> Tier 2, depth 3 (34) -> Tier 3; + // 7-pass compress.bw array: depth 3 (22) -> Tier 2, depth 5 (36) -> Tier 3; + // 4-pass render.shadow: depth 5 (21) -> Tier 2, depth 8 (33) -> Tier 3. let mut last = 0u64; let mut burst = 0u32; - assert!(should_expand_render_ext(&mut last, &mut burst, 100_000_000, 2, 0, false)); + assert_eq!(target_render_slots(&mut last, &mut burst, 10_000_000, 11, 0, false, BASE_RENDER_SLOTS), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 15_000_000, 11, 11, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 18_000_000, 11, 22, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 20_000_000, 7, 7, false, tier1_end), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 25_000_000, 7, 14, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 28_000_000, 7, 28, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 30_000_000, 4, 12, false, tier1_end), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 35_000_000, 4, 16, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 38_000_000, 4, 28, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 40_000_000, 8, 0, false, BASE_RENDER_SLOTS), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 50_000_000, 20, 0, false, BASE_RENDER_SLOTS), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 60_000_000, 32, 0, false, BASE_RENDER_SLOTS), full_end); + + // 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(); + 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); + let mut o_ext = Objects::new(); + g16::slots::PassSlot::new(&mut o_ext, 2, 1).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); + // 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); } #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ @@ -1162,7 +1265,7 @@ def module(text, name): } #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ - use crate::g16::resources::should_expand_render_ext; + 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 { @@ -1186,9 +1289,12 @@ def module(text, name): assert!(s.base_render_quarantined()); assert!(s.render_exhausted_within(2)); assert!(!s.render_exhausted_within(4)); - // Fresh single-pass VM expands RenderExtArena immediately because a base pass slot is quarantined. + // Fresh single-pass VM expands Tier 0 RenderExtArena immediately because a base pass slot is quarantined. let mut last=0u64;let mut burst=0u32; - assert!(should_expand_render_ext(&mut last,&mut burst,10_000_000,1,0,s.base_render_quarantined())); + assert_eq!( + target_render_slots(&mut last,&mut burst,10_000_000,1,0,s.base_render_quarantined(),BASE_RENDER_SLOTS), + EXT_RENDER_TIERS[0].1 + ); // Expanded VM picks and retires pass slot 2, displacing base pass slot 0 back to reusable. let k=s.pick_pass_in(&prep,&geo,0).unwrap(); assert_eq!(k,2); @@ -1198,8 +1304,74 @@ def module(text, name): assert!(!s.render_exhausted_within(2)); } + #[test]fn async_scrub_queue_and_recovery_generation_guard(){ + 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 a=vm(1); + let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; + // Prime and displace slot 0. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); + render.set_dirty(0,0x1000,0x2000).unwrap(); + render.passes[0].tilemap.fill(0,0x66,0x2000).unwrap(); + s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); + s.retire(&mut c1).unwrap(); + + // Hand staged scrub off via ScrubQueue; waiter is woken on completion and woke flag is set. + s.stage_displaced_pass_scrubs(); + let batch=s.take_staged_scrubs(); + assert!(!batch.is_empty()); + let mut q=ScrubQueue::new(); + assert!(q.push_batch(batch)); + assert!(s.scrubbing_active()); + assert_eq!(s.pick_pass_in(&prep,&geo,0),None); + let mut item=q.pop().expect("queued scrub"); + assert!(q.pop().is_none()); + let wmb_before=g16::engine::WMB_CALLS.load(std::sync::atomic::Ordering::SeqCst); + assert!(item.run_one()); + assert!(g16::engine::WMB_CALLS.load(std::sync::atomic::Ordering::SeqCst)>wmb_before); + assert!(!s.scrubbing_active()); + assert!(s.take_scrub_woke()); + assert!(!s.take_scrub_woke()); + assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(!s.render_needs_full_work(0)); + + // Re-displace slot 0, stage scrub, then simulate recovery invalidate_scrub() BEFORE + // the async scrub runs: it must clear scrubbing without marking clean, so next claim + // performs a full scrub. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + assert!(q.push_batch(s.take_staged_scrubs())); + assert!(s.scrubbing_active()); + s.invalidate_scrub(); + let mut stale=q.pop().expect("stale scrub"); + assert!(!stale.run_one()); + assert!(!s.scrubbing_active()); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(s.render_needs_full_work(0)); + } + } ''' +poll_source = (production/'poll.rs').read_text() +mod_source = (production/'mod.rs').read_text() +sleep_source = (production/'sleep.rs').read_text() +assert 'scrubs.run()' not in poll_source, 'poll.rs must hand scrubs off asynchronously via enqueue_scrubs' +assert 'while let Some(mut item) = self.scrub_queue.lock().pop()' not in poll_source, 'run_scrubs must drop scrub_queue spinlock before run_one()' +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' budget=(production/'budget.rs').read_text() budget=budget.replace('new_condvar, new_mutex,','').replace('#[pin_data]','').replace(' #[pin]\n','') constructor=item(budget,'pub(crate) fn new()') @@ -1226,10 +1398,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() -render_burst_lines = '\n'.join( - 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 should_expand_compute_ext(') + '\npub(crate) ' + item(resources_source, 'fn should_expand_render_ext(') +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 = ( + resources_source[ext_tiers_start:ext_tiers_end] + + '\n' + + '\n'.join( + 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 should_expand_compute_ext(') + + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') +) source = source.replace('__CMD_CLASSES__',item(graph_source,'pub(crate) const fn cmd_fw(')+'\n'+item(graph_source,'pub(crate) const fn cmd_shared(')).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) 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 {')) @@ -1247,7 +1427,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': 32, + 'result': 'pass', 'tests': 33, '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', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py index 26afcd4f09ced..eb884621a6808 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py @@ -26,7 +26,7 @@ def function(text, name): #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); const EINVAL:Error=Error(-22);const EAGAIN:Error=Error(-11);type Result = std::result::Result; #[path="__LOGIC__"]mod logic; -use logic::Retirement; +use logic::{Retirement, ABORT_GRACE_NS}; mod encode { __STAMP_SEED__ __STAMP__ } struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell} impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0)}}} @@ -47,7 +47,7 @@ def function(text, name): struct Resources{compute:Vec,passes:Vec,pools:Pools} impl Resources{fn compute(&self)->Result<&Self>{Ok(self)}fn render(&self)->Result<&Self>{Ok(self)}fn compute_unit(&self,k:usize)->Result<&CUnit>{self.compute.get(k).ok_or(EINVAL)}fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.get(k).ok_or(EINVAL)}fn pb_retired(&self,k:usize)->Result{self.pools.retired(k)}fn pb_retired_at(&self,k:usize,target:u64)->Result{self.pools.retired_at(k,target)}} struct Claims{slot:[u32;16],slot_count:u32,pass:[u32;1]} -struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} +struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} fn stamp_reached(observed:u32,own:u32,tail:u32)->bool{logic::stamp_reached(observed,own,tail)} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} @@ -58,7 +58,8 @@ def function(text, name): struct Pools{full:bool,completed:u64} impl Pools{fn retired(&self,_k:usize)->Result{Ok(self.full)}fn retired_at(&self,_k:usize,target:u64)->Result{Ok(self.full && target!=0 && self.completed>=target)}} struct Firmware{graph:Graph,engine:Engine,slots:Slots,pools:Pools,queue_passed:bool} -fn rmb(){}fn now_ns()->u64{100_000_000} +thread_local!{static CLOCK:Cell = const { Cell::new(100_000_000) };} +fn rmb(){}fn now_ns()->u64{CLOCK.with(|c| c.get())} impl Firmware{ fn queue_receipt(&self,_ch:Channel,_state:&Object,_info:&Object,_head:u32,_rec:u32)->Result{Ok(self.queue_passed)} fn queue_passed(&self,_ch:Channel,_state:&Object,_info:&Object,_f:&Flight)->Result{Ok(self.queue_passed)} @@ -76,7 +77,7 @@ def function(text, name): let mut f=Firmware{ graph:Graph{compute:CGraph{fw_stamp:Object::default(),qstate:Object::default(),qinfo:Object::default(),notifier:Object::default()}, render:RGraph{fw_stamp:Default::default(),qstate:Default::default(),qinfo:Default::default(),notifier:Object::default()}}, - engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true,completed:2}}},claims:Claims{slot:[0;16],slot_count:u32::from(!render),pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,doomed:false}],target,ta_target:target,fs_target:target,retired_ticks:[0;4]}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true,completed:2}}},claims:Claims{slot:[0;16],slot_count:u32::from(!render),pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target,ta_target:target,fs_target:target,retired_ticks:[0;4]}, slots:Slots{scrub:Scrub{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}]}}, pools:Pools{full:true,completed:2},queue_passed:true, }; @@ -292,6 +293,71 @@ def function(text, name): assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(None)); assert_eq!(fmix.graph.compute.fw_stamp.reads.get(),1); } +#[test]fn innocent_suspect_flight_does_not_false_abort_after_recovery_grace(){ + let mut f=firmware(true,15); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + // Long after recovery started (>20 ms), flight finishes its stage/queue gates while scene + // timestamps are briefly unsettled on the first poll. + CLOCK.with(|c| c.set(100_000_000)); + f.engine.flights[0].job.resources.passes[0].scene.set(0x628,0); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + assert_eq!(f.engine.flights[0].gate_passed_ns,Some(100_000_000)); + assert_eq!(f.engine.flights[0].unsettled_polls,1); + // Receipts settle before ABORT_GRACE_NS from gate_passed_ns -> full normal retirement. + CLOCK.with(|c| c.set(100_500_000)); + f.engine.flights[0].job.resources.passes[0].scene.set(0x628,103); + assert_eq!(f.retired(),Ok(Retirement::Full)); + assert!(!f.engine.flights[0].doomed); +} +#[test]fn truly_aborted_suspect_requires_two_polls_and_grace_from_gate_passed(){ + let mut f=firmware(false,22); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + f.engine.flights[0].job.resources.compute[0].its.set(8,0); + CLOCK.with(|c| c.set(100_000_000)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + // Second poll before ABORT_GRACE_NS stays pending. + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS - 1)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + // Once both >=2 polls and >=ABORT_GRACE_NS elapsed from gate_passed_ns, abort and doom. + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS)); + assert_eq!(f.retired(),Ok(Retirement::Aborted)); + assert!(f.engine.flights[0].doomed); +} +#[test]fn same_tick_stage_timestamps_retire_full_while_zero_or_reversed_stay_pending(){ + // 24 MHz (41.67 ns) stage timestamps can legitimately record end == start on tiny draws + // or dispatches; accept end >= start while still rejecting 0 or reversed intervals. + let mut r=firmware(true,50); + r.engine.flights[0].job.resources.passes[0].scene.set(0x600,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x620,200); + r.engine.flights[0].job.resources.passes[0].scene.set(0x628,200); + assert_eq!(r.retired(),Ok(Retirement::Full)); + assert_eq!(r.engine.retired_ticks,[100,100,200,200]); + + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,0); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,99); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x628,199); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + + let mut c=firmware(false,51); + c.engine.flights[0].job.resources.compute[0].its.set(0,300); + c.engine.flights[0].job.resources.compute[0].its.set(8,300); + assert_eq!(c.retired(),Ok(Retirement::Full)); + assert_eq!(c.engine.retired_ticks,[300,300,0,0]); + + c.engine.flights[0].job.resources.compute[0].its.set(8,0); + assert_eq!(c.retired(),Ok(Retirement::Pending)); + c.engine.flights[0].job.resources.compute[0].its.set(8,299); + assert_eq!(c.retired(),Ok(Retirement::Pending)); +} '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index 205016c1feb7c..38eb620a86d78 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -50,9 +50,15 @@ pub regions: Vec, pub lock_calls: std::cell::Cell, pub read_calls: std::cell::Cell, + pub last_read_len: std::cell::Cell, } pub struct VmReadGuard<'a>(&'a Vm); impl VmReadGuard<'_> { + pub fn covers_range(&mut self, address: u64, size: u64, _read: bool, _write: bool) -> bool { + address + .checked_add(size) + .is_some_and(|end| self.0.contains(address, end)) + } pub fn read_user(&mut self, va: u64, out: &mut [u8]) -> Result { self.0.read_user(va, out) } @@ -71,6 +77,7 @@ } pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { self.read_calls.set(self.read_calls.get() + 1); + self.last_read_len.set(out.len()); let end = va.checked_add(out.len() as u64).ok_or(EFAULT)?; for r in &self.regions { if r.readable && va >= r.base && end <= r.base + r.bytes.len() as u64 { @@ -94,7 +101,13 @@ } pub fn reset_cover_calls() { COVER_CALLS.with(|c| c.set(0)); } pub fn cover_calls() -> usize { COVER_CALLS.with(Cell::get) } - pub fn cover(vm: &mmu::Vm, start: u64, end: u64, _read: bool, _write: bool) -> Result { + pub fn cover_locked( + guard: &mut mmu::VmReadGuard<'_>, + start: u64, + end: u64, + read: bool, + write: bool, + ) -> Result { COVER_CALLS.with(|c| c.set(c.get() + 1)); if end <= start || start < 0x4000 || end > (1u64 << 42) - 0x8000 { return Err(EINVAL); @@ -103,7 +116,7 @@ || start < 0x1000010000 && end > 0x1000000000 { return Err(EACCES); } - if vm.contains(start, end) { Ok(()) } else { Err(EFAULT) } + if guard.covers_range(start, end - start, read, write) { Ok(()) } else { Err(EFAULT) } } } #[path = "PRODUCTION_SOURCE"] pub mod gate; @@ -273,13 +286,17 @@ assert_eq!(result, Err(kernel::prelude::ERESTARTSYS)); assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); } +fn vdm_check(vm: &mmu::Vm, vas: &[u64]) -> kernel::prelude::Result { + let mut guard = vm.read_lock()?; + g16::gate::vdm_batch_locked(&mut guard, vas) +} #[test] fn vdm_m4_root_barrier() { for word in [0x21000960, 0x21000968] { - assert!(g16::gate::vdm_batch(&vm_for(&[word]), &[BASE]).is_ok()); + assert!(vdm_check(&vm_for(&[word]), &[BASE]).is_ok()); } for word in [0, 0x21000964, 0x40000000] { - assert!(g16::gate::vdm_batch(&vm_for(&[word]), &[BASE]).is_err()); + assert!(vdm_check(&vm_for(&[word]), &[BASE]).is_err()); } } #[test] @@ -295,20 +312,20 @@ vm.region(BASE, page0); vm.region(BASE + 0x4000, page1); - // Empty batch acquires no VM lock. - assert!(g16::gate::vdm_batch(&vm, &[]).is_ok()); - assert_eq!(vm.lock_calls.get(), 0); + // Empty batch performs no reads. + assert!(vdm_check(&vm, &[]).is_ok()); assert_eq!(vm.read_calls.get(), 0); // Four adjacent VDM roots within 256 bytes share one lock and one read_user. - assert!(g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x20, BASE + 0x40, BASE + 0x80]).is_ok()); + vm.lock_calls.set(0); + assert!(vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x40, BASE + 0x80]).is_ok()); assert_eq!(vm.lock_calls.get(), 1); assert_eq!(vm.read_calls.get(), 1); // A bad root inside the same cached 256-byte window is still rejected. vm.regions[0].bytes[0x80..0x84].copy_from_slice(&0xdeadbeefu32.to_le_bytes()); assert_eq!( - g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x20, BASE + 0x80]), + vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x80]), Err(kernel::prelude::EINVAL) ); vm.regions[0].bytes[0x80..0x84].copy_from_slice(&root); @@ -316,10 +333,56 @@ // Cross-page and end-of-page roots share one lock and never over-read past UAT_PGSZ. vm.lock_calls.set(0); vm.read_calls.set(0); - assert!(g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); + assert!(vdm_check(&vm, &[BASE, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); assert_eq!(vm.lock_calls.get(), 1); assert_eq!(vm.read_calls.get(), 3); } +#[test] +fn cdm_batches_vm_read_lock_and_releases_on_resched() { + let target = 0x600000000u64; + let mut root = Vec::new(); + root.extend(launch(0, USC, 0)); + root.extend(launch(1, USC + 0x80, 0x400000000)); + root.extend(launch(2, USC + 0x100, 0x400000040)); + root.extend([0x20000000 | (target >> 32) as u32, target as u32]); + let mut vm = vm_for(&root); + let mut linked_words = launch(0, USC + 0x4000, 0); + linked_words.push(0x40000000); + let mut linked = bytes(&linked_words); + linked.resize(0x4000, 0); + vm.region(target, linked); + vm.region(USC + 0x4000, vec![0; 0x4000]); + + // Multi-launch mode 0/1/2 + linked segment acquires the VM read lock only once. + assert!(g16::gate::cdm(&vm, USC, BASE, BASE + root.len() as u64 * 4).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + + // Streams longer than CDM_RESCHED_RECORDS (1024) drop and re-acquire the lock on each resched. + let mut long = vec![0x60000160; 2500]; + long.push(0x40000000); + let long_vm = vm_for(&long); + let sched_before = kernel::task::scheduled(); + assert!(g16::gate::cdm(&long_vm, USC, BASE, BASE + long.len() as u64 * 4).is_ok()); + let sched_delta = kernel::task::scheduled() - sched_before; + assert_eq!(sched_delta, 3); + assert_eq!(long_vm.lock_calls.get(), sched_delta); +} +#[test] +fn single_vdm_and_short_cdm_root_minimize_poc_read_len() { + let vm = vm_for(&[0x21000960]); + assert!(vdm_check(&vm, &[BASE]).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(vm.read_calls.get(), 1); + assert_eq!(vm.last_read_len.get(), 4); + + let mut words = launch(0, USC, 0); + words.push(0x40000000); + let cdm_vm = vm_for(&words); + assert!(g16::gate::cdm(&cdm_vm, USC, BASE, BASE + words.len() as u64 * 4).is_ok()); + assert_eq!(cdm_vm.lock_calls.get(), 1); + assert_eq!(cdm_vm.read_calls.get(), 1); + assert_eq!(cdm_vm.last_read_len.get(), words.len() * 4); +} ''' with tempfile.TemporaryDirectory(prefix='m4-rust-gate-') as directory: @@ -333,7 +396,7 @@ (OUT / 'stream-gate-host.log').write_text(result.stdout + result.stderr) (OUT / 'stream-gate-host.json').write_text(json.dumps({ 'source': str(SOURCE), 'sha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result': 'pass', 'test_groups': 10, + 'result': 'pass', 'test_groups': 12, 'mesa_sources': ['src/asahi/genxml/agx3_cmdstream.h', 'src/asahi/lib/agx3_cdm_decode_core.c', 'src/asahi/lib/agx_vdm_barrier_core.c'], 'limitations': 'Host VM model validates parser, addresses, cycles and interruption; hardware and kernel cache behavior require target tests.'