diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 2e683729d2261..2bbba9dfa8d45 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -50,6 +50,8 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { _reg: drm::Registration<'bound, AsahiDrmDriver>, /// The G17 GPU, whose coprocessors must be stopped when the driver is unbound. g17: Option>, + legacy: Option>, + asc: Option>, #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) g16: Option>, m3: Option, @@ -286,16 +288,19 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i if !deep { return 0; } - match data.g17.as_ref() { - Some(gpu) => kernel::error::from_result(|| gpu.sleep_prepare().map(|_| 0)), - None => { - // SAFETY: `dev` is a valid bound device for the duration of `prepare`. - dev_warn!( - unsafe { kernel::device::Device::::from_raw(dev) }, - "GPU: deep sleep refused, legacy firmware backend has no deep-sleep support\n" - ); - EBUSY.to_errno() - } + if let Some(gpu) = data.g17.as_ref() { + kernel::error::from_result(|| gpu.sleep_prepare().map(|_| 0)) + } else if let (Some(gpu), Some(asc)) = (data.legacy.as_ref(), data.asc.as_ref()) { + // The firmware stops only at the commit, which a dry run never reaches: its stop is + // registered all the same, since the sleep driver's checks look for it. + kernel::error::from_result(|| gpu.sleep_prepare(asc.cpu_control()).map(|_| 0)) + } else { + // SAFETY: `dev` is a valid bound device for the duration of `prepare`. + dev_warn!( + unsafe { kernel::device::Device::::from_raw(dev) }, + "GPU: deep sleep refused, legacy firmware backend has no deep-sleep support\n" + ); + EBUSY.to_errno() } } @@ -321,10 +326,14 @@ fn sleep_pd_init(dev: &kernel::device::Device>) -> Result { unsafe extern "C" fn sleep_suspend_noirq_driver( dev: *mut bindings::device, ) -> core::ffi::c_int { - #[cfg(any(CONFIG_DRM_ASAHI_G14_V27_2, CONFIG_DRM_ASAHI_M3_T8122))] // SAFETY: Called by the PM core with a bound GPU device. let data = unsafe { sleep_data(dev) }; - let hold_firmware = false; + if let Some(gpu) = data.legacy.as_ref() { + if let Err(e) = gpu.sleep_seal() { + return e.to_errno(); + } + } + let hold_firmware = data.legacy.as_ref().is_some_and(|gpu| gpu.sleep_holds_pd()); #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] let hold_firmware = hold_firmware || data.g14_v27_2 @@ -369,6 +378,8 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { } if let Some(gpu) = data.g17.as_ref() { gpu.sleep_complete(); + } else if let (Some(gpu), Some(asc)) = (data.legacy.as_ref(), data.asc.as_ref()) { + gpu.sleep_complete(&|| asc.start_cpu()); } } @@ -499,7 +510,8 @@ impl platform::Driver for AsahiPlatformDriver { resources.init_mmio()?; // Start the coprocessor CPU, so UAT can initialize the handoff - regs::Resources::start_cpu(pdev)?; + let asc = regs::AscControl::new(pdev)?; + asc.start_cpu(); let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; // SAFETY: Every adapter calls close_binding in unbind before devres; @@ -537,6 +549,7 @@ impl platform::Driver for AsahiPlatformDriver { let stats = gpu.stats_snapshot(); let debug_stats = gpu.raw_stats_snapshot(); + let legacy = Some(gpu.clone()); let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources }); // SAFETY: `reg` is stored in `AsahiPlatformDriverData` and dropped when the driver is @@ -565,6 +578,8 @@ impl platform::Driver for AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy, + asc: Some(asc), m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -610,6 +625,8 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, + asc: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, m3: None, @@ -655,6 +672,8 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, + asc: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -713,6 +732,8 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, + asc: None, m3: Some(backend), #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -796,6 +817,8 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: Some(gpu), + legacy: None, + asc: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -845,6 +868,8 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, + asc: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -887,6 +912,8 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, + asc: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, @@ -945,6 +972,8 @@ impl AsahiPlatformDriver { _device: reg.device().into(), _reg: reg, g17: None, + legacy: None, + asc: None, m3: None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 8da8a428ad72a..1b738a1c1970f 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -51,6 +51,7 @@ use kernel::{ UniqueArc, // }, time::{ + delay::fsleep, Delta, Instant, Monotonic, // @@ -124,6 +125,63 @@ const RX_WORK_RUNNING: u32 = 1 << 1; const MSG_TX_DOORBELL: u64 = 0x83 << 48; /// Firmware control channel doorbell. const MSG_FWCTL: u64 = 0x84 << 48; + +/// How long a system sleep waits for submitted GPU work to retire before refusing. +const SLEEP_DRAIN_MS: u32 = 1000; +/// ASC_CPU_CONTROL's run bit. +const ASC_RUN: u32 = 0x10; + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +#[allow(improper_ctypes)] +unsafe extern "C" { + fn apple_sleep_commit_stops_coprocs() -> bool; + fn apple_sleep_coproc_register_first( + dev: *mut kernel::bindings::device, + last_stop: Option core::ffi::c_int>, + data: *mut core::ffi::c_void, + ) -> core::ffi::c_int; + fn apple_sleep_coproc_set_ready(dev: *mut kernel::bindings::device, ready: bool); + fn apple_sleep_coproc_stopped(dev: *mut kernel::bindings::device) -> bool; + fn apple_sleep_coproc_wake_error(dev: *mut kernel::bindings::device) -> core::ffi::c_int; + fn apple_sleep_coproc_unregister(dev: *mut kernel::bindings::device); +} + +/// The legacy firmware's stop, run by the sleep driver's commit once every refusal is behind it. +pub(crate) struct SleepStop { + rtk: *mut kernel::bindings::apple_rtkit, + asc_ctl: *mut u8, + ran: bool, + idle_ret: core::ffi::c_int, + idle_us: u32, +} + +// SAFETY: Owned by `GpuManager::sleep_stop`; the commit callback touches it with interrupts off +// on the single boot CPU, and nothing else does until `sleep_complete()` unregisters it. +unsafe impl Send for SleepStop {} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +unsafe extern "C" fn legacy_commit_stop(data: *mut core::ffi::c_void) -> core::ffi::c_int { + // SAFETY: `data` is the `SleepStop` boxed in `GpuManager::sleep_stop` until + // `sleep_complete()` unregisters this callback. + let c = unsafe { &mut *data.cast::() }; + c.ran = true; + // SAFETY: `rtk` and `asc_ctl` stay mapped while the device is bound; this runs at the + // commit with interrupts off. + unsafe { + c.idle_ret = kernel::bindings::apple_rtkit_sleep_idle_polled( + c.rtk, + c.asc_ctl.cast(), + &mut c.idle_us, + ); + if c.idle_ret != 0 { + return c.idle_ret; + } + kernel::bindings::apple_rtkit_mailbox_recv_off(c.rtk); + let ctl = kernel::bindings::readl(c.asc_ctl.cast()); + kernel::bindings::writel(ctl & !ASC_RUN, c.asc_ctl.cast()); + } + 0 +} // /// Halt the firmware (?). // const MSG_HALT: u64 = 0x85 << 48; @@ -353,6 +411,12 @@ pub(crate) struct GpuManager { next_mmio_iova: u64, #[pin] rtkit: Mutex>>, + /// The firmware's stop, registered with the sleep driver for the commit of a deep sleep. + #[pin] + sleep_stop: Mutex>>, + /// The sleep passed this device's suspend_noirq: nothing may reach the firmware until + /// `sleep_complete()`. + sleep_sealed: AtomicBool, #[pin] rx_channels: Mutex, rx_work_state: AtomicU32, @@ -564,6 +628,21 @@ pub(crate) trait Gpu: Send + Sync { fn timestamp_window_size(&self) -> u64 { 0 } + /// Prepare the GPU firmware for a firmware-driven system sleep (S2R). `asc_ctl` is the + /// mapped ASC_CPU_CONTROL register. + fn sleep_prepare(&self, _asc_ctl: *mut u8) -> Result { + Err(EBUSY) + } + /// Called at suspend_noirq: refuses a sleep that work reached after the prepare. + fn sleep_seal(&self) -> Result { + Ok(()) + } + /// Whether the firmware runs until the sleep's commit, so its power domain must stay on. + fn sleep_holds_pd(&self) -> bool { + false + } + /// Restart or wake the GPU firmware after a system sleep. + fn sleep_complete(&self, _start_cpu: &dyn Fn()) {} } /// Trait used to abstract the firmware/GPU-dependent variants of the GpuManager. @@ -1155,6 +1234,8 @@ impl GpuManager::ver { io_mappings: KVec::new(), next_mmio_iova: IOVA_KERN_MMIO_RANGE.start, rtkit <- new_mutex!(None, "rtkit"), + sleep_stop <- new_mutex!(None, "sleep_stop"), + sleep_sealed: AtomicBool::new(false), crashed: AtomicBool::new(false), garbage_held: AtomicBool::new(false), event_manager, @@ -1657,10 +1738,36 @@ impl GpuManager::ver { self.rtkit.lock().is_some() } + /// Called with the RTKit lock held before any message to the firmware: once a deep sleep + /// is past suspend_noirq nothing is sent until `sleep_complete()`. + fn sleep_gate(&self, _rtk: Pin<&mut rtkit::RtKit>) -> Result { + if self.sleep_sealed.load(Ordering::Acquire) { + dev_warn!(self.dev.as_ref(), "s2r: GPU message during sleep refused\n"); + return Err(EBUSY); + } + Ok(()) + } + + /// The GPU's `struct device`, for the sleep driver's coprocessor registration. + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + fn raw_device(&self) -> *mut kernel::bindings::device { + let pdev: &kernel::platform::Device = self.dev.as_ref(); + let dev: &kernel::device::Device = pdev.as_ref(); + dev.as_raw() + } + + /// GPU operations started and not yet finished (the firmware's pending-submission count). + fn pending_ops(&self) -> u32 { + self.initdata + .globals + .with(|raw, _inner| raw.pending_submissions.load(Ordering::Acquire)) + } + /// Ring a doorbell on this manager's RTKit transport, or fail with ENODEV without one. fn ring_doorbell(&self, message: u64) -> Result { let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + let mut rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + self.sleep_gate(rtk.as_mut())?; rtk.send_message(EP_DOORBELL, message) } @@ -1672,7 +1779,8 @@ impl GpuManager::ver { msg: &fw::channels::DeviceControlMsg::ver, ) -> Result { let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + let mut rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + self.sleep_gate(rtk.as_mut())?; let token = txch.device_control.send(msg); rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; Ok(token) @@ -1854,6 +1962,168 @@ impl Gpu for GpuManager::ver { window.into_share(), ) } + + fn sleep_prepare(&self, asc_ctl: *mut u8) -> Result { + if self.is_crashed() { + dev_warn!( + self.dev.as_ref(), + "s2r: GPU firmware already crashed before sleep; skipping its stop\n" + ); + return Ok(()); + } + #[cfg(not(CONFIG_APPLE_SOC_SLEEP))] + { + let _ = asc_ctl; + Err(EBUSY) + } + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + { + // SAFETY: Reads the sleep driver's state: true where its commit stops coprocessors. + if !unsafe { apple_sleep_commit_stops_coprocs() } { + return Err(EBUSY); + } + // User space is frozen by now: let the work already submitted retire. + for _ in 0..SLEEP_DRAIN_MS / 5 { + if self.pending_ops() == 0 { + break; + } + fsleep(Delta::from_millis(5)); + } + let left = self.pending_ops(); + if left != 0 { + dev_warn!( + self.dev.as_ref(), + "s2r: sleep refused, {} GPU submissions still running\n", + left + ); + return Err(EBUSY); + } + let rtk = self.rtkit.lock().as_ref().ok_or(ENODEV)?.as_raw(); + let mut slot = self.sleep_stop.lock(); + *slot = Some(KBox::new( + SleepStop { + rtk, + asc_ctl, + ran: false, + idle_ret: 0, + idle_us: 0, + }, + GFP_KERNEL, + )?); + let data = slot.as_deref_mut().map_or(core::ptr::null_mut(), |c| { + core::ptr::from_mut(c).cast::() + }); + let dev = self.raw_device(); + // SAFETY: `dev` is the bound GPU device; `data` stays at the same address until + // `sleep_complete()` unregisters it. + let ret = + unsafe { apple_sleep_coproc_register_first(dev, Some(legacy_commit_stop), data) }; + if ret != 0 { + *slot = None; + return Err(Error::from_errno(ret)); + } + // SAFETY: `dev` was just registered. + unsafe { apple_sleep_coproc_set_ready(dev, true) }; + dev_info!( + self.dev.as_ref(), + "s2r: GPU firmware stops at the sleep commit\n" + ); + Ok(()) + } + } + + fn sleep_seal(&self) -> Result { + if self.sleep_stop.lock().is_none() { + return Ok(()); + } + let _guard = self.rtkit.lock(); + let left = self.pending_ops(); + if left != 0 { + dev_warn!( + self.dev.as_ref(), + "s2r: sleep refused, {} GPU submissions started after the prepare\n", + left + ); + return Err(EBUSY); + } + self.sleep_sealed.store(true, Ordering::Release); + Ok(()) + } + + fn sleep_holds_pd(&self) -> bool { + self.sleep_stop.lock().is_some() + } + + fn sleep_complete(&self, start_cpu: &dyn Fn()) { + self.sleep_sealed.store(false, Ordering::Release); + #[cfg(not(CONFIG_APPLE_SOC_SLEEP))] + let _ = start_cpu; + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + { + let Some(stop) = self.sleep_stop.lock().take() else { + return; + }; + let dev = self.raw_device(); + // SAFETY: `dev` is registered until the unregister below; `stop` outlives it. + let (stopped, wake_err) = unsafe { + let stopped = stop.ran || apple_sleep_coproc_stopped(dev); + let wake_err = apple_sleep_coproc_wake_error(dev); + apple_sleep_coproc_unregister(dev); + (stopped, wake_err) + }; + // SAFETY: Reads a global PM flag word. + let real = unsafe { kernel::bindings::pm_resume_via_firmware() }; + if !stopped { + dev_info!( + self.dev.as_ref(), + "s2r: sleep refused before the commit; GPU firmware kept running\n" + ); + return; + } + if stop.idle_ret != 0 || wake_err != 0 { + self.crashed.store(true, Ordering::Relaxed); + dev_err!( + self.dev.as_ref(), + "s2r: GPU firmware stop failed at the commit (idle {} wake {})\n", + stop.idle_ret, + wake_err + ); + return; + } + // The firmware was stopped at the commit: restart it, whether the sleep reached the + // hardware or was refused after the commit. + let res = { + let mut guard = self.rtkit.lock(); + match guard.as_mut().as_pin_mut() { + None => Err(ENODEV), + Some(mut rtk) => rtk.as_mut().warm_restart().and_then(|()| { + start_cpu(); + rtk.as_mut().boot() + }), + } + }; + match res { + Ok(()) => { + let kick = self.kick_firmware(); + dev_info!( + self.dev.as_ref(), + "s2r: GPU firmware restarted warm (real {}, idle {} us, kick {:?})\n", + real, + stop.idle_us, + kick + ); + } + Err(e) => { + self.crashed.store(true, Ordering::Relaxed); + dev_err!( + self.dev.as_ref(), + "s2r: GPU firmware warm restart failed: {:?}\n", + e + ); + } + } + } + } } #[versions(AGX)] @@ -2188,7 +2458,8 @@ impl GpuManager for GpuManager::ver { let mut fwctl = self.fwctl_channel.lock(); let token = { let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + let mut rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + self.sleep_gate(rtk.as_mut())?; let token = fwctl.send(&msg); rtk.send_message(EP_DOORBELL, MSG_FWCTL)?; token diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 0ce8eea67912f..9cdfdafe894c2 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -315,6 +315,35 @@ impl CpuControl { } } +/// Mapped ASC CPU control register for starting/restarting the legacy GPU coprocessor. +pub(crate) struct AscControl<'drm> { + mmio: IoMem<'drm, ASC_CTL_SIZE>, +} + +impl AscControl<'_> { + pub(crate) fn new<'bound>( + pdev: &'bound platform::Device>, + ) -> Result> { + let asc_req = pdev.io_request_by_name(c_str!("asc")).ok_or(EINVAL)?; + let mmio = asc_req.iomap_sized::()?; + Ok(AscControl { mmio }) + } + + /// The mapped ASC_CPU_CONTROL register, for the sleep driver's commit-time stop. + pub(crate) fn cpu_control(&self) -> *mut u8 { + let base = ::as_ptr(self.mmio.as_view()); + // SAFETY: ASC_CPU_CONTROL (0x44) lies within the ASC_CTL_SIZE mapping. + unsafe { base.cast::().add(0x44) } + } + + pub(crate) fn start_cpu(&self) { + self.mmio + .as_view() + .relaxed() + .update(ASC_CPU_CONTROL, |r| r.with_const_cpu_run::<1>()); + } +} + /// Device resources for this GPU instance. pub(crate) struct Resources<'drm> { dev: ARef, @@ -363,15 +392,6 @@ impl Resources<'_> { Ok(()) } - /// Start the ASC coprocessor CPU. - pub(crate) fn start_cpu(pdev: &platform::Device>) -> Result { - let asc_req = pdev.io_request_by_name(c_str!("asc")).ok_or(EINVAL)?; - let asc_mmio = asc_req.iomap_sized::()?; - let asc_mmio = asc_mmio.as_view().relaxed(); - asc_mmio.update(ASC_CPU_CONTROL, |r| r.with_const_cpu_run::<1>()); - Ok(()) - } - /// Get the GPU identification info from registers. /// /// See [`hw::GpuIdConfig`] for the result.