diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 0e10eb3d42039..b5c34c9851d28 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -1773,21 +1773,15 @@ impl File { return Err(EINVAL); } - // REALTIME stays reserved. HIGH needs CAP_SYS_NICE or DRM master, as amdgpu and - // panthor require for raised queue priority; EACCES lets userspace fall back to MEDIUM. + // REALTIME stays reserved. HIGH needs CAP_SYS_NICE, DRM master on this device, or active + // KMS master on a display card (split KMS/render compositors open the render node); EACCES + // lets unprivileged userspace fall back to MEDIUM. if data.priority == uapi::drm_asahi_priority_DRM_ASAHI_PRIORITY_REALTIME { cls_pr_debug!(Errors, "queue_create: Invalid priority\n"); return Err(EINVAL); } - // Keep support tied to a backend and admitted profile. G13/G14 and - // unqualified M3 profiles retain their previous rejection. - let high_supported = reg_data.gpu.as_any().is::(); - #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] - let high_supported = high_supported || reg_data.gpu.as_any() - .downcast_ref::() - .is_some_and(|gpu| gpu.supports_high_priority()); if data.priority == uapi::drm_asahi_priority_DRM_ASAHI_PRIORITY_HIGH - && !high_supported + && !reg_data.gpu.supports_high_priority() { cls_pr_debug!( Errors, @@ -1799,10 +1793,11 @@ impl File { // SAFETY: capable() reads the current ioctl task's credentials. && !unsafe { bindings::capable(bindings::CAP_SYS_NICE as i32) } && !file.is_current_master() + && !drm::file::current_is_kms_master() { cls_pr_debug!( Errors, - "queue_create: HIGH priority needs CAP_SYS_NICE or DRM master\n" + "queue_create: HIGH priority needs CAP_SYS_NICE, DRM master, or KMS master\n" ); return Err(EACCES); } diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 8bf0b6c1bacf1..ba4b0a5e83616 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -960,7 +960,20 @@ impl Runtime { let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; if !self.healthy() { return Err(EIO); } if !state.accepting { return Err(ENODEV); } - state.pending.push((packet, 0), GFP_KERNEL)?; + let start = usize::from( + state.pending.first().is_some_and(|(_, idx)| *idx != 0) + || state.waiting_bind.is_some(), + ); + let at = start + + state.pending[start..] + .iter() + .position(|(p, _)| p.urgency < packet.urgency) + .unwrap_or(state.pending.len() - start); + state.pending.reserve(1, GFP_KERNEL)?; + state + .pending + .insert_within_capacity(at, (packet, 0)) + .map_err(|_| ENOMEM)?; self.pump(state); Ok(()) } @@ -2451,6 +2464,7 @@ impl gpu::Gpu for Backend { Ok(()) } fn supports_vm_status(&self) -> bool { true } + fn supports_high_priority(&self) -> bool { true } fn feature_flags(&self) -> u64 { uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SCHEDULED_QUEUES as u64 diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs index f59cd893bf9e5..2ae883cf09723 100644 --- a/drivers/gpu/drm/asahi/g15/mod.rs +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -589,6 +589,10 @@ impl Firmware { } impl gpu::Gpu for Gpu { + fn supports_high_priority(&self) -> bool { + true + } + fn max_cmdbuf_size(&self) -> usize { command::MAX_CMDBUF } diff --git a/drivers/gpu/drm/asahi/g15/queue.rs b/drivers/gpu/drm/asahi/g15/queue.rs index 3bdebb7995e44..038baaf1a4ed0 100644 --- a/drivers/gpu/drm/asahi/g15/queue.rs +++ b/drivers/gpu/drm/asahi/g15/queue.rs @@ -8,8 +8,9 @@ //! execution context. The native ABI hardware-reservation wording remains a compatibility limit. //! QUEUE_CREATE validates //! `usc_exec_base` (4 GiB aligned, the window inside the user range) and refuses a failed VM or -//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. Ray-query scratch layouts are -//! refused by the shared default `reserve_render_scs` (RENDER_RAY_QUERY is never advertised). +//! GPU (EIO); REALTIME is refused by `file.rs` and HIGH requires authorization. Ray-query scratch +//! layouts are refused by the shared default `reserve_render_scs` (RENDER_RAY_QUERY is never +//! advertised). //! //! QUEUE_DESTROY (dropping the queue) drains: the scheduler entity is torn down first, which //! waits (killable) until every accepted job has been handed to the engine; the engine then runs @@ -39,8 +40,8 @@ use crate::{file, mmu}; /// Per-queue state the engine reads. 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. + /// Host priority: `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it (HIGH 1, + /// MEDIUM 2, LOW 3; `file.rs` refuses REALTIME). Smaller is served first. pub(crate) priority: u32, /// Completed stage time of the DRM file that created this queue. pub(crate) usage: Arc, diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 84f68c6f583f0..481b0b5cb0351 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -863,6 +863,10 @@ impl Firmware { } impl gpu::Gpu for Gpu { + fn supports_high_priority(&self) -> bool { + true + } + fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { self.shared.syncobj_wait_hint() } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index e5ffe07ed80de..06e62a443a221 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -10,8 +10,9 @@ //! process (such as a compositor). It reserves no hardware graph or execution context. //! QUEUE_CREATE validates //! `usc_exec_base` (4 GiB aligned, the window inside the user range) and refuses a failed VM or -//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. `render_scs_layout` (the -//! largest ray-query scratch layouts of the queue's render stages) is reserved at creation: +//! GPU (EIO); REALTIME is refused by `file.rs` and HIGH requires authorization. +//! `render_scs_layout` (the largest ray-query scratch layouts of the queue's render stages) is +//! reserved at creation: //! EINVAL for a malformed layout, E2BIG beyond the largest SCS-capable UMA pool; a render //! whose scratch exceeds the reservation is refused (EINVAL), as on the M4 Pro. The //! reservation also sizes the SCS-capable render pools its VM creates for it @@ -49,8 +50,8 @@ use crate::{file, mmu}; /// Per-queue state the engine reads. 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. + /// Host priority: `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it (HIGH 1, + /// MEDIUM 2, LOW 3; `file.rs` refuses REALTIME). Smaller is served first. pub(crate) priority: u32, /// Completed stage time of the DRM file that created this queue (deduplicated per file). pub(crate) usage: Arc, diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 7b503059ad9d8..45831510470ff 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -3039,6 +3039,10 @@ impl Gpu { } impl gpu::Gpu for Gpu { + fn supports_high_priority(&self) -> bool { + true + } + fn max_cmdbuf_size(&self) -> usize { command::MAX_STREAM } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 373552451979b..5ad30cc825992 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -537,6 +537,10 @@ pub(crate) trait Gpu: Send + Sync { /// Release the backend's handle owner after closing user mapping admission. /// Accepted jobs and firmware resource leases retain their own references. fn vm_closed(&self, _vm: &mmu::Vm) {} + /// Whether this GPU backend schedules `DRM_ASAHI_PRIORITY_HIGH` queues. + fn supports_high_priority(&self) -> bool { + false + } /// Create a new user command queue. fn new_queue( &self, diff --git a/drivers/gpu/drm/asahi/m3/m3_drm.rs b/drivers/gpu/drm/asahi/m3/m3_drm.rs index fb483d3ffa67d..cf45ff0191eaa 100644 --- a/drivers/gpu/drm/asahi/m3/m3_drm.rs +++ b/drivers/gpu/drm/asahi/m3/m3_drm.rs @@ -538,6 +538,7 @@ impl gpu::Gpu for Backend { Ok(()) } fn supports_vm_status(&self) -> bool { true } + fn supports_high_priority(&self) -> bool { Self::supports_high_priority(self) } /// The features the 7.1.12 file layer reported for the M3 runtime: VM status (not its /// mirror), scheduled queues, and the SoC's optional render and compute features. fn feature_flags(&self) -> u64 { diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 44845a34a4c5f..94a2539cdede4 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -454,7 +454,13 @@ impl queue::Queue for Queue { vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; let mut job=self.entity.new_job(1,Job{shared:self.shared.clone(),packet})?; for sync in syncs.drain(0..in_sync_count) {if let Some(f)=sync.fence {job.add_dependency(f)?;}} - let mut job=job.arm();let finished=job.fences().finished();job.push(); + let mut job=job.arm(); + let finished={ + let mut fences=job.fences(); + fences.set_dont_pipeline(); + fences.finished() + }; + job.push(); for mut sync in syncs {if let Some(chain)=sync.chain_fence.take() { sync.syncobj.add_point(chain,&finished,sync.timeline_value); } else {sync.syncobj.replace_fence(Some(&finished));}} diff --git a/drivers/gpu/drm/drm_auth.c b/drivers/gpu/drm/drm_auth.c index e5013b870ba06..992364a3565a0 100644 --- a/drivers/gpu/drm/drm_auth.c +++ b/drivers/gpu/drm/drm_auth.c @@ -29,11 +29,14 @@ */ #include +#include +#include #include #include #include #include +#include #include #include @@ -91,6 +94,53 @@ bool drm_is_current_master(struct drm_file *fpriv) } EXPORT_SYMBOL(drm_is_current_master); +static int drm_match_kms_master_fd(const void *data, struct file *filp, + unsigned int fd) +{ + struct inode *inode; + struct drm_file *fpriv; + struct drm_device *dev; + + if (!filp) + return 0; + + inode = file_inode(filp); + if (!S_ISCHR(inode->i_mode) || imajor(inode) != DRM_MAJOR) + return 0; + + if (!filp->f_op || filp->f_op->open != drm_open) + return 0; + + fpriv = filp->private_data; + if (!fpriv || !drm_is_primary_client(fpriv)) + return 0; + + dev = fpriv->minor->dev; + if (drm_dev_is_unplugged(dev) || + !drm_core_check_feature(dev, DRIVER_MODESET)) + return 0; + + return drm_is_current_master(fpriv) ? 1 : 0; +} + +/** + * drm_current_is_kms_master - checks whether current holds master on a KMS card + * + * On split KMS/render platforms (where the display controller and render-only + * GPU are separate DRM devices), a Wayland compositor holds DRM master on the + * KMS primary node while opening the GPU render node. Checking whether the + * calling task currently owns an active KMS master fd lets render-only GPU + * drivers grant elevated queue priority to the active compositor without + * requiring CAP_SYS_NICE. Any live DRIVER_MODESET primary node counts, and + * priority is checked at queue creation so existing queues retain their + * priority across a VT switch or DROP_MASTER (matching amdgpu). + */ +bool drm_current_is_kms_master(void) +{ + return iterate_fd(current->files, 0, drm_match_kms_master_fd, NULL) != 0; +} +EXPORT_SYMBOL(drm_current_is_kms_master); + int drm_getmagic(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_auth *auth = data; diff --git a/include/drm/drm_auth.h b/include/drm/drm_auth.h index 50131383ed814..5f5946b2f528d 100644 --- a/include/drm/drm_auth.h +++ b/include/drm/drm_auth.h @@ -133,6 +133,7 @@ struct drm_master *drm_master_get(struct drm_master *master); struct drm_master *drm_file_get_master(struct drm_file *file_priv); void drm_master_put(struct drm_master **master); bool drm_is_current_master(struct drm_file *fpriv); +bool drm_current_is_kms_master(void); struct drm_master *drm_master_create(struct drm_device *dev); diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 5bb3c41573ba7..857fa86035b2c 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -1254,8 +1254,9 @@ enum drm_asahi_priority { /** * @DRM_ASAHI_PRIORITY_HIGH: High priority queue. * - * Requires CAP_SYS_NICE or DRM master; otherwise queue creation fails - * with -EACCES. + * Requires CAP_SYS_NICE, DRM master on this device, or active DRM + * master on a KMS display card; otherwise queue creation fails with + * -EACCES. */ DRM_ASAHI_PRIORITY_HIGH = 2, diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index db35f964be4b6..d15860f9f11c7 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -227,6 +227,7 @@ const vm_flags_t RUST_CONST_HELPER_VM_NOHUGEPAGE = VM_NOHUGEPAGE; const u32 RUST_CONST_HELPER_DRM_EXEC_INTERRUPTIBLE_WAIT = DRM_EXEC_INTERRUPTIBLE_WAIT; const u32 RUST_CONST_HELPER_DRM_EXEC_IGNORE_DUPLICATES = DRM_EXEC_IGNORE_DUPLICATES; +const unsigned long RUST_CONST_HELPER_DRM_SCHED_FENCE_DONT_PIPELINE = DRM_SCHED_FENCE_DONT_PIPELINE; #if IS_ENABLED(CONFIG_GPU_BUDDY) const unsigned long RUST_CONST_HELPER_GPU_BUDDY_RANGE_ALLOCATION = GPU_BUDDY_RANGE_ALLOCATION; diff --git a/rust/kernel/drm/file.rs b/rust/kernel/drm/file.rs index 055440f5c52ea..b63ee7b123e67 100644 --- a/rust/kernel/drm/file.rs +++ b/rust/kernel/drm/file.rs @@ -233,3 +233,9 @@ impl File { } impl super::private::Sealed for File {} + +/// Returns whether the calling task holds DRM master on an active KMS display device. +pub fn current_is_kms_master() -> bool { + // SAFETY: `drm_current_is_kms_master()` inspects `current->files` under its own lock. + unsafe { bindings::drm_current_is_kms_master() } +} diff --git a/rust/kernel/drm/sched.rs b/rust/kernel/drm/sched.rs index 8194c22003c1f..439945f871fb0 100644 --- a/rust/kernel/drm/sched.rs +++ b/rust/kernel/drm/sched.rs @@ -368,6 +368,23 @@ impl<'a> JobFences<'a> { // SAFETY: self.0.finished is always a valid fence unsafe { Fence::get_raw(&mut self.0.finished) } } + + /// Marks the job's finished fence with `DRM_SCHED_FENCE_DONT_PIPELINE`. + /// + /// Prevents cross-entity dependency pipelining on a shared scheduler so a + /// job on another entity waits until this job finishes rather than only + /// until it is handed to `run_job`. Same-entity dependencies still + /// pipeline. + pub fn set_dont_pipeline(&mut self) { + // SAFETY: `self.0` is an armed job's valid `drm_sched_fence` and + // `finished.flags` is atomically updated by `set_bit()`. + unsafe { + bindings::set_bit( + bindings::DRM_SCHED_FENCE_DONT_PIPELINE as usize, + addr_of_mut!(self.0.finished.flags), + ); + } + } } struct EntityInner { diff --git a/tools/asahi/g14-v27-2-try-bind-tests.py b/tools/asahi/g14-v27-2-try-bind-tests.py index 8d02181888d4f..41492c92bbc77 100755 --- a/tools/asahi/g14-v27-2-try-bind-tests.py +++ b/tools/asahi/g14-v27-2-try-bind-tests.py @@ -210,6 +210,7 @@ def build_harness(mutation=None): raise ValueError(f'unknown mutation: {mutation}') rt_body = '\n'.join(rt_methods.values()) + submit_rs = ASAHI / 'm3/m3_submit.rs' return f''' #![allow(warnings)] @@ -371,6 +372,18 @@ def build_harness(mutation=None): self.0.push(v); Ok(()) }} + pub fn reserve(&mut self, additional: usize, _: GfpKernel) -> core::result::Result<(), kernel::alloc::AllocError> {{ + self.0.reserve(additional); + Ok(()) + }} + pub fn insert_within_capacity(&mut self, i: usize, v: T) -> core::result::Result<(), kernel::alloc::AllocError> {{ + if i <= self.0.len() && self.0.len() < self.0.capacity() {{ + self.0.insert(i, v); + Ok(()) + }} else {{ + Err(kernel::alloc::AllocError) + }} + }} pub fn pop(&mut self) -> Option {{ self.0.pop() }} pub fn remove(&mut self, i: usize) -> Result {{ if i < self.0.len() {{ Ok(self.0.remove(i)) }} else {{ Err(EINVAL) }} @@ -385,6 +398,10 @@ def build_harness(mutation=None): type Output = T; fn index(&self, i: usize) -> &T {{ &self.0[i] }} }} +impl core::ops::Index> for KVec {{ + type Output = [T]; + fn index(&self, r: core::ops::RangeFrom) -> &[T] {{ &self.0[r] }} +}} impl core::ops::IndexMut for KVec {{ fn index_mut(&mut self, i: usize) -> &mut T {{ &mut self.0[i] }} }} @@ -884,6 +901,7 @@ def build_harness(mutation=None): struct Packet {{ vm: mmu::Vm, + urgency: u8, commands: Vec, preempt: Option, render_queue: Option>, @@ -895,8 +913,12 @@ def build_harness(mutation=None): }} impl Packet {{ fn compute(vm: mmu::Vm, count: usize) -> Arc {{ + Self::compute_with_urgency(vm, count, 1) + }} + fn compute_with_urgency(vm: mmu::Vm, count: usize, urgency: u8) -> Arc {{ Arc::new(Self {{ vm, + urgency, commands: vec![Command::Compute(Default::default()); count], preempt: Some(Preempt(0xdead_0000)), render_queue: None, @@ -908,8 +930,12 @@ def build_harness(mutation=None): }}) }} fn render(vm: mmu::Vm, rq: Arc) -> Arc {{ + Self::render_with_urgency(vm, rq, 1) + }} + fn render_with_urgency(vm: mmu::Vm, rq: Arc, urgency: u8) -> Arc {{ Arc::new(Self {{ vm, + urgency, commands: vec![Command::Render {{ command: Default::default(), usc: 0x1000 }}], preempt: None, render_queue: Some(rq), @@ -1649,6 +1675,164 @@ def build_harness(mutation=None): assert!(pkt_b.guard_released.load(Ordering::SeqCst)); }} +fn test_urgency_reordering_and_fifo_order() {{ + reset_clock(); + module_parameters::robust_isolation.set(0); + // One in-flight render holds state.rendering so subsequent renders queue in pending. + let rt = Runtime::new(4, mmu::UatFirmware::Handoff); + let vm = mmu::Vm::new(50); + let rq = render::QueueRender::new(); + let inflight = Packet::render_with_urgency(vm.clone(), rq.clone(), 1); + let med_a = Packet::render_with_urgency(vm.clone(), rq.clone(), 1); + let med_b = Packet::render_with_urgency(vm.clone(), rq.clone(), 1); + let low_c = Packet::render_with_urgency(vm.clone(), rq.clone(), 0); + let high_d = Packet::render_with_urgency(vm.clone(), rq.clone(), 2); + let high_e = Packet::render_with_urgency(vm.clone(), rq.clone(), 2); + + assert_eq!(rt.submit(inflight.clone()), Ok(())); + assert_eq!(rt.submit(med_a.clone()), Ok(())); + assert_eq!(rt.submit(med_b.clone()), Ok(())); + assert_eq!(rt.submit(low_c.clone()), Ok(())); + assert_eq!(rt.submit(high_d.clone()), Ok(())); + assert_eq!(rt.submit(high_e.clone()), Ok(())); + + // Pending must be [high_d, high_e, med_a, med_b, low_c] (HIGH before MEDIUM before LOW, FIFO within ties). + {{ + let g = rt.state.lock(); + let s = g.as_ref().unwrap(); + assert_eq!(s.pending.len(), 5); + assert!(Arc::ptr_eq(&s.pending[0].0, &high_d)); + assert!(Arc::ptr_eq(&s.pending[1].0, &high_e)); + assert!(Arc::ptr_eq(&s.pending[2].0, &med_a)); + assert!(Arc::ptr_eq(&s.pending[3].0, &med_b)); + assert!(Arc::ptr_eq(&s.pending[4].0, &low_c)); + }} + + // Retire each render in turn and confirm publication order and that lower priorities still complete. + let expected = [high_d.clone(), high_e.clone(), med_a.clone(), med_b.clone(), low_c.clone()]; + let render_done = rt.state.lock().as_ref().unwrap().root.render_done_flags.clone(); + for (step, next_pkt) in expected.iter().enumerate() {{ + render_done[0].store(true, Ordering::SeqCst); + render_done[1].store(true, Ordering::SeqCst); + rt.service(); + let g = rt.state.lock(); + let s = g.as_ref().unwrap(); + let cur = &s.rendering.as_ref().expect("next render should be in flight").packet; + assert!(Arc::ptr_eq(cur, next_pkt), "step {{step}} published wrong packet"); + }} + render_done[0].store(true, Ordering::SeqCst); + render_done[1].store(true, Ordering::SeqCst); + rt.service(); + assert_eq!(inflight.outcome(), Some(Ok(()))); + for pkt in &expected {{ + assert_eq!(pkt.outcome(), Some(Ok(())), "lower-priority packet must still complete"); + }} +}} + +fn test_urgency_preserves_partly_published_and_waiting_bind_front() {{ + reset_clock(); + // 1. Partly-published LOW packet (idx != 0) must stay at index 0 ahead of arriving HIGH packet. + module_parameters::robust_isolation.set(0); + let rt = Runtime::new(4, mmu::UatFirmware::Handoff); + let vm = mmu::Vm::new(51); + // Submit more compute commands than POOL_SLOTS so low_multi publishes a prefix and keeps the + // remainder at pending[0] with idx > 0. + let low_two = Packet::compute_with_urgency(vm.clone(), POOL_SLOTS + 1, 0); + let high_new = Packet::compute_with_urgency(vm.clone(), 1, 2); + assert_eq!(rt.submit(low_two.clone()), Ok(())); + {{ + let g = rt.state.lock(); + let s = g.as_ref().unwrap(); + assert_eq!(s.pending.len(), 1); + assert!(s.pending[0].1 > 0, "prefix of low_two should already be published"); + }} + assert_eq!(rt.submit(high_new.clone()), Ok(())); + {{ + let g = rt.state.lock(); + let s = g.as_ref().unwrap(); + assert_eq!(s.pending.len(), 2); + assert!(Arc::ptr_eq(&s.pending[0].0, &low_two), "partly-published packet must stay at front"); + assert!(Arc::ptr_eq(&s.pending[1].0, &high_new)); + }} + + // 2. Packet at index 0 waiting on a context slot (waiting_bind.is_some()) must stay at index 0. + module_parameters::robust_isolation.set(1); + let rt2 = Runtime::new(4, mmu::UatFirmware::Handoff); + let vm_ext = mmu::Vm::new(99); + let vm_b = mmu::Vm::new(52); + let low_wait = Packet::compute_with_urgency(vm_b.clone(), 1, 0); + let high_wait = Packet::compute_with_urgency(vm_b.clone(), 1, 2); + let _ext_bind = rt2.graph.kernel_uat().try_bind(&vm_ext).unwrap(); + assert_eq!(rt2.submit(low_wait.clone()), Ok(())); + assert!(rt2.state.lock().as_ref().unwrap().waiting_bind.is_some()); + assert_eq!(rt2.submit(high_wait.clone()), Ok(())); + {{ + let g = rt2.state.lock(); + let s = g.as_ref().unwrap(); + assert_eq!(s.pending.len(), 2); + assert!(Arc::ptr_eq(&s.pending[0].0, &low_wait), "waiting_bind front packet must stay at front"); + assert!(Arc::ptr_eq(&s.pending[1].0, &high_wait)); + }} +}} + +fn test_cross_entity_dont_pipeline_low_to_medium_and_medium_to_high() {{ + // Model shared-scheduler drm_sched_entity_add_dependency_cb() (sched_entity.c:496): + // when DRM_SCHED_FENCE_DONT_PIPELINE is set on the producer's finished fence, a consumer on + // another entity waits for producer.finished (not producer.scheduled), so submitting the + // consumer only happens after the producer retires -> publication order is [producer, consumer]. + let submit_rs = include_str!("{submit_rs}"); + let arm_to_push = submit_rs + .split("let mut job=job.arm();") + .nth(1) + .expect("m3_submit.rs missing job.arm()") + .split("job.push();") + .next() + .expect("m3_submit.rs missing job.push()"); + assert!( + arm_to_push.contains("set_dont_pipeline()"), + "m3_submit.rs must mark finished fence DONT_PIPELINE between arm() and push()" + ); + + for (prod_urg, cons_urg) in [(0u8, 1u8), (1u8, 2u8)] {{ + reset_clock(); + module_parameters::robust_isolation.set(0); + let rt = Runtime::new(4, mmu::UatFirmware::Handoff); + let vm = mmu::Vm::new(60); + let rq = render::QueueRender::new(); + let blocker = Packet::render_with_urgency(vm.clone(), rq.clone(), 1); + let producer = Packet::render_with_urgency(vm.clone(), rq.clone(), prod_urg); + let consumer = Packet::render_with_urgency(vm.clone(), rq.clone(), cons_urg); + + assert_eq!(rt.submit(blocker.clone()), Ok(())); + // Producer is scheduled (handed to submit -> pending[0]), NOT yet finished. + assert_eq!(rt.submit(producer.clone()), Ok(())); + let dont_pipeline = true; + let producer_finished = producer.outcome().is_some(); + let consumer_ready = !dont_pipeline || producer_finished; + assert!(!consumer_ready, "DONT_PIPELINE must hold cross-entity consumer until producer finishes"); + + // Retire blocker -> producer publishes and runs. + let render_done = rt.state.lock().as_ref().unwrap().root.render_done_flags.clone(); + render_done[0].store(true, Ordering::SeqCst); + render_done[1].store(true, Ordering::SeqCst); + rt.service(); + assert!(Arc::ptr_eq(&rt.state.lock().as_ref().unwrap().rendering.as_ref().unwrap().packet, &producer)); + + // Retire producer -> producer.finished signals -> drm_sched now submits consumer. + render_done[0].store(true, Ordering::SeqCst); + render_done[1].store(true, Ordering::SeqCst); + rt.service(); + assert_eq!(producer.outcome(), Some(Ok(()))); + assert_eq!(rt.submit(consumer.clone()), Ok(())); + assert!(Arc::ptr_eq(&rt.state.lock().as_ref().unwrap().rendering.as_ref().unwrap().packet, &consumer)); + + render_done[0].store(true, Ordering::SeqCst); + render_done[1].store(true, Ordering::SeqCst); + rt.service(); + assert_eq!(consumer.outcome(), Some(Ok(()))); + }} +}} + fn main() {{ test_try_bind_no_peer_guard(); test_robust_isolation_compute_concurrent_no_deadlock(); @@ -1661,7 +1845,10 @@ def build_harness(mutation=None): test_withdraw_front_and_nonfront_during_bind_wait(); test_sleep_prepare_and_sleep_complete_during_bind_wait(); test_stop_during_bind_wait_no_deadlock(); - println!("g14-v27-2-try-bind-tests: all 11 cases passed"); + test_urgency_reordering_and_fifo_order(); + test_urgency_preserves_partly_published_and_waiting_bind_front(); + test_cross_entity_dont_pipeline_low_to_medium_and_medium_to_high(); + println!("g14-v27-2-try-bind-tests: all 14 cases passed"); }} ''' diff --git a/tools/asahi/queue-priority-tests.py b/tools/asahi/queue-priority-tests.py index ba8900384975f..06560453f90aa 100644 --- a/tools/asahi/queue-priority-tests.py +++ b/tools/asahi/queue-priority-tests.py @@ -14,10 +14,11 @@ submit = (root / 'drivers/gpu/drm/asahi/m3/m3_submit.rs').read_text() ordering = submit.split(' let urgency=', 1)[1].split(' Ok(Self', 1)[0] ordering = 'let urgency=' + ordering +arm_push = submit.split('let mut job=job.arm();', 1)[1].split('job.push();', 1)[0] +assert 'set_dont_pipeline()' in arm_push, 'm3_submit must set DRM_SCHED_FENCE_DONT_PIPELINE between arm() and push()' assert 'uapi::drm_asahi_priority_DRM_ASAHI_PRIORITY_REALTIME - data.priority' in s unit = r''' #![allow(dead_code, non_upper_case_globals)] -use std::any::Any; const EINVAL:i32=22; const EACCES:i32=13; macro_rules! cls_pr_debug { ($($arg:tt)*) => {} } mod uapi { @@ -29,6 +30,10 @@ pub unsafe fn capable(_:i32)->bool { CAP.with(|c|c.get()) } thread_local! {pub static CAP:std::cell::Cell=const {std::cell::Cell::new(false)};} } +mod drm { pub mod file { + pub fn current_is_kms_master()->bool { KMS_MASTER.with(|c|c.get()) } + thread_local! {pub static KMS_MASTER:std::cell::Cell=const {std::cell::Cell::new(false)};} +}} mod g17 {pub struct Gpu;} mod m3 {pub mod m3_drm { #[derive(PartialEq)] pub enum Profile {Legacy, Extended} @@ -36,10 +41,16 @@ pub struct Backend {pub soc:Soc,pub profile:Profile} impl Backend {pub fn supports_high_priority(&self)->bool { PREDICATE }} }} -struct Gpu(Box); impl Gpu {fn as_any(&self)->&dyn Any {&*self.0}} +struct Gpu(bool); +impl Gpu { + fn supports_high_priority(&self)->bool { self.0 } +} struct Reg {gpu:Gpu} struct Data {flags:u32,priority:u32} -struct File(bool); impl File {fn is_current_master(&self)->bool {self.0}} +struct File {master:bool} +impl File { + fn is_current_master(&self)->bool {self.master} +} fn admit(reg_data:&Reg,data:&Data,file:&File)->Result<(),i32> { GATE Ok(()) } mod sched { #[derive(Debug,PartialEq)] pub enum Priority {Low,Normal,High,Kernel} @@ -51,25 +62,34 @@ fn main() { use m3::m3_drm::*; let mut n=0; - for backend in 0..5 { for cap in [false,true] { for master in [false,true] { - let gpu:Box=match backend { - 0=>Box::new(g17::Gpu), - 1=>Box::new(Backend{soc:Soc{chip_id:0x8122},profile:Profile::Extended}), - 2=>Box::new(Backend{soc:Soc{chip_id:0x8122},profile:Profile::Legacy}), - 3=>Box::new(Backend{soc:Soc{chip_id:0x6030},profile:Profile::Extended}), - _=>Box::new(())}; - let reg=Reg{gpu:Gpu(gpu)}; - bindings::CAP.with(|c|c.set(cap)); - for flags in [0,1,u32::MAX] { for priority in [0,1,2,3,4,u32::MAX] { - // The async flag passes this gate; a backend without it refuses it later. - let expected=if flags&!1!=0 || priority>=3 {Err(EINVAL)} - else if priority!=2 {Ok(())} - else if backend!=0 && !(backend==1 && cfg!(CONFIG_DRM_ASAHI_M3_T8122)) {Err(EINVAL)} - else if cap||master {Ok(())} else {Err(EACCES)}; - assert_eq!(admit(®,&Data{flags,priority},&File(master)),expected, - "backend={backend} cap={cap} master={master} flags={flags} priority={priority}"); n+=1; - }} - }}} + let m3_cases = [ + (Backend{soc:Soc{chip_id:0x8122},profile:Profile::Extended}, true), + (Backend{soc:Soc{chip_id:0x8122},profile:Profile::Legacy}, false), + (Backend{soc:Soc{chip_id:0x6030},profile:Profile::Extended}, false), + ]; + for (backend, expected) in &m3_cases { + assert_eq!(backend.supports_high_priority(), *expected); + } + for high_supported in [false,true] { + for cap in [false,true] { + for master in [false,true] { + for kms_master in [false,true] { + let reg=Reg{gpu:Gpu(high_supported)}; + bindings::CAP.with(|c|c.set(cap)); + drm::file::KMS_MASTER.with(|c|c.set(kms_master)); + for flags in [0,1,u32::MAX] { for priority in [0,1,2,3,4,u32::MAX] { + // The async flag passes this gate; a backend without it refuses it later. + let expected=if flags&!1!=0 || priority>=3 {Err(EINVAL)} + else if priority!=2 {Ok(())} + else if !high_supported {Err(EINVAL)} + else if cap||master||kms_master {Ok(())} else {Err(EACCES)}; + assert_eq!(admit(®,&Data{flags,priority},&File{master}),expected, + "high_supported={high_supported} cap={cap} master={master} kms_master={kms_master} flags={flags} priority={priority}"); n+=1; + }} + } + } + } + } for (uapi,expected) in [(0,sched::Priority::Low),(1,sched::Priority::Normal),(2,sched::Priority::High)] { assert_eq!(ordering(3-uapi),Ok((uapi as u8,expected))); }