diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 6f9a89cc311b6..a363679cc1614 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -163,7 +163,8 @@ impl Drop for Vm { self.vm.close_idle_reclaim(); if let Some(status) = self.vm.status() { // Retained graphs may keep this status alive; the client's mirror - // object must not outlive the client's VM handle. + // objects (status and fence-error count) must not outlive the + // client's VM handle. status.release_mirror(); } if self.vm.status().is_some() { @@ -536,6 +537,13 @@ impl File { uapi::DRM_ASAHI_PARAM_GROUP_VM_STATUS_MIRROR if gpu.supports_vm_status() => { return Self::register_vm_status_mirror(data, file); } + uapi::DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR => { + // Only backends whose failed output fences are all counted (g17). + if !gpu.supports_vm_status() || !gpu.supports_vm_fence_error_count() { + return Err(EOPNOTSUPP); + } + return Self::register_vm_fence_error_mirror(data, file); + } uapi::DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS => { if data.pad != 0 || data.size < core::mem::size_of::() as u64 @@ -649,6 +657,46 @@ impl File { Ok(0) } + /// Register a file-owned GEM word as the mirror of a file-owned VM's fence-error count. + fn register_vm_fence_error_mirror( + data: &uapi::drm_asahi_get_params, + file: &DrmFile, + ) -> Result { + type Request = uapi::drm_asahi_vm_fence_error_mirror; + kernel::static_assert!(core::mem::size_of::() == 24); + kernel::static_assert!(core::mem::offset_of!(Request, handle) == 4); + kernel::static_assert!(core::mem::offset_of!(Request, offset) == 8); + kernel::static_assert!(core::mem::offset_of!(Request, flags) == 16); + let size = core::mem::size_of::(); + if data.pad != 0 || data.size < size as u64 || data.size > 4096 { + return Err(EINVAL); + } + let user = UserPtr::from_addr(data.pointer as usize); + let mut reader = UserSlice::new(user, data.size as usize).reader(); + let [ids, offset, flags] = reader.read::<[u64; 3]>()?; + // A longer request is a newer struct: fields this kernel does not know must be zero. + let mut tail = [0u8; 64]; + while !reader.is_empty() { + let chunk = &mut tail[..reader.len().min(64)]; + reader.read_slice(chunk)?; + if chunk.iter().any(|&byte| byte != 0) { + return Err(EINVAL); + } + } + // vm_id and handle share the first 8 bytes, in memory order. + let ids = ids.to_ne_bytes(); + let vm_id = u32::from_ne_bytes([ids[0], ids[1], ids[2], ids[3]]); + let handle = u32::from_ne_bytes([ids[4], ids[5], ids[6], ids[7]]); + if flags != 0 || handle == 0 || offset % core::mem::align_of::() as u64 != 0 { + return Err(EINVAL); + } + let offset = usize::try_from(offset).map_err(|_| EINVAL)?; + let status = Self::vm_status(file, vm_id)?; + let owner = gem::ObjectRef::new(gem::Object::lookup_handle(file, handle)?); + status.attach_fence_error_mirror(owner, offset)?; + Ok(0) + } + fn vm_status(file: &DrmFile, vm_id: u32) -> Result> { let vms = file.inner().vms(); let guard = vms.lock(); diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index df98a3410a50d..61c70fc9df9c7 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -6,6 +6,7 @@ //! Signalling belongs outside the device lock, after timestamp and VM-status writes. use super::context::{Context, WorkStateLease}; +use super::status::VmStatus; use crate::file::SyncItem; use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use kernel::{ @@ -190,6 +191,8 @@ pub(crate) struct Submission { error: AtomicI32, /// Live Member objects, plus the enqueue guard, independently of signalling. owners: AtomicU8, + /// The VM's status, captured at publication: it counts this fence if it fails. + status: Arc, firmware_source: bool, /// Set under the device mutex when the only member's successful retirement /// is queued, before its fence is signalled off-lock: a consumer published @@ -199,16 +202,22 @@ pub(crate) struct Submission { impl Submission { fn new(context: Arc, firmware_source: bool) -> Result> { + let status = context.status().clone(); let work = Arc::new(WorkStateLease::deferred(context)?, GFP_KERNEL)?; - Self::with_work(Some(work), firmware_source) + Self::with_work(Some(work), status, firmware_source) } - fn with_work(work: Option>, firmware_source: bool) -> Result> { + fn with_work( + work: Option>, + status: Arc, + firmware_source: bool, + ) -> Result> { Arc::pin_init( pin_init!(Self { state <- new_mutex!(State { work, ready: None }, "G17 submission work state"), remaining: AtomicU8::new(1), error: AtomicI32::new(0), owners: AtomicU8::new(1), + status, firmware_source, retired: AtomicBool::new(false), }), @@ -267,8 +276,13 @@ impl Submission { self.note_error(error); } if self.remaining.fetch_sub(1, Ordering::AcqRel) == 1 { + // The final error: note_error may have set it before any member completed. let error = self.error.load(Ordering::Acquire); if error != 0 { + // The only place a published submission's output fence takes an error, so + // every failed one is counted, once, before it signals below. A submission + // that fails before publication is counted in Outputs instead. + self.status.count_fence_error(); fence.set_error(Error::from_errno(error)); } else { self.release_state(); @@ -366,11 +380,17 @@ mod tests { fn contexts() -> FenceContexts { FenceContexts::new(1, c_str!("asahi_promise_test"), KEY).unwrap() } - fn aggregate(contexts: &FenceContexts) -> Aggregate { + fn status() -> Arc { + Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap() + } + fn aggregate_for(contexts: &FenceContexts, status: Arc) -> Aggregate { let mut fence = export_fallback(contexts).unwrap(); - fence.source = Some(Submission::with_work(None, true).unwrap()); + fence.source = Some(Submission::with_work(None, status, true).unwrap()); Aggregate(fence.into()) } + fn aggregate(contexts: &FenceContexts) -> Aggregate { + aggregate_for(contexts, status()) + } #[test] fn exact_export_identity_recognizes_unpublished_source() { @@ -417,6 +437,50 @@ mod tests { ); } + #[test] + fn failed_output_fences_are_counted_once_before_they_signal() { + let contexts = contexts(); + let status = status(); + let fence_status = + |aggregate: &Aggregate| super::super::job::fence_status(&aggregate.fence()); + // Success: no count. + let ok = aggregate_for(&contexts, status.clone()); + let member = ok.member(); + ok.finish_enqueue(Ok(())); + member.complete(Ok(())); + assert!(fence_status(&ok) > 0); + assert_eq!(status.fence_errors(), 0); + // Two failed members of one submission: one failed fence, counted once. + let failed = aggregate_for(&contexts, status.clone()); + let (a, b) = (failed.member(), failed.member()); + failed.finish_enqueue(Ok(())); + a.complete(Err(ECANCELED)); + // Another member still holds the fence. + assert_eq!(status.fence_errors(), 0); + b.complete(Err(ENODATA)); + assert_eq!(fence_status(&failed), ECANCELED.to_errno()); + assert_eq!(status.fence_errors(), 1); + // An error noted early fails the fence even if every member then succeeds. + let noted = aggregate_for(&contexts, status.clone()); + let member = noted.member(); + noted.finish_enqueue(Ok(())); + member.note_error(EIO); + member.complete(Ok(())); + assert_eq!(fence_status(¬ed), EIO.to_errno()); + assert_eq!(status.fence_errors(), 2); + // A member dropped without completing cancels its fence; so does an enqueue error. + let dropped = aggregate_for(&contexts, status.clone()); + drop(dropped.member()); + dropped.finish_enqueue(Ok(())); + assert_eq!(status.fence_errors(), 3); + let rejected = aggregate_for(&contexts, status.clone()); + rejected.finish_enqueue(Err(ENOMEM)); + assert_eq!(status.fence_errors(), 4); + // The reported VM status ignores these collateral errors; the count does not. + assert_eq!(status.reported_error(), 0); + drop((a, b, member)); + } + #[test] fn rejected_private_fence_never_exports_source_state() { let fence = export_fallback(&contexts()).unwrap(); @@ -471,6 +535,9 @@ pub(crate) struct Outputs { submission: Option, result: Result, cumulative: Option, + /// The queue's VM status. An error fence installed instead of a published submission's + /// is counted in it first, as `Submission::member_done` counts a published one. + status: Arc, } impl Outputs { pub(crate) fn new( @@ -478,6 +545,7 @@ impl Outputs { mut syncs: KVec, input_count: usize, allocation_failure: &Fence, + status: &Arc, ) -> Result { if input_count > syncs.len() { return Err(EINVAL); @@ -486,6 +554,8 @@ impl Outputs { let fallback = match export_fallback(contexts) { Ok(fence) => fence, Err(error) => { + // The outputs end with the queue's failed fence: count it before installing. + status.count_fence_error(); if let Some(bundle) = &mut cumulative { bundle.fail(allocation_failure); } else { @@ -501,6 +571,7 @@ impl Outputs { submission: None, result: Err(ECANCELED), cumulative, + status: status.clone(), }) } pub(crate) fn inputs(&self) -> &[SyncItem] { @@ -548,6 +619,9 @@ impl Drop for Outputs { } if let Some(fallback) = self.fallback.take() { if let Err(error) = self.result { + // Counted before the fallback is installed or signals. A restarted SUBMIT + // installs it at the same timeline points again, and the count tells. + self.status.count_fence_error(); fallback.set_error(error); } if let Some(bundle) = &mut self.cumulative { diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ddbc46092ce7f..7f16067980387 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -2561,6 +2561,13 @@ impl gpu::Gpu for Gpu { true } + /// A published submission's output fence takes its error only in + /// `fence::Submission::member_done`, and a SUBMIT that fails before publication installs + /// its error fence through `fence::Outputs`; both count it in the VM status first. + fn supports_vm_fence_error_count(&self) -> bool { + true + } + /// The G17 runtime never programs fault_control into the firmware, so unmapped reads are not /// guaranteed to return zero. Advertising soft faults made Mesa point out-of-bounds vec3/vec4 /// vertex fetches at address 0 and skip bounds checks on bounded loads; on T6040 those reads diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index d322c2710ab9e..17b903033233f 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -559,6 +559,7 @@ impl crate::queue::Queue for Queue { syncs, input_count, &self.allocation_failure, + self.context.status(), ) { Ok(outputs) => outputs, Err(error) => { diff --git a/drivers/gpu/drm/asahi/g17/status.rs b/drivers/gpu/drm/asahi/g17/status.rs index 54f5160f32f11..abfe407bf1503 100644 --- a/drivers/gpu/drm/asahi/g17/status.rs +++ b/drivers/gpu/drm/asahi/g17/status.rs @@ -4,7 +4,7 @@ use crate::debug::*; use crate::gem; -use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering}; use kernel::{new_mutex, prelude::*, str::BStr, sync::Mutex, task::Pid}; const DEBUG_CLASS: DebugFlags = DebugFlags::Errors; @@ -30,20 +30,47 @@ pub(crate) struct VmStatus { /// The process that created the VM, named in the failure report. tgid: Pid, comm: [u8; 16], - /// The client's mapped status word, retained with its object only while the - /// client's VM handle exists; released by `release_mirror` at VM close. + /// The client's mapped words, each retained with its object only while the + /// client's VM handle exists; released by `release_mirror` at VM close. The + /// fence-error count lives here too, so it and its word change together. #[pin] - mirror: Mutex>, + mirror: Mutex, } /// One aligned word inside the retained, vmapped mirror object. -struct Mirror { - word: *mut i32, +struct Mirror { + word: *mut T, _owner: gem::ObjectRef, } // SAFETY: The word points into the mapping the retained owner keeps alive; it is // only accessed atomically through this pointer while the mutex is held. -unsafe impl Send for Mirror {} +unsafe impl Send for Mirror {} + +struct Mirrors { + /// The status word (DRM_ASAHI_PARAM_GROUP_VM_STATUS_MIRROR). + status: Option>, + /// Output fences of this VM's submissions that signalled with an error. One + /// increment per failed fence: a u64 never wraps. + fence_errors: u64, + /// The word that mirrors `fence_errors` (DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR). + fence_error_word: Option>, +} + +/// Check one aligned `T` inside a GEM object a client registers, and map it. +fn map_word(owner: &mut gem::ObjectRef, offset: usize) -> Result<*mut T> { + if owner.size() > MIRROR_MAX_SIZE + || offset % core::mem::align_of::() != 0 + || offset + .checked_add(core::mem::size_of::()) + .is_none_or(|end| end > owner.size()) + { + return Err(EINVAL); + } + let base = owner.vmap()?.addr.cast::(); + // SAFETY: The checked range is inside the page-aligned mapping, which the + // caller retains with `owner` for as long as it keeps the pointer. + Ok(unsafe { base.add(offset) }.cast::()) +} impl VmStatus { /// Called from the creating client's ioctl: the VM records who it belongs to. @@ -64,7 +91,14 @@ impl VmStatus { recovery_guilty: AtomicBool::new(false), tgid, comm, - mirror <- new_mutex!(None, "Asahi VM status mirror"), + mirror <- new_mutex!( + Mirrors { + status: None, + fence_errors: 0, + fence_error_word: None, + }, + "Asahi VM status mirror" + ), }) } @@ -148,14 +182,38 @@ impl VmStatus { Ok(_) => error.to_errno(), Err(first) => first, }; - let mirror = self.mirror.lock(); - if let Some(mirror) = mirror.as_ref() { + let mirrors = self.mirror.lock(); + if let Some(mirror) = mirrors.status.as_ref() { // SAFETY: attach_mirror stored only an aligned word within a mapping the // retained owner keeps alive while this entry exists under the mutex. unsafe { AtomicI32::from_ptr(mirror.word) }.store(error, Ordering::SeqCst); } } + /// Count an output fence of this VM that is about to signal with an error, any errno. + /// The caller signals the fence only after this returns: a client that sees the fence + /// signalled and then reads its registered word sees this increment. + /// + /// Only the kernel writes the word, with a single store of its own count under the + /// mutex (never a read-modify-write of client memory), so concurrent counts reach the + /// word in order and it never goes back. + pub(crate) fn count_fence_error(&self) { + let mut mirrors = self.mirror.lock(); + mirrors.fence_errors = mirrors.fence_errors.wrapping_add(1); + if let Some(mirror) = mirrors.fence_error_word.as_ref() { + // SAFETY: attach_fence_error_mirror stored only an 8-byte aligned word within a + // mapping the retained owner keeps alive while this entry exists under the mutex. + unsafe { AtomicU64::from_ptr(mirror.word) } + .store(mirrors.fence_errors, Ordering::Release); + } + } + + /// Output fences of this VM that signalled with an error, counted so far. + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn fence_errors(&self) -> u64 { + self.mirror.lock().fence_errors + } + /// A teardown error of a client whose VM handle is already gone. pub(crate) fn unobserved_teardown(&self, error: Error) -> bool { self.client_closed.load(Ordering::Acquire) @@ -178,20 +236,18 @@ impl VmStatus { } /// Retain one mapped GEM word until the client's VM handle is dropped. + /// + /// release_mirror marks the client closed before it takes the mutex, so a registration + /// racing with VM destruction is refused (ENOENT) rather than kept past it. The last + /// reference to a status can then drop in atomic context (a fence's last put): with + /// both mirrors released, dropping it releases no object and sleeps nowhere. pub(crate) fn attach_mirror(&self, mut owner: gem::ObjectRef, offset: usize) -> Result { - if owner.size() > MIRROR_MAX_SIZE - || offset % core::mem::align_of::() != 0 - || offset - .checked_add(core::mem::size_of::()) - .is_none_or(|end| end > owner.size()) - { - return Err(EINVAL); + let word = map_word::(&mut owner, offset)?; + let mut mirrors = self.mirror.lock(); + if self.client_closed() { + return Err(ENOENT); } - let base = owner.vmap()?.addr.cast::(); - // SAFETY: The checked range is inside the retained, page-aligned mapping. - let word = unsafe { base.add(offset) }.cast::(); - let mut mirror = self.mirror.lock(); - if mirror.is_some() { + if mirrors.status.is_some() { return Err(EBUSY); } // No reporter runs while the mutex is held, so the word holds the first @@ -199,7 +255,34 @@ impl VmStatus { let error = self.reported_error.load(Ordering::SeqCst); // SAFETY: The retained owner keeps this checked, aligned word mapped. unsafe { AtomicI32::from_ptr(word) }.store(error, Ordering::SeqCst); - *mirror = Some(Mirror { + mirrors.status = Some(Mirror { + word, + _owner: owner, + }); + Ok(()) + } + + /// Retain one mapped, 8-byte aligned GEM word that mirrors the fence-error count + /// until the client's VM handle is dropped. The word starts at the current count. + pub(crate) fn attach_fence_error_mirror( + &self, + mut owner: gem::ObjectRef, + offset: usize, + ) -> Result { + let word = map_word::(&mut owner, offset)?; + let mut mirrors = self.mirror.lock(); + // As in attach_mirror: a registration racing with VM destruction is refused. + if self.client_closed() { + return Err(ENOENT); + } + if mirrors.fence_error_word.is_some() { + return Err(EBUSY); + } + // No count runs while the mutex is held, so the word holds the current count when + // it becomes visible, and every later count stores after this. + // SAFETY: The retained owner keeps this checked, aligned word mapped. + unsafe { AtomicU64::from_ptr(word) }.store(mirrors.fence_errors, Ordering::Release); + mirrors.fence_error_word = Some(Mirror { word, _owner: owner, }); @@ -212,11 +295,15 @@ impl VmStatus { self.client_closed.store(true, Ordering::Release); } - /// The client's VM handle is gone and nobody reads the mirror any more. The - /// mapping and object reference drop outside the mutex (GEM release may sleep). + /// The client's VM handle is gone and nobody reads the mirrors any more. The + /// mappings and object references drop outside the mutex (GEM release may sleep). + /// Later fence errors are still counted, but no longer stored anywhere. pub(crate) fn release_mirror(&self) { self.mark_client_closed(); - let taken = self.mirror.lock().take(); + let taken = { + let mut mirrors = self.mirror.lock(); + (mirrors.status.take(), mirrors.fence_error_word.take()) + }; drop(taken); } } @@ -268,7 +355,7 @@ mod tests { assert!(!status.unobserved_teardown(ETIMEDOUT)); status.report_failure(ENOENT); assert!(!status.warned.load(Ordering::Acquire)); - assert!(status.mirror.lock().is_none()); + assert!(status.mirror.lock().status.is_none()); } #[test] @@ -286,6 +373,23 @@ mod tests { assert!(status.warned.load(Ordering::Acquire)); } + #[test] + fn fence_errors_only_grow_and_survive_the_mirror() { + let Ok(status) = KBox::pin_init(VmStatus::new(), GFP_KERNEL) else { + panic!("allocation failed"); + }; + assert_eq!(status.fence_errors(), 0); + status.count_fence_error(); + status.count_fence_error(); + assert_eq!(status.fence_errors(), 2); + // A collateral cancellation counts without touching the reported status. + assert_eq!(status.reported_error(), 0); + status.release_mirror(); + assert!(status.mirror.lock().fence_error_word.is_none()); + status.count_fence_error(); + assert_eq!(status.fence_errors(), 3); + } + #[test] fn an_open_client_warns_on_its_first_error_only() { let Ok(status) = KBox::pin_init(VmStatus::new(), GFP_KERNEL) else { diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 588f95f087a49..bc68a23a7ad81 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -377,6 +377,13 @@ pub(crate) trait Gpu: Send + Sync { fn supports_vm_status(&self) -> bool { false } + /// Whether every submission of a user VM whose output fence ends with an error is counted + /// in its VM status before that fence is installed or signals, failed SUBMITs included, + /// so the count can be mirrored (DRM_ASAHI_FEATURE_VM_FENCE_ERROR_COUNT). A cumulative + /// output may also carry an earlier point's error, counted by that point's submission. + fn supports_vm_fence_error_count(&self) -> bool { + false + } /// Limits for independently executing queues, if supported by this GPU. fn queue_limits(&self) -> Option { None @@ -388,6 +395,9 @@ pub(crate) trait Gpu: Send + Sync { flags |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS_MIRROR); } + if self.supports_vm_status() && self.supports_vm_fence_error_count() { + flags |= uapi::DRM_ASAHI_FEATURE_VM_FENCE_ERROR_COUNT as u64; + } if self.queue_limits().is_some() { flags |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES); } diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index fc3b32a63b470..8f743d111d694 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -531,6 +531,20 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_RENDER_MESH_OUTPUT ((1ULL) << 38) +/* + * DRM_ASAHI_FEATURE_VM_FENCE_ERROR_COUNT: GET_PARAMS supports + * DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR, which registers a userspace + * word that counts the SUBMIT ioctls of a VM whose output fence ended with an + * error. The kernel updates the word before it installs or signals such a + * fence, so for a submission without DRM_ASAHI_SYNC_TIMELINE_SYNCOBJ_CUMULATIVE + * outputs, when every output fence of the submission has signalled and the + * word still holds the value it had before the submission, none of them + * failed. + * Registration may still be refused. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_VM_FENCE_ERROR_COUNT ((1ULL) << 50) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 @@ -541,6 +555,13 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_PARAM_GROUP_VM_STATUS_MIRROR 3 +/** + * define DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR - GET_PARAMS group for + * struct drm_asahi_vm_fence_error_mirror, available with + * DRM_ASAHI_FEATURE_VM_FENCE_ERROR_COUNT + */ +#define DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR 4 + /* GET_PARAMS group VM_STATUS is an in/out query on the calling file's VM. * Set pointer to this structure and size to sizeof(structure). * vm_id selects the VM; flags and pad must be zero. error is output only. @@ -595,9 +616,11 @@ struct drm_asahi_queue_limits { * group DRM_ASAHI_PARAM_GROUP_VM_STATUS_MIRROR * * Registers a 32-bit word in a GEM object of the calling file. The kernel - * keeps its own reference to the object for the lifetime of the VM status, - * zeroes the word, and from then on keeps it equal to the VM status error + * keeps its own reference to the object until the VM is destroyed, + * stores the VM's first reported error in the word (0 if none), and from + * then on keeps it equal to the VM status error * (see &drm_asahi_vm_status.error). Each VM accepts one registration. + * A VM that does not exist or is being destroyed fails with ENOENT. * EOPNOTSUPP means that userspace must keep using * DRM_ASAHI_PARAM_GROUP_VM_STATUS. */ @@ -615,6 +638,49 @@ struct drm_asahi_vm_status_mirror { __u32 flags; }; +/** + * struct drm_asahi_vm_fence_error_mirror - VM fence error count registration, + * GET_PARAMS group DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR + * + * Registers a 64-bit word in a GEM object of the calling file. The kernel + * keeps its own reference to the object until the VM is destroyed, sets the + * word to the VM's current count, and from then on keeps it equal to the + * number of this VM's SUBMIT ioctls whose output fence ended with an error + * (any errno, including ECANCELED and ENODATA, which leave the VM status at + * 0). It updates the word before it installs or signals each such fence; the + * count only grows and does not wrap. Userspace only reads the word. + * + * Each such SUBMIT counts one, whether or not it named output syncs, so a + * submission split across several SUBMITs counts once per failed SUBMIT. + * That includes a SUBMIT that fails and installs an error fence in its + * outputs instead; the kernel counts it before installing it. A SUBMIT + * refused before it has an output fence (invalid arguments, queue or sync + * list) counts nothing. A DRM_ASAHI_SYNC_TIMELINE_SYNCOBJ_CUMULATIVE output + * may also carry an earlier point's error, which only that point's SUBMIT + * counts, if it is one of this VM's. + * + * Each VM accepts one registration (EBUSY for a second one). EINVAL: nonzero + * flags, a zero handle, an offset that is not 8-byte aligned or outside the + * object, an object larger than 64 KiB, a VM without a status, or a request + * size over 4 KiB or with nonzero bytes past this struct. ENOENT: missing, + * foreign or destroyed vm_id, or missing handle. EOPNOTSUPP: the device does + * not count fence errors (DRM_ASAHI_FEATURE_VM_FENCE_ERROR_COUNT is clear); + * kernels without this group fail it with EINVAL. + */ +struct drm_asahi_vm_fence_error_mirror { + /** @vm_id: VM whose fence errors are counted */ + __u32 vm_id; + + /** @handle: GEM object holding the word, at most 64 KiB in size */ + __u32 handle; + + /** @offset: Byte offset of the word in the object, 8-byte aligned */ + __u64 offset; + + /** @flags: MBZ */ + __u64 flags; +}; + /** * struct drm_asahi_get_params - Arguments passed to DRM_IOCTL_ASAHI_GET_PARAMS */ @@ -626,7 +692,11 @@ struct drm_asahi_get_params { * DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS when * DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES is set, or * DRM_ASAHI_PARAM_GROUP_VM_STATUS_MIRROR when - * DRM_ASAHI_FEATURE_VM_STATUS_MIRROR is set. Any other group, or a + * DRM_ASAHI_FEATURE_VM_STATUS_MIRROR is set, or + * DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR when + * DRM_ASAHI_FEATURE_VM_FENCE_ERROR_COUNT is set. With that bit clear, + * DRM_ASAHI_PARAM_GROUP_VM_FENCE_ERROR_MIRROR fails with EOPNOTSUPP, or + * with EINVAL on kernels that predate it. Any other group, or any other * group whose feature bit is clear, fails with EINVAL. */ __u32 param_group; diff --git a/tools/asahi/g15-input-error-tests.py b/tools/asahi/g15-input-error-tests.py index 0aa557e8dae80..62e0de4751734 100644 --- a/tools/asahi/g15-input-error-tests.py +++ b/tools/asahi/g15-input-error-tests.py @@ -40,12 +40,13 @@ def extract(text, marker): macro_rules! mod_pr_debug { ($($arg:tt)*)=>{{ let _=format_args!($($arg)*); }} } struct Mutex(StdMutex);impl Mutex{fn lock(&self)->MutexGuard<'_,T>{self.0.lock().unwrap()}} struct Mirror{word:*mut i32} +struct Mirrors{status:Option} struct BStr<'a>(&'a [u8]); impl<'a> BStr<'a>{fn from_bytes(b:&'a [u8])->Self{Self(b)}} impl std::fmt::Display for BStr<'_>{fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{write!(f,"{}",String::from_utf8_lossy(self.0))}} -struct VmStatus{error:AtomicI32,reported_error:AtomicI32,client_closed:AtomicBool,teardown_expired:AtomicBool,warned:AtomicBool,recovery_guilty:AtomicBool,tgid:i32,comm:[u8;16],mirror:Mutex>} +struct VmStatus{error:AtomicI32,reported_error:AtomicI32,client_closed:AtomicBool,teardown_expired:AtomicBool,warned:AtomicBool,recovery_guilty:AtomicBool,tgid:i32,comm:[u8;16],mirror:Mutex} impl VmStatus { - fn new(word:*mut i32)->Self{Self{error:AtomicI32::new(0),reported_error:AtomicI32::new(0),client_closed:AtomicBool::new(false),teardown_expired:AtomicBool::new(false),warned:AtomicBool::new(false),recovery_guilty:AtomicBool::new(false),tgid:1,comm:*b"host-test\0\0\0\0\0\0\0",mirror:Mutex(StdMutex::new(Some(Mirror{word})))}} + fn new(word:*mut i32)->Self{Self{error:AtomicI32::new(0),reported_error:AtomicI32::new(0),client_closed:AtomicBool::new(false),teardown_expired:AtomicBool::new(false),warned:AtomicBool::new(false),recovery_guilty:AtomicBool::new(false),tgid:1,comm:*b"host-test\0\0\0\0\0\0\0",mirror:Mutex(StdMutex::new(Mirrors{status:Some(Mirror{word})}))}} __STATUS__ } mod g17 {use super::*;__POLICY__} @@ -69,7 +70,7 @@ def extract(text, marker): self.saw_sticky.store(self.vm.status.get(),Ordering::SeqCst); self.saw_report.store(self.vm.status.reported_error(),Ordering::SeqCst); let mirror=self.vm.status.mirror.lock(); - self.saw_mirror.store(unsafe{AtomicI32::from_ptr(mirror.as_ref().unwrap().word)}.load(Ordering::SeqCst),Ordering::SeqCst); + self.saw_mirror.store(unsafe{AtomicI32::from_ptr(mirror.status.as_ref().unwrap().word)}.load(Ordering::SeqCst),Ordering::SeqCst); self.result.store(result.err().map_or(0,|e|e.to_errno()),Ordering::SeqCst); self.signals.fetch_add(1,Ordering::SeqCst); } diff --git a/tools/asahi/g17-fence-error-count-tests.py b/tools/asahi/g17-fence-error-count-tests.py new file mode 100755 index 0000000000000..4a442907615d3 --- /dev/null +++ b/tools/asahi/g17-fence-error-count-tests.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production G17 fence-error count bodies on host models. + +Submission::member_done and note_error, and Outputs::new, finish, install and +Drop (g17/fence.rs), and the VmStatus count, mirror registration and release +bodies (g17/status.rs) are compiled unchanged. Fences, syncobjs, GEM objects +and kernel mutexes are models: a model fence records the count and the mirrored +word when it signals, a model output sync the error and the word when a fence +is installed in it. Checks: an output fence that signals with an error is +counted once, before it signals, keyed on the final error; the error fence of a +SUBMIT that fails before publication (allocation failure, or ERESTARTSYS and +other errors before publish) is counted before it is installed; success and a +malformed sync split are never counted; registration starts at the current +count and VM drop releases the object; concurrent counts never move the word +backwards. +With --mutations, each listed source change must die at its intended assertion. +""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] / "drivers/gpu/drm/asahi/g17" + + +def extract(text, marker): + if text.count(marker) != 1: + raise RuntimeError(f"marker not unique: {marker!r}") + start = text.index(marker) + opening = text.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return text[start:end] + + +def line(text, marker): + lines = [entry for entry in text.splitlines() if marker in entry] + if len(lines) != 1: + raise RuntimeError(f"line not unique: {marker!r}") + return lines[0] + + +HARNESS = r''' +#![allow(dead_code)] +use std::sync::{Arc, Mutex as StdMutex, MutexGuard}; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Error(i32); +impl Error { + fn from_errno(errno: i32) -> Self { assert!(errno < 0); Self(errno) } + fn to_errno(self) -> i32 { self.0 } +} +type Result = core::result::Result; +const ENOENT: Error = Error(-2); const EIO: Error = Error(-5); const ENOMEM: Error = Error(-12); +const EBUSY: Error = Error(-16); const EINVAL: Error = Error(-22); const ENODATA: Error = Error(-61); +const ECANCELED: Error = Error(-125); const ERESTARTSYS: Error = Error(-512); +struct Mutex(StdMutex); +impl Mutex { fn lock(&self) -> MutexGuard<'_, T> { self.0.lock().unwrap() } } + +mod gem { + use std::sync::{Arc, atomic::{AtomicU64, AtomicUsize, Ordering}}; + pub struct VMap { pub addr: *mut core::ffi::c_void } + /// A GEM object reference: `words` backs `size` bytes; the test keeps its own view. + pub struct ObjectRef { pub words: Arc>, pub size: usize, map: Option, pub drops: Arc } + impl ObjectRef { + pub fn new(words: &Arc>, size: usize, drops: &Arc) -> Self { + assert!(size <= words.len() * 8); + Self { words: words.clone(), size, map: None, drops: drops.clone() } + } + pub fn size(&self) -> usize { self.size } + pub fn vmap(&mut self) -> super::Result<&VMap> { + let addr = self.words.as_ptr() as *mut core::ffi::c_void; + Ok(self.map.get_or_insert(VMap { addr })) + } + } + impl Drop for ObjectRef { fn drop(&mut self) { self.drops.fetch_add(1, Ordering::SeqCst); } } +} + +__STATUS_ITEMS__ + +struct VmStatus { reported_error: AtomicI32, client_closed: AtomicBool, mirror: Mutex } +impl VmStatus { + fn new() -> Self { + Self { + reported_error: AtomicI32::new(0), + client_closed: AtomicBool::new(false), + mirror: Mutex(StdMutex::new(Mirrors { status: None, fence_errors: 0, fence_error_word: None })), + } + } + fn count(&self) -> u64 { self.mirror.lock().fence_errors } +__STATUS__ +} + +/// The model fence notes, when it signals, the VM's count and the mirrored word. +struct ExportFence { scoped: bool, waited: AtomicBool } +struct UserFence { + payload: T, + status: Arc, + view: Option<(Arc>, usize)>, + error: AtomicI32, + signalled: AtomicBool, + seen: StdMutex)>>, +} +impl core::ops::Deref for UserFence { type Target = T; fn deref(&self) -> &T { &self.payload } } +impl UserFence { + fn new(status: &Arc, view: Option<(Arc>, usize)>) -> Self { + Self { payload: ExportFence { scoped: false, waited: AtomicBool::new(false) }, status: status.clone(), view, + error: AtomicI32::new(0), signalled: AtomicBool::new(false), seen: StdMutex::new(None) } + } + fn set_error(&self, error: Error) { + assert!(!self.signalled.load(Ordering::SeqCst), "error set after signal"); + self.error.store(error.to_errno(), Ordering::SeqCst); + } + fn signal(&self) { + assert!(!self.signalled.swap(true, Ordering::SeqCst), "signalled twice"); + let word = self.view.as_ref().map(|(words, index)| words[*index].load(Ordering::Acquire)); + *self.seen.lock().unwrap() = Some((self.status.count(), word)); + } + fn seen(&self) -> (u64, Option) { self.seen.lock().unwrap().expect("fence signalled") } + fn errno(&self) -> i32 { assert!(self.signalled.load(Ordering::SeqCst)); self.error.load(Ordering::SeqCst) } +} +fn signal_exported(fence: &UserFence) { fence.signal() } +fn unwaited(_: &AtomicBool) {} +mod trace { pub fn output(_: &super::UserFence, _: i32) {} } + +struct Submission { remaining: AtomicU8, error: AtomicI32, status: Arc, released: AtomicBool } +impl Submission { + fn new(status: &Arc, members: u8) -> Self { + // The enqueue guard plus each member, as Aggregate::member counts them. + Self { remaining: AtomicU8::new(members + 1), error: AtomicI32::new(0), status: status.clone(), + released: AtomicBool::new(false) } + } + fn release_state(&self) { self.released.store(true, Ordering::SeqCst); } +__FENCE__ +} + +/// What output syncs received: the installed fence's errno and the mirrored word then. +type Log = Arc>>; +type View = (Arc>, usize); +type KVec = Vec; +type UniqueFence = UserFence; +#[derive(Clone)] +struct Fence { errno: i32 } +impl Fence { + fn from_fence(fence: &UserFence) -> Self { Self { errno: fence.error.load(Ordering::SeqCst) } } +} +fn note(view: &View, log: &Log, fence: &Fence) { + log.lock().unwrap().push((fence.errno, view.0[view.1].load(Ordering::Acquire))); +} +struct SyncObj { view: View, log: Log } +impl SyncObj { + fn add_point(&self, _chain: (), fence: &Fence, _point: u64) { note(&self.view, &self.log, fence) } + fn replace_fence(&self, fence: Option<&Fence>) { note(&self.view, &self.log, fence.unwrap()) } +} +mod sync_output { + pub struct SignalBundle { pub view: super::View, pub log: super::Log } + impl SignalBundle { pub fn fail(&mut self, fence: &super::Fence) { super::note(&self.view, &self.log, fence) } } +} +struct SyncItem { syncobj: SyncObj, chain_fence: Option<()>, timeline_value: u64, cumulative: Option } +struct FenceContexts { fail: bool, status: Arc, view: Option } +fn export_fallback(contexts: &FenceContexts) -> Result> { + if contexts.fail { return Err(ENOMEM); } + Ok(UserFence::new(&contexts.status, contexts.view.clone())) +} +/// Published submissions end in member_done, exercised above. +struct Aggregate; +impl Aggregate { + fn fence(&self) -> Fence { unreachable!() } + fn finish_enqueue(&self, _: Result) { unreachable!() } +} +__OUTPUTS__ + +/// One input sync, then `outputs` output syncs: a timeline point, then binary syncobjs. +fn syncs(view: &View, log: &Log, outputs: usize, cumulative: bool) -> Vec { + (0..=outputs).map(|index| SyncItem { + syncobj: SyncObj { view: view.clone(), log: log.clone() }, + chain_fence: (index == 1).then_some(()), + timeline_value: 7, + cumulative: (cumulative && index == 1) + .then(|| sync_output::SignalBundle { view: view.clone(), log: log.clone() }), + }).collect() +} + +fn object(words: usize) -> (Arc>, Arc) { + (Arc::new((0..words).map(|_| AtomicU64::new(0xdead_beef)).collect()), Arc::new(AtomicUsize::new(0))) +} + +/// Complete one submission: the enqueue guard first, then each member's result. +fn run(status: &Arc, view: &Option<(Arc>, usize)>, results: &[Result], early: Option) + -> UserFence { + let fence = UserFence::new(status, view.clone()); + let submission = Submission::new(status, results.len() as u8); + if let Some(error) = early { submission.note_error(error); } + submission.member_done(&fence, Ok(())); + for result in results { submission.member_done(&fence, *result); } + assert!(fence.signalled.load(Ordering::SeqCst)); + assert_eq!(submission.released.load(Ordering::SeqCst), fence.errno() == 0); + fence +} + +fn main() { + let status = Arc::new(VmStatus::new()); + // A failure before registration is counted and becomes the word's first value. + let early = run(&status, &None, &[Err(ECANCELED)], None); + assert_eq!(early.seen(), (1, None), "failed fence counted before it signals"); + let (words, drops) = object(2048); + let size = 16 * 1024; + assert_eq!(status.attach_fence_error_mirror(gem::ObjectRef::new(&words, size, &drops), 4), Err(EINVAL), + "misaligned offset refused"); + assert_eq!(status.attach_fence_error_mirror(gem::ObjectRef::new(&words, size, &drops), size), Err(EINVAL), + "offset past the object refused"); + let (big, big_drops) = object(80 * 128); + assert_eq!(status.attach_fence_error_mirror(gem::ObjectRef::new(&big, 80 * 1024, &big_drops), 0), Err(EINVAL), + "object over 64 KiB refused"); + assert_eq!(drops.load(Ordering::SeqCst), 2, "refused registrations keep no reference"); + status.attach_fence_error_mirror(gem::ObjectRef::new(&words, size, &drops), 8).unwrap(); + assert_eq!(words[1].load(Ordering::SeqCst), 1, "registration starts at the current count"); + assert_eq!(words[0].load(Ordering::SeqCst), 0xdead_beef, "registration writes only its word"); + assert_eq!(status.attach_fence_error_mirror(gem::ObjectRef::new(&words, size, &drops), 0), Err(EBUSY), + "one registration per VM"); + let view = Some((words.clone(), 1)); + + let ok = run(&status, &view, &[Ok(()), Ok(())], None); + assert_eq!((ok.errno(), ok.seen()), (0, (1, Some(1))), "success leaves the count"); + let both = run(&status, &view, &[Err(ECANCELED), Err(ENODATA)], None); + assert_eq!(both.errno(), ECANCELED.to_errno()); + assert_eq!(both.seen(), (2, Some(2)), "one count per failed fence, stored before it signals"); + let noted = run(&status, &view, &[Ok(())], Some(EIO)); + assert_eq!(noted.errno(), EIO.to_errno()); + assert_eq!(noted.seen(), (3, Some(3)), "an error noted early is counted on the final error"); + let late = run(&status, &view, &[Ok(()), Err(ENOMEM)], None); + assert_eq!(late.seen(), (4, Some(4)), "failed fence counted before it signals"); + println!("PASS sequential: counted once per failed fence before its signal, success uncounted, \ + registration bounds/alignment/EBUSY, starts at the current count"); + + // Concurrent failures: the client's protocol holds (sample the word before the submission; + // a failed fence, once signalled, shows a larger word), and the word never goes back. + let stop = Arc::new(AtomicBool::new(false)); + let reader = { + let (words, stop) = (words.clone(), stop.clone()); + std::thread::spawn(move || { + let mut last = 0; + while !stop.load(Ordering::Acquire) { + let now = words[1].load(Ordering::Acquire); + assert!(now >= last, "the word never goes back"); + last = now; + } + }) + }; + let workers: Vec<_> = (0..8).map(|worker| { + let (status, view) = (status.clone(), view.clone()); + std::thread::spawn(move || { + for round in 0..2000u32 { + let result = if (worker + round) % 3 == 0 { Ok(()) } else { Err(ECANCELED) }; + let before = view.as_ref().unwrap().0[1].load(Ordering::Acquire); + let fence = run(&status, &view, &[result], None); + let (count, word) = fence.seen(); + assert!(word.unwrap() <= count); + if result.is_err() { assert!(word.unwrap() > before, "failed fence counted before it signals"); } + } + }) + }).collect(); + for worker in workers { worker.join().unwrap(); } + stop.store(true, Ordering::Release); + reader.join().unwrap(); + let failures = (0..8u32).map(|w| (0..2000u32).filter(|r| (w + r) % 3 != 0).count() as u64).sum::(); + assert_eq!((status.count(), words[1].load(Ordering::SeqCst)), (4 + failures, 4 + failures)); + println!("PASS concurrent: {} failures from 8 threads, word == count, monotonic", failures); + + // A SUBMIT that fails before publication installs an error fence instead of a published + // submission's: it is counted before any output receives it. + let outs = Arc::new(VmStatus::new()); + let (owords, odrops) = object(2048); + outs.attach_fence_error_mirror(gem::ObjectRef::new(&owords, size, &odrops), 0).unwrap(); + let oview: View = (owords.clone(), 0); + let log: Log = Default::default(); + let taken = |log: &Log| std::mem::take(&mut *log.lock().unwrap()); + let alloc = Fence { errno: ENOMEM.to_errno() }; + let failing = FenceContexts { fail: true, status: outs.clone(), view: Some(oview.clone()) }; + let working = FenceContexts { fail: false, status: outs.clone(), view: Some(oview.clone()) }; + assert_eq!(Outputs::new(&failing, syncs(&oview, &log, 2, false), 1, &alloc, &outs).err(), Some(ENOMEM)); + assert_eq!(taken(&log), [(ENOMEM.to_errno(), 1); 2], "allocation failure counted before it is installed"); + assert_eq!(Outputs::new(&failing, syncs(&oview, &log, 2, true), 1, &alloc, &outs).err(), Some(ENOMEM)); + assert_eq!(taken(&log), [(ENOMEM.to_errno(), 2)], "allocation failure counted before it is installed"); + // A malformed split installs nothing and counts nothing. + assert_eq!(Outputs::new(&working, syncs(&oview, &log, 0, false), 2, &alloc, &outs).err(), Some(EINVAL)); + assert_eq!((taken(&log).len(), outs.count()), (0, 2), "a malformed split counts nothing"); + // An interrupted SUBMIT (restarted later at the same points), and any other error before + // publication: the fallback fence carries the error and is counted first. + let outputs = Outputs::new(&working, syncs(&oview, &log, 2, false), 1, &alloc, &outs).unwrap(); + assert_eq!(outs.count(), 2, "prepared outputs count nothing"); + assert_eq!(outputs.finish(Err(ERESTARTSYS)), Err(ERESTARTSYS)); + assert_eq!(taken(&log), [(ERESTARTSYS.to_errno(), 3); 2], "a failed SUBMIT's fence is counted before it is installed"); + let outputs = Outputs::new(&working, syncs(&oview, &log, 1, true), 1, &alloc, &outs).unwrap(); + assert_eq!(outputs.finish(Err(EBUSY)), Err(EBUSY)); + assert_eq!(taken(&log), [(EBUSY.to_errno(), 4)], "a failed SUBMIT's fence is counted before it is installed"); + assert_eq!(outs.count(), 4); + println!("PASS unpublished: allocation-failure and fallback fences counted before they are \ + installed (plain and cumulative outputs), malformed split uncounted"); + + // VM drop: both objects go, later failures still count but write nothing. + status.attach_mirror(gem::ObjectRef::new(&words, size, &drops), 16).unwrap(); + status.release_mirror(); + assert_eq!(drops.load(Ordering::SeqCst), 5, "VM drop releases the object"); + let after = run(&status, &None, &[Err(EIO)], None); + assert_eq!(after.seen().0, 5 + failures); + assert_eq!(words[1].load(Ordering::SeqCst), 4 + failures, "no store after release"); + assert_eq!(status.attach_fence_error_mirror(gem::ObjectRef::new(&words, size, &drops), 8), Err(ENOENT), + "no registration after VM drop"); + assert_eq!(status.attach_mirror(gem::ObjectRef::new(&words, size, &drops), 16), Err(ENOENT), + "no status mirror after VM drop"); + assert_eq!(drops.load(Ordering::SeqCst), 7, "refused registrations keep no reference"); + assert!(status.mirror.lock().status.is_none() && status.mirror.lock().fence_error_word.is_none(), + "a released status holds no object, so its last put sleeps nowhere"); + println!("PASS release: VM drop releases both objects, later errors counted but not stored, \ + no registration of either mirror after it"); +} +''' + +# (old, new, message the mutant must die with) +MEMBER_COUNT = (" self.status.count_fence_error();\n" + " fence.set_error(Error::from_errno(error));\n") +MEMBER_SET = " fence.set_error(Error::from_errno(error));\n" +FALLBACK_COUNT = (" self.status.count_fence_error();\n" + " fallback.set_error(error);\n") +FALLBACK_SET = " fallback.set_error(error);\n" +MUTATIONS = { + "count-after-signal": [ + (MEMBER_COUNT, MEMBER_SET), + (" unwaited(&fence.waited);", + " if error != 0 { self.status.count_fence_error(); }\n unwaited(&fence.waited);"), + ], "count-per-member-result": [ + (MEMBER_COUNT, MEMBER_SET), + (" self.note_error(error);\n", " self.note_error(error);\n self.status.count_fence_error();\n"), + ], "count-success-too": [ + (MEMBER_COUNT, MEMBER_SET), + (" let error = self.error.load(Ordering::Acquire);\n", + " let error = self.error.load(Ordering::Acquire);\n self.status.count_fence_error();\n"), + ], "registration-starts-at-zero": [ + (".store(mirrors.fence_errors, Ordering::Release);\n mirrors.fence_error_word", + ".store(0, Ordering::Release);\n mirrors.fence_error_word"), + ], "release-keeps-object": [ + ("mirrors.fence_error_word.take())", "None::>)"), + ], "registration-after-drop": [ + (" // As in attach_mirror: a registration racing with VM destruction is refused.\n" + " if self.client_closed() {\n return Err(ENOENT);\n }\n", ""), + ], "fallback-uncounted": [ + (FALLBACK_COUNT, FALLBACK_SET), + ], "fallback-counted-after-install": [ + (FALLBACK_COUNT, FALLBACK_SET), + (" trace::output(\n &fallback,", + " if self.result.is_err() { self.status.count_fence_error(); }\n" + " trace::output(\n &fallback,"), + ], "status-mirror-after-drop": [ + (" let mut mirrors = self.mirror.lock();\n if self.client_closed() {\n" + " return Err(ENOENT);\n }\n if mirrors.status.is_some() {", + " let mut mirrors = self.mirror.lock();\n if mirrors.status.is_some() {"), + ], "allocation-failure-uncounted": [ + (" status.count_fence_error();\n", ""), + ], +} +EXPECTED = { + "count-after-signal": "failed fence counted before it signals", + "count-per-member-result": "one count per failed fence", + "count-success-too": "success leaves the count", + "registration-starts-at-zero": "registration starts at the current count", + "release-keeps-object": "VM drop releases the object", + "registration-after-drop": "no registration after VM drop", + "fallback-uncounted": "a failed SUBMIT's fence is counted before it is installed", + "fallback-counted-after-install": "a failed SUBMIT's fence is counted before it is installed", + "allocation-failure-uncounted": "allocation failure counted before it is installed", + "status-mirror-after-drop": "no status mirror after VM drop", +} + + +def fixture(): + fence = (ROOT / "fence.rs").read_text() + status = (ROOT / "status.rs").read_text() + fence_methods = "\n".join(extract(fence, marker) for marker in [ + " fn note_error(&self, error: Error) -> bool {", " fn member_done("]) + fence_methods = fence_methods.replace("super::trace::", "trace::") + outputs = "\n".join([ + extract(fence, "fn install("), extract(fence, "pub(crate) struct Outputs {"), + "impl Outputs {", extract(fence, " pub(crate) fn new(\n contexts: &FenceContexts,"), + extract(fence, " pub(crate) fn finish(mut self"), "}", extract(fence, "impl Drop for Outputs {")]) + outputs = outputs.replace("super::trace::", "trace::").replace("super::sync_output::", "sync_output::") + items = "\n".join([line(status, "const MIRROR_MAX_SIZE"), extract(status, "struct Mirror {"), + line(status, "unsafe impl Send for Mirror"), extract(status, "struct Mirrors {"), + extract(status, "fn map_word(")]) + methods = "\n".join(extract(status, marker) for marker in [ + " pub(crate) fn count_fence_error(", " pub(crate) fn attach_fence_error_mirror(", + " pub(crate) fn release_mirror(", " pub(crate) fn mark_client_closed(", + " pub(crate) fn attach_mirror(", + " pub(crate) fn client_closed("]) + return (HARNESS.replace("__STATUS_ITEMS__", items).replace("__STATUS__", methods) + .replace("__FENCE__", fence_methods).replace("__OUTPUTS__", outputs)) + + +def build_and_run(work, name, source): + path = work / (name + ".rs") + path.write_text(source) + binary = work / name + built = subprocess.run([os.environ.get("RUSTC", "rustc"), "--edition=2021", "-O", "-Dwarnings", + str(path), "-o", str(binary)], capture_output=True, text=True) + if built.returncode: + raise RuntimeError(f"{name}: NOBUILD, not a runtime kill:\n{built.stderr}") + return subprocess.run([str(binary)], capture_output=True, text=True, timeout=120) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mutations", action="store_true") + args = parser.parse_args() + control = fixture() + with tempfile.TemporaryDirectory(prefix="asahi-g17-errcount-") as temporary: + work = Path(temporary) + ran = build_and_run(work, "control", control) + print(ran.stdout, end="") + if ran.returncode: + raise SystemExit("control failed:\n" + ran.stderr) + if args.mutations: + for name, changes in MUTATIONS.items(): + source = control + for old, new in changes: + if source.count(old) != 1: + raise RuntimeError(f"{name}: anchor count {source.count(old)}: {old!r}") + source = source.replace(old, new) + ran = build_and_run(work, name, source) + if ran.returncode == 0 or EXPECTED[name] not in ran.stderr: + raise SystemExit(f"{name}: did not die at '{EXPECTED[name]}':\n{ran.stdout}{ran.stderr}") + print(f"KILLED {name}: {EXPECTED[name]}") + print("PASS: G17 fence-error count") + + +if __name__ == "__main__": + main()