diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index ae25ebbd5255b..95971eaac3031 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -153,6 +153,7 @@ impl drm::driver::Driver for AsahiDrmDriver { /// Firmware interface selected by the hardware compatible. pub(crate) enum ProbeConfig { Legacy(&'static hw::HwConfig), + LegacyWithG14Handoff(&'static hw::HwConfig), G17(&'static g17::Config), /// M5 Pro, Max and Ultra: the ID registers select the configuration. G17M5, @@ -200,7 +201,7 @@ macro_rules! asahi_of_device_table { ), ( of::DeviceId::new(c"apple,agx-t8112"), - ProbeConfig::Legacy(&hw::t8112::HWCONFIG) + ProbeConfig::LegacyWithG14Handoff(&hw::t8112::HWCONFIG) ), ( of::DeviceId::new(c"apple,agx-t6000"), @@ -376,8 +377,9 @@ impl platform::Driver for AsahiPlatformDriver { dev_info!(pdev.as_ref(), "Probing...\n"); - let cfg = match info.ok_or(ENODEV)? { - ProbeConfig::Legacy(cfg) => *cfg, + let (cfg, has_g14_handoff) = match info.ok_or(ENODEV)? { + ProbeConfig::Legacy(cfg) => (*cfg, false), + ProbeConfig::LegacyWithG14Handoff(cfg) => (*cfg, true), ProbeConfig::G17(cfg) => { return AsahiPlatformDriver::probe_g17(pdev, regs::G17Resources::new(pdev)?, cfg) } @@ -391,16 +393,19 @@ impl platform::Driver for AsahiPlatformDriver { ProbeConfig::M5 => return Err(ENODEV), }; - // G14 with firmware 27.2 has its own root and start sequence (g14_v27_2.rs). - if (cfg.gpu_gen, cfg.gpu_variant) == (hw::GpuGen::G14, hw::GpuVariant::G) { - let version: Option> = pdev.as_ref().fwnode().ok_or(EIO)? - .property_read_array_vec(c"apple,firmware-version", 3)?.optional(); - if version.as_deref() == Some(&[27, 2, 0]) { - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] - return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg); - #[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))] - return Err(ENODEV); - } + let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; + let compat: KVec = fwnode + .property_read_array_vec(c"apple,firmware-compat", 3)? + .required_by(pdev.as_ref())?; + + // The loader advertises the supported wire layout independently of the image version. + if has_g14_handoff && compat.as_slice() == [27, 2, 0] { + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + return AsahiPlatformDriver::probe_g14_v27_2( + pdev, cfg, hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2, + ); + #[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))] + return Err(ENODEV); } // SAFETY: The selected SoC's UAT output width bounds all device DMA. @@ -414,11 +419,6 @@ impl platform::Driver for AsahiPlatformDriver { // Start the coprocessor CPU, so UAT can initialize the handoff regs::Resources::start_cpu(pdev)?; - let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; - let compat: KVec = fwnode - .property_read_array_vec(c"apple,firmware-compat", 3)? - .required_by(pdev.as_ref())?; - let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; // SAFETY: Every adapter calls close_binding in unbind before devres; // probe errors drop this local owner while the bound callback is live. @@ -503,9 +503,11 @@ impl AsahiPlatformDriver { fn probe_g14_v27_2<'bound>( pdev: &'bound platform::Device>, cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, ) -> Result> { let crate::g14_v27_2::Started { backend, drm, binding, resources } = - crate::g14_v27_2::start(pdev, cfg)?; + crate::g14_v27_2::start(pdev, cfg, registers, writable)?; let gpu = backend.clone() as Arc; let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources }); // SAFETY: The registration is stored in the platform data and unregistered when it is diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 773693a0cdfcb..b77cd15cc9a20 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -24,7 +24,7 @@ use kernel::{ platform, prelude::*, soc::apple::rtkit, - sync::{aref::ARef, Arc, ArcBorrow, CondVar, Mutex, SpinLock}, + sync::{aref::ARef, Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock}, time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, uapi, workqueue::{impl_has_work, OwnedQueue, Work, WorkItem}, @@ -211,14 +211,14 @@ pub(crate) struct Started<'a> { } /// Starts the firmware and retires the boot job. -pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'static hw::HwConfig) - -> Result> { +pub(crate) fn start<'a>( + pdev: &'a platform::Device>, + cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, +) -> Result> { use kernel::dma::{Device as _, DmaMask}; let dev: &device::Device = pdev.as_ref(); - let (registers, writable) = match cfg.chip_id { - 0x8112 => (hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2), - _ => return Err(ENODEV), - }; let geometry = mmu::UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas }; let mut window = mmu::FirmwareWindow::reserve(dev, geometry)?; let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?; @@ -299,6 +299,7 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta struct Inflight { packet: Arc, last: bool, + publication_error: Option, stamp: event::EventValue, slot: usize, /// Queue publications up to and including this command, counted from take-over. @@ -335,10 +336,26 @@ struct State { capacity: u32, inflight: KVec, pending: KVec<(Arc, usize)>, + accepting: bool, submitted: u64, retired: u64, } +impl State { + /// Stop publishing this packet. Report failure only once any published prefix retires. + fn fail_publication(&mut self, packet: &Arc, err: Error) { + let _ = self.pending.remove(0); + if let Some(last) = self.inflight.iter_mut().rev() + .find(|flight| Arc::ptr_eq(&flight.packet, packet)) + { + last.publication_error = Some(err); + } else { + packet.release_guard(); + packet.finish(Err(err)); + } + } +} + #[pin_data(PinnedDrop)] pub(crate) struct Runtime { dev: ARef, @@ -395,6 +412,8 @@ impl Runtime { } let mut guard = self.state.lock(); 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)?; self.pump(state); Ok(()) @@ -417,7 +436,9 @@ impl Runtime { self.healthy.store(false, Ordering::Release); self.idle.notify_all(); for (packet, _) in state.pending.drain(..) { - packet.release_guard(); + if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &packet)) { + packet.release_guard(); + } packet.finish(Err(error)); } // Published work stays owned: the firmware may still read it. @@ -447,7 +468,7 @@ impl Runtime { /// Publishes pending commands while pool slots are free. fn pump(&self, state: &mut State) { self.acknowledge(state); - if self.asleep.load(Ordering::Acquire) { return; } + if !self.healthy() || self.asleep.load(Ordering::Acquire) { return; } while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { // A slot is reused only once the firmware has unlinked it from its tracking list // (+0x94), which its retirement scan does after the slot's cursor is advanced. @@ -480,15 +501,16 @@ impl Runtime { let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); let Command::Compute(control) = packet.commands[index] else { // Queues of this backend accept only compute commands (Queue::submit). - let _ = state.pending.remove(0); - if !(packet.may_be_published() && index != 0) { packet.release_guard(); } - packet.finish(Err(EINVAL)); + state.fail_publication(&packet, EINVAL); continue; }; - let result = (|| -> Result<(mmu::VmBind, event::EventValue)> { + let slot = state.next_slot; + let stamp = state.last.next(); + let ordinal = state.published + 1; + let last = index + 1 == packet.commands.len(); + let result = (|| -> Result { let bind = self.graph.kernel_uat().bind(&packet.vm)?; let preempt = packet.preempt.as_ref().ok_or(EINVAL)?.gpu_va().get(); - let stamp = state.last.next(); let job = ComputeJob { context: bind.slot(), sequence: state.sequence, @@ -497,38 +519,32 @@ impl Runtime { usc_base: control.usc_base, preempt, }; - let command = state.pool.encode(state.next_slot, &state.queue, stamp.raw(), &job)?; + let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; + let publication = state.root.stage_compute(command)?; + state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, + publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; packet.mark_published(); - state.root.publish(command)?; - state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; - Ok((bind, stamp)) + publication.commit(); + Ok(()) })(); match result { - Ok((bind, stamp)) => { + Ok(()) => { state.last = stamp; state.sequence += 1; - let slot = state.next_slot; state.busy |= 1 << slot; - state.published += 1; - let ordinal = state.published; - state.next_slot = (state.next_slot + 1) % POOL_SLOTS; + state.published = ordinal; + state.next_slot = (slot + 1) % POOL_SLOTS; state.submitted += 1; - let last = index + 1 == packet.commands.len(); - if state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - started: Instant::now(), _bind: bind }, GFP_KERNEL).is_err() { - self.fail_all(state, ENOMEM); + if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } + if let Err(err) = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK) { + self.fail_all(state, err); return; } - if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } } + Err(EBUSY) if !state.inflight.is_empty() => return, Err(e) => { dev_err!(self.dev, "GPU: compute publication failed {:?}\n", e); - let _ = state.pending.remove(0); - // Earlier commands of a published packet fail it when they retire. - if !(packet.may_be_published() && index != 0) { - packet.release_guard(); - } - packet.finish(Err(e)); + state.fail_publication(&packet, e); } } } @@ -550,7 +566,11 @@ impl Runtime { let mut guard = self.state.lock(); let Some(state) = Option::as_mut(&mut *guard) else { return; }; self.service_locked(state); - if state.inflight.is_empty() && state.pending.is_empty() { self.idle.notify_all(); } + if state.inflight.is_empty() + && (state.pending.is_empty() || self.asleep.load(Ordering::Acquire)) + { + self.idle.notify_all(); + } } fn service_locked(&self, state: &mut State) { @@ -592,8 +612,15 @@ impl Runtime { } state.busy &= !(1 << done.slot); state.retired += 1; - if done.last { + if let Some(err) = done.publication_error { + done.packet.release_guard(); + done.packet.finish(Err(err)); + } else if done.last { done.packet.retired(); + } else if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &done.packet)) + && !state.pending.iter().any(|(packet, _)| Arc::ptr_eq(packet, &done.packet)) + { + done.packet.release_guard(); } } continue; @@ -624,7 +651,7 @@ impl Runtime { // Hold publications first, then let what is published retire. User space is frozen by // now; only the scheduler's queued jobs can still arrive, and they wait in `pending`. self.asleep.store(true, Ordering::Release); - let start = Instant::::now(); + let mut remaining = msecs_to_jiffies(STOP_DRAIN_MS); loop { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } @@ -633,15 +660,16 @@ impl Runtime { state.submitted, state.retired, state.pending.len()); return Ok(()); } - if start.elapsed() >= Delta::from_millis(STOP_DRAIN_MS.into()) { + if remaining == 0 { dev_err!(self.dev, "GPU: sleep refused, {} commands still running\n", state.inflight.len()); self.asleep.store(false, Ordering::Release); self.pump(state); return Err(EBUSY); } - // The service retires on notifications; `idle` is signalled only when nothing at all - // is left, so look again every 50 ms. - let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(50)); + remaining = match self.idle.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => jiffies, + _ => 0, + }; } } @@ -658,17 +686,20 @@ impl Runtime { /// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC /// with every mapping still in place (RTKit power-off if the firmware does not stop). pub(crate) fn stop(&self) { - // Let published work retire; the service signals `idle` when nothing is left. + // Close admission while the service retires work already accepted. { let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + state.accepting = false; let start = Instant::::now(); while self.healthy() && start.elapsed() < Delta::from_millis(STOP_DRAIN_MS.into()) { let Some(state) = guard.as_ref() else { break; }; if state.inflight.is_empty() && state.pending.is_empty() { break; } let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(STOP_DRAIN_MS)); } + // Serialize the last permitted publication with the transition to shutdown. + self.healthy.store(false, Ordering::Release); } - self.healthy.store(false, Ordering::Release); // Nothing queues service work after the detach, and none is queued or running once the // drain returns, so no work outlives the module. drop(self.notify.detach()); @@ -782,6 +813,7 @@ impl Backend { capacity, inflight: KVec::new(), pending: KVec::new(), + accepting: true, submitted: 0, retired: 0, }); diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 8db6c0ded49fd..37d09ac8a19be 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -358,6 +358,27 @@ impl CommandPool { } } +/// Ring contents prepared while the firmware still owns the old producer. +pub(crate) struct ComputePublication<'a> { + positions: &'a fw::types::GpuArray, + indices: &'a fw::types::GpuArray, + head: &'a core::sync::atomic::AtomicU32, + producer: &'a core::sync::atomic::AtomicU32, + next_head: u32, + next_producer: u32, +} + +impl ComputePublication<'_> { + pub(crate) fn commit(self) { + self.head.store(self.next_head, Ordering::Release); + crate::pgtable::clean_poc(self.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + self.producer.store(self.next_producer, Ordering::Release); + crate::pgtable::clean_poc(self.indices.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + } +} + /// The firmware 27.2 root and every record it names. pub(crate) struct RootV27_2 { graph: Arc, @@ -410,42 +431,50 @@ impl RootV27_2 { Ok((Self::word(&self.boot.positions, 0x40)?, Self::word(&self.boot.positions, 0)?)) } - /// Publishes `command` as the queue's next command: pointer, queue head, then the compute - /// submission entry and its producer. - pub(crate) fn publish(&self, command: u64) -> Result { + /// Prepares a work pointer and channel entry without advancing either producer. + pub(crate) fn stage_compute(&self, command: u64) -> Result> { let job = &self.boot; + let indices = &self.channels[2 * SUBMISSION_RING]; + let ring = &self.channels[2 * SUBMISSION_RING + 1]; + crate::pgtable::clean_invalidate_poc(job.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::clean_invalidate_poc(indices.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); let head = job.positions.shared_index(0x40)?; let old = head.load(Ordering::Acquire); let capacity = Self::word(&job.positions, 0x50)?; - if capacity == 0 || (old % capacity) as usize * 8 + 8 > job.pointers.as_slice().len() { - return Err(EINVAL); + let retired = Self::word(&job.positions, 0)?; + if capacity <= 1 || old >= capacity || retired >= capacity + || capacity as usize > job.pointers.len() / 8 + { + return Err(EIO); } - let at = (old % capacity) as usize * 8; + let next_head = (old + 1) % capacity; + if next_head == retired { return Err(EBUSY); } + + let producer = indices.shared_index(0x20)?; + let write = producer.load(Ordering::Acquire); + let read = Self::word(indices, 0)?; + let entries = crate::m3::m3_channel_format::SLOTS; + if write >= entries || read >= entries { return Err(EIO); } + let next_producer = (write + 1) % entries; + if next_producer == read { return Err(EBUSY); } + let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(COMPUTE as u32, job.queue.gpu_va().get(), + u16::try_from(next_head).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; + + let at = old as usize * 8; job.pointers.shared_index(at)?.store(command as u32, Ordering::Relaxed); job.pointers.shared_index(at + 4)?.store((command >> 32) as u32, Ordering::Relaxed); crate::pgtable::clean_poc(job.pointers.as_slice()[at..].as_ptr(), 8); - crate::pgtable::poc_barrier(); - let new = (old + 1) % capacity; - head.store(new, Ordering::Release); - crate::pgtable::clean_poc(job.positions.as_slice().as_ptr(), 0x60); - crate::pgtable::poc_barrier(); - let state = &self.channels[2 * SUBMISSION_RING]; - let ring = &self.channels[2 * SUBMISSION_RING + 1]; - let w = Self::word(state, 0x20)?; - if w >= crate::m3::m3_channel_format::SLOTS { return Err(EIO); } - let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; - let entry = crate::m3::submission_entry(COMPUTE as u32, job.queue.gpu_va().get(), - u16::try_from(new).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; - let base = w as usize * entry.len(); - for (k, word) in entry.chunks(4).enumerate() { - ring.shared_index(base + 4 * k)?.store(u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + let base = write as usize * entry.len(); + for (index, word) in entry.chunks_exact(4).enumerate() { + ring.shared_index(base + 4 * index)?.store( + u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); } crate::pgtable::clean_poc(ring.as_slice()[base..].as_ptr(), entry.len()); crate::pgtable::poc_barrier(); - state.shared_index(0x20)?.store((w + 1) % crate::m3::m3_channel_format::SLOTS, Ordering::Release); - crate::pgtable::clean_poc(state.as_slice().as_ptr(), 0x30); - crate::pgtable::poc_barrier(); - Ok(()) + Ok(ComputePublication { positions: &job.positions, indices, head, producer, + next_head, next_producer }) } /// Publishes the boot job, whose command and ring entry the root already holds. The GPU @@ -729,18 +758,11 @@ impl RootV27_2 { } for (i, state) in states.iter().enumerate() { let [mv] = state.volt_mv.as_slice() else { return Err(EINVAL); }; - let sram_mv = match &sram_table { - Some(table) => { - let (freq, voltage) = table[i * 8..i * 8 + 8].split_at(4); - if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz { - return Err(EINVAL); - } - let value = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); - if value < *mv || value > 1100 { return Err(EINVAL); } - value - } - None => (*mv).max(850), - }; + let (freq, voltage) = sram_table[i * 8..i * 8 + 8].split_at(4); + let sram_mv = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); + if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz || sram_mv < *mv || sram_mv == 0 { + return Err(EINVAL); + } let mhz = state.freq_hz / 1_000_000; for series in [abi::COMMON26_HW_PERF_FREQUENCY, 0x1924] { put32(hw, series + i * 4, mhz); @@ -882,8 +904,8 @@ impl RootV27_2 { } /// The loader's `adt-perf-states-sram` table under `/chosen/aurora-gpu-resources/sgx` - /// (frequency and SRAM millivolts per state), if it published one. The node itself must exist. - fn sram_table(states: usize) -> Result>> { + /// (frequency and SRAM millivolts per state). + fn sram_table(states: usize) -> Result> { let chosen = kernel::of::chosen().ok_or(ENODEV)?; let is = |name: Option>, want: &[u8]| { name.as_deref().is_some_and(|n| n.strip_suffix(b"\0").unwrap_or(n) == want) @@ -892,8 +914,9 @@ impl RootV27_2 { if !is(parent.get_opt_property::>(c"name")?, b"aurora-gpu-resources") { continue; } for child in parent.children() { if is(child.get_opt_property::>(c"name")?, b"sgx") { - let table = child.get_opt_property::>(c"adt-perf-states-sram")?; - if table.as_ref().is_some_and(|t| t.len() != states * 8) { return Err(EINVAL); } + let table = child.get_opt_property::>(c"adt-perf-states-sram")? + .ok_or(ENODEV)?; + if table.len() != states * 8 { return Err(EINVAL); } return Ok(table); } }