From 96c882e979f6ed78131750067c2c5ad616b5fce6 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 04:18:03 -0500 Subject: [PATCH 01/10] drm/asahi: G14 compute on GPU firmware 27.2 GPU firmware 27.2 on G14 (the M2's G14G) takes a new root: four opaque records (status, control, power, an extra block) after the UAT level descriptors, and a runtime directory of 26.x-style channels in place of the 13.5 RuntimePointers. Add that root as G14 V27_2 and a compute-only runtime on it. - fw/initdata.rs: the raw InitData and HwDataB layouts gain V27_2 (a new AGX_V27_2 version group instantiates only these two), with layout checks against 13.5. - gpu/v27_2.rs: builds the root on the records of a 13.5 G14 manager (GpuManager::build_graph with GraphProfile::G14V27_2, which maps no registers and keeps the private range below the 27.2 timestamp aperture): hardware data from the 13.5 values, the chip's 27.2 register table (hw/t8112.rs), the power and thermal controller, the idle-policy records, and one queue with a kernel-owned boot compute job. - g14_v27_2.rs: start sequence and runtime. The driver's kernel window is mirrored into the loader's shared second-level table and named in TTBAT context 0 (mmu::FirmwareWindow); the ASC is started, the GPU held powered and the boot job retired; clients then submit through the 26.x front end (m3_submit), each compute command re-encoded in the 27.2 layout from a 48-slot pool and published in order. Completion follows the queue's retired position. The firmware's event, statistics, log and trace rings are consumed as they fill. Render commands get EINVAL. - driver.rs: a G14G whose DT apple,firmware-version is 27.2.0 takes this path, before anything starts the coprocessor. There are no module parameters. Inputs come from the DT (operating points, power and thermal properties, apple,coredump-copy-buffer, the SRAM voltages the loader publishes, the UAT regions), the GPU's ID registers and the T8112 chip configuration. Unbind stops the firmware (allow-off, RTKit power-off if it does not stop, ASC halt) and keeps its memory for the rest of the boot. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/Makefile | 2 +- drivers/gpu/drm/asahi/asahi_core.rs | 2 + drivers/gpu/drm/asahi/driver.rs | 72 ++ drivers/gpu/drm/asahi/event.rs | 11 + drivers/gpu/drm/asahi/fw/initdata.rs | 56 +- drivers/gpu/drm/asahi/g14_v27_2.rs | 656 ++++++++++++ drivers/gpu/drm/asahi/g15/uat.rs | 2 +- drivers/gpu/drm/asahi/g17/fw/initdata.rs | 1 + drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs | 2 +- drivers/gpu/drm/asahi/g17/mod.rs | 19 +- drivers/gpu/drm/asahi/gpu.rs | 80 +- drivers/gpu/drm/asahi/gpu/v27_2.rs | 1009 +++++++++++++++++++ drivers/gpu/drm/asahi/hw/mod.rs | 24 + drivers/gpu/drm/asahi/hw/t8112.rs | 44 + drivers/gpu/drm/asahi/m3/m3_submit.rs | 73 +- drivers/gpu/drm/asahi/m3/mod.rs | 14 +- drivers/gpu/drm/asahi/mmu.rs | 139 +++ drivers/gpu/drm/asahi/object.rs | 17 + drivers/gpu/drm/asahi/regs.rs | 7 + drivers/gpu/drm/asahi/rtkit_dump.c | 19 + rust/macros/versions.rs | 12 +- 21 files changed, 2207 insertions(+), 54 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g14_v27_2.rs create mode 100644 drivers/gpu/drm/asahi/gpu/v27_2.rs create mode 100644 drivers/gpu/drm/asahi/rtkit_dump.c diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index 24341a6f3abce..a356bb326d245 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -8,4 +8,4 @@ aurora-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o -aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o +aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o rtkit_dump.o diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b970691651032..5f180203f8369 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -27,6 +27,8 @@ mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; mod gpu; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +mod g14_v27_2; mod hw; mod initdata; mod m3; diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 77ffd32891cd2..1526566cf68a5 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -53,6 +53,9 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) g16: Option>, m3: Option, + /// The G14 firmware-27.2 backend, whose firmware must be stopped on unbind. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: Option>, /// Raw `struct device *` of the platform device. Stored once at probe /// time so the `Drop` impl can find the sysfs file on unregister. raw_dev: *mut bindings::device, @@ -337,6 +340,10 @@ impl platform::Driver for AsahiPlatformDriver { if let Some(m3) = this.m3.as_ref() { m3.stop(); } + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = this.g14_v27_2.as_ref() { + backend.stop(); + } this.close_binding(); } @@ -368,6 +375,18 @@ 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); + } + } + // SAFETY: The selected SoC's UAT output width bounds all device DMA. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; @@ -449,6 +468,8 @@ impl platform::Driver for AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -461,6 +482,41 @@ impl platform::Driver for AsahiPlatformDriver { } impl AsahiPlatformDriver { + /// G14 with firmware 27.2: start the firmware and register a compute-only DRM device. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + fn probe_g14_v27_2<'bound>( + pdev: &'bound platform::Device>, + cfg: &'static hw::HwConfig, + ) -> Result> { + let crate::g14_v27_2::Started { backend, drm, binding, resources } = + crate::g14_v27_2::start(pdev, cfg)?; + 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 + // dropped, after the backend has stopped the firmware. + let reg = match unsafe { drm::Registration::new(pdev.as_ref(), drm, data, 0) } { + Ok(reg) => reg, + Err(error) => { + backend.stop(); + return Err(error); + } + }; + dev_info!(pdev.as_ref(), "G14 firmware 27.2 running; compute-only DRM device registered\n"); + Ok(AsahiPlatformDriverData { + binding, + _device: reg.device().into(), + _reg: reg, + g17: None, + #[cfg(CONFIG_DRM_ASAHI_G16)] + g16: None, + m3: None, + g14_v27_2: Some(backend), + raw_dev: core::ptr::null_mut(), + raw_stats: core::ptr::null_mut(), + stats: None, + }) + } + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn probe_g15<'bound>( pdev: &'bound platform::Device>, @@ -487,6 +543,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -529,6 +587,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: Some(backend), + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, raw_dev: core::ptr::null_mut(), raw_stats: core::ptr::null_mut(), stats: None, @@ -605,6 +665,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: Some(gpu), m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -652,6 +714,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -691,6 +755,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, g16: Some(gpu), raw_dev, raw_stats, @@ -747,6 +813,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -780,5 +848,9 @@ impl Drop for AsahiPlatformDriverData<'_> { if let Some(m3) = self.m3.as_ref() { m3.stop(); } + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = self.g14_v27_2.as_ref() { + backend.stop(); + } } } diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index edd7d701e665c..a993bca69f507 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -54,6 +54,11 @@ pub(crate) type Event = slotalloc::Guard; pub(crate) struct EventValue(u32); impl EventValue { + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + pub(crate) fn raw(self) -> u32 { + self.0 + } + /// Returns the `EventValue` that succeeds this one. pub(crate) fn next(&self) -> EventValue { EventValue(self.0.wrapping_add(0x100)) @@ -199,6 +204,12 @@ impl EventManager { Ok(ev) } + /// Reserve the normal stamp pair for a kernel queue that polls its own completion. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + pub(crate) fn try_get_polled(&self) -> Result { + self.alloc.try_get(None) + } + /// Signals an event by slot, indicating completion (of one or more commands). pub(crate) fn signal(&self, slot: u32) { match self diff --git a/drivers/gpu/drm/asahi/fw/initdata.rs b/drivers/gpu/drm/asahi/fw/initdata.rs index 7c7488e950ace..7c7e3cfe45eb0 100644 --- a/drivers/gpu/drm/asahi/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/fw/initdata.rs @@ -637,7 +637,7 @@ pub(crate) mod raw { pub(crate) afr_unkpad: u32, } - #[versions(AGX)] + #[versions(AGX_V27_2)] #[derive(Debug)] #[repr(C)] pub(crate) struct HwDataB { @@ -663,10 +663,15 @@ pub(crate) mod raw { pub(crate) yuv_matrices: Array<0x3f, Array<3, Array<4, i16>>>, pub(crate) pad_1c8: Pad<0x8>, + #[ver(V < V27_2)] pub(crate) io_mappings: Array, + #[ver(V >= V27_2)] + pub(crate) io_mappings: Array<60, crate::g17::fw::initdata::RegisterMapEntry>, #[ver(V >= V13_0B4)] pub(crate) sgx_sram_ptr: U64, + #[ver(V >= V27_2)] + pub(crate) coredump_copy_buffer_size: U64, pub(crate) chip_id: u32, pub(crate) unk_454: u32, @@ -835,7 +840,7 @@ pub(crate) mod raw { #[ver(V >= V13_0B4)] pub(crate) unk_c3c: u32, } - #[versions(AGX)] + #[versions(AGX_V27_2)] default_zeroed!(HwDataB::ver); #[derive(Debug)] @@ -1243,7 +1248,7 @@ pub(crate) mod raw { pub(crate) index_mask: U64, } - #[versions(AGX)] + #[versions(AGX_V27_2)] #[derive(Debug)] #[repr(C)] pub(crate) struct InitData<'a> { @@ -1253,20 +1258,65 @@ pub(crate) mod raw { pub(crate) unk_buf: GpuPointer<'a, &'a [u8]>, pub(crate) unk_8: u32, pub(crate) unk_c: u32, + #[ver(V < V27_2)] pub(crate) runtime_pointers: GpuPointer<'a, super::RuntimePointers::ver>, + #[ver(V < V27_2)] pub(crate) globals: GpuPointer<'a, super::Globals::ver>, + #[ver(V < V27_2)] pub(crate) fw_status: GpuPointer<'a, super::FwStatus>, + // From 27.2 the root names opaque records; their layouts live with the 27.2 builder. + #[ver(V >= V27_2)] + pub(crate) runtime_pointers: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) globals: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) role: u32, + #[ver(V >= V27_2)] + pub(crate) host_mapped_fw_allocations: u32, pub(crate) uat_page_size: u16, pub(crate) uat_page_bits: u8, pub(crate) uat_num_levels: u8, pub(crate) uat_level_info: Array<0x3, UatLevelInfo>, pub(crate) __pad0: Pad<0x14>, + #[ver(V < V27_2)] pub(crate) host_mapped_fw_allocations: u32, + #[ver(V < V27_2)] pub(crate) unk_ac: u32, + #[ver(V < V27_2)] pub(crate) unk_b0: u32, + #[ver(V < V27_2)] pub(crate) unk_b4: u32, + #[ver(V < V27_2)] pub(crate) unk_b8: u32, + #[ver(V >= V27_2)] + pub(crate) status_record: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) control: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) power: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) extra: GpuPointer<'a, &'a [u8]>, } + + // Layout checks for the firmware 27.2 root and hardware data against the 13.5 layout. + const _: () = { + // T8112's older layout locates its optional SRAM pointer after 25 IO records. + assert!(core::mem::offset_of!(HwDataBG14V13_5, io_mappings) == 0x640); + assert!(core::mem::size_of::() == 0x20); + assert!(core::mem::offset_of!(HwDataBG14V13_5, sgx_sram_ptr) == 0x960); + assert!(core::mem::offset_of!(HwDataBG14V27_2, io_mappings) == 0x640); + assert!(core::mem::offset_of!(HwDataBG14V27_2, sgx_sram_ptr) == 0xfa0); + assert!(core::mem::offset_of!(HwDataBG14V27_2, coredump_copy_buffer_size) == 0xfa8); + assert!(core::mem::offset_of!(HwDataBG14V27_2, chip_id) == 0xfb0); + type Root = InitDataG14V27_2<'static>; + assert!(core::mem::offset_of!(Root, ver_info) == 0); + assert!(core::mem::offset_of!(Root, role) == 0x28); + assert!(core::mem::offset_of!(Root, host_mapped_fw_allocations) == 0x2c); + assert!(core::mem::offset_of!(Root, uat_level_info) == 0x34); + assert!(core::mem::offset_of!(Root, status_record) == 0xa8); + assert!(core::mem::offset_of!(Root, extra) == 0xc0); + assert!(core::mem::size_of::() == 0xc8); + }; } #[derive(Debug)] diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs new file mode 100644 index 0000000000000..ea585628b1e4f --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -0,0 +1,656 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G14 GPUs on GPU firmware 27.2: start the firmware and run compute work on it. +//! +//! [`start`] builds the 27.2 root (`gpu/v27_2.rs`) on the records of a 13.5 G14 manager, +//! installs the driver's kernel window in the loader's UAT regions, starts the ASC, holds the +//! GPU powered and retires one kernel-owned compute job. [`Backend`] then serves clients +//! through the 26.x submission front end (`m3_submit`): each compute command is encoded in the +//! 27.2 layout and published, in order, on the root's queue. Render commands are refused. +//! +//! Completion follows the queue's retired position, which the firmware advances in order. +//! The firmware's event, statistics, log and trace rings are consumed as they fill, since +//! the firmware waits for space in them. + +use core::ops::Range; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +use kernel::{ + device, + drm::sched, + new_delayed_work, new_mutex, + platform, + prelude::*, + soc::apple::rtkit, + sync::{aref::ARef, Arc, Mutex}, + time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, + uapi, + workqueue::{self, impl_has_delayed_work, DelayedWork, WorkItem}, +}; + +use crate::{ + alloc, event, gem, + gpu::{self, CommandPool, ComputeJob, GpuManagerG14V13_5, QueueInfo, RootV27_2, POOL_SLOTS}, + hw, mmu, queue, + m3::m3_submit::{Command, Packet}, +}; + +/// RTKit endpoints of the GPU firmware. +const EP_FIRMWARE: u8 = 0x20; +const EP_DOORBELL: u8 = 0x21; + +/// ASC CPU control register and its run bit. +const ASC_CPU_CONTROL: usize = 0x44; +const ASC_RUN: u32 = 0x10; + +/// Commands slower than this are a hang; the firmware state is then not trusted. +const COMMAND_TIMEOUT_MS: i64 = 5000; +/// Idle polling keeps the firmware's rings drained and bounds completion latency. +const IDLE_POLL_MS: u64 = 20; + +/// The ASC control page, kept mapped until the firmware is stopped. +pub(crate) struct AscControl(*mut u8); +// SAFETY: a device register page; accesses are single 32-bit MMIO operations. +unsafe impl Send for AscControl {} +// SAFETY: as above. +unsafe impl Sync for AscControl {} + +impl AscControl { + fn new(phys: u64) -> Result { + // SAFETY: `phys` is the ASC register window of this platform device. + let ptr = unsafe { kernel::bindings::ioremap(phys, 0x4000) }; + if ptr.is_null() { return Err(ENOMEM); } + Ok(Self(ptr.cast())) + } + fn read(&self, at: usize) -> u32 { + // SAFETY: `at` is a register offset inside the mapped page. + unsafe { kernel::bindings::readl(self.0.add(at).cast()) } + } + fn write(&self, at: usize, value: u32) { + // SAFETY: as above. + unsafe { kernel::bindings::writel(value, self.0.add(at).cast()) } + } + /// Clears the ASC run bit. + fn halt(&self) { + self.write(ASC_CPU_CONTROL, self.read(ASC_CPU_CONTROL) & !ASC_RUN); + } +} + +impl Drop for AscControl { + fn drop(&mut self) { + // SAFETY: mapped in `new`, unmapped once. + unsafe { kernel::bindings::iounmap(self.0.cast()) } + } +} + +/// RTKit operations of the GPU firmware: its crash log lives in the loader's data segment. +pub(crate) struct Firmware; + +#[vtable] +impl rtkit::Operations for Firmware { + type Data = Arc>; + type Buffer = crate::g17::CrashLog; + + const COPROC_PLACES_BUFFERS: bool = true; + + fn shmem_map(dev: kernel::sync::ArcBorrow<'_, ARef>, iova: usize, size: usize) -> Result { + crate::g17::CrashLog::from_firmware(&dev, iova, size) + } + + fn crashed(dev: kernel::sync::ArcBorrow<'_, ARef>, log: Option<&[u8]>) { + unsafe extern "C" { + fn asahi_save_rtkit_dump(dev: *mut core::ffi::c_void, data: *const u8, size: usize); + } + dev_err!(&**dev, "GPU firmware crashed\n"); + if let Some(log) = log { + // SAFETY: RTKit and the device remain live throughout this synchronous copy. + unsafe { asahi_save_rtkit_dump(dev.as_raw().cast(), log.as_ptr(), log.len()) }; + } + } + + fn recv_message(_dev: kernel::sync::ArcBorrow<'_, ARef>, _ep: u8, _message: u64) {} +} + +type Peer = Pin>>; + +/// Polls `done` every millisecond, draining the firmware's rings, for at most `ms`. +fn wait(root: &RootV27_2, ms: i64, mut done: impl FnMut() -> Result) -> Result { + let start = Instant::::now(); + loop { + if done()? { return Ok(()); } + if start.elapsed() >= Delta::from_millis(ms) { return Err(ETIMEDOUT); } + let _ = root.drain(); + fsleep(Delta::from_millis(1)); + } +} + +/// Publishes an idle-policy record and waits until the firmware has consumed and +/// acknowledged it. +fn set_idle_policy(root: &RootV27_2, peer: &mut Peer, allow_off: bool) -> Result { + let (target, generation) = root.publish_idle_policy(allow_off)?; + peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK)?; + wait(root, 500, || Ok(root.idle_progress()? == [target; 3] && root.idle_acknowledgement()? == generation)) +} + +/// Stops firmware that no runtime owns: allow power-off, then RTKit power-off, then the ASC +/// run bit. Everything it could reach is kept for the rest of the boot. +fn halt_unowned(dev: &device::Device, mut peer: Peer, root: crate::fw::types::GpuObject, + asc: AscControl, booted: bool) { + if booted { + let allowed = set_idle_policy(&root, &mut peer, true); + // SAFETY: the RTKit instance is live and owned here. + let off = kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(peer.as_raw()) }); + dev_err!(dev, "GPU firmware halted: allow-off={:?} power-off={:?}\n", allowed, off); + } + asc.halt(); + core::mem::forget(peer); + core::mem::forget(root); + core::mem::forget(asc); +} + +/// A started 27.2 GPU, ready for DRM registration. +pub(crate) struct Started<'a> { + pub(crate) backend: Arc, + pub(crate) drm: kernel::drm::UnregisteredDevice, + pub(crate) binding: crate::binding::Owner, + pub(crate) resources: crate::regs::Resources<'a>, +} + +/// Starts the firmware and retires the boot job. +pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'static hw::HwConfig) + -> 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())?; + let control = asc.read(ASC_CPU_CONTROL); + if control & ASC_RUN != 0 { return Err(EBUSY); } + let mut peer = KBox::pin( + rtkit::RtKit::::new(dev, None, 0, Arc::new(ARef::from(dev), GFP_KERNEL)?)?, + GFP_KERNEL)?; + let resources = crate::regs::Resources::new(pdev)?; + let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; + let copy_bytes: u32 = dev.fwnode().ok_or(ENODEV)? + .property_read(c"apple,coredump-copy-buffer").required_by(dev)?; + let board = gpu::BoardV27_2 { + sgx: sgx.start(), sgx_size: sgx.size() as u64, copy_bytes, registers, writable, + }; + + // SAFETY: the mask is the UAT's physical width. + unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(geometry.oas)?)? }; + let drm = kernel::drm::UnregisteredDevice::::new(pdev, Ok(()))?; + // SAFETY: the unregistered DRM instance is private to this bound probe. + let binding = unsafe { crate::binding::Owner::new(pdev.as_ref(), &drm)? }; + let uat = mmu::Uat::new_adopted(&drm, geometry, &window.regions())?; + let graph = GpuManagerG14V13_5::build_graph(&drm, &resources, cfg, KBox::new(uat, GFP_KERNEL)?, + gpu::GraphProfile::G14V27_2)?; + let root = RootV27_2::build(&graph, &board)?; + let pool = CommandPool::new(&mut gpu::GpuManager::alloc(&*graph), cfg)?; + window.mirror(graph.kernel_uat())?; + window.install()?; + window.announce(); + asc.write(ASC_CPU_CONTROL, control | ASC_RUN); + + // From here the firmware may read everything the window names: nothing is freed. + let mut booted = false; + let result = (|| -> Result { + let start = Instant::::now(); + while !window.answered() { + if start.elapsed() >= Delta::from_millis(1000) { return Err(ETIMEDOUT); } + fsleep(Delta::from_millis(1)); + } + peer.as_mut().boot()?; + booted = true; + peer.as_mut().start_endpoint(EP_FIRMWARE)?; + peer.as_mut().start_endpoint(EP_DOORBELL)?; + if !window.intact() { return Err(EIO); } + peer.as_mut().send_message(EP_FIRMWARE, gpu::init_message(root.gpu_va().get()))?; + // Let initialization settle before the first control record. + let _ = wait(&root, 1000, || Ok(false)); + set_idle_policy(&root, &mut peer, false)?; + // Command-handler installation completes during powered initialization. + let _ = wait(&root, 500, || Ok(root.command_service()? == (2, 0))); + root.publish_boot_job(resources.operating_point())?; + peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + wait(&root, 3000, || root.boot_job_complete()) + })(); + if let Err(e) = result { + dev_err!(dev, "GPU firmware 27.2 did not start: {:?}\n", e); + halt_unowned(dev, peer, root, asc, booted); + core::mem::forget(window); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + // The firmware keeps using the window until it is stopped; it stays for the life of the boot. + core::mem::forget(window); + let backend = Backend::start(&drm, dev, peer, root, graph, pool, asc, cfg)?; + Ok(Started { backend, drm, binding, resources }) +} + +struct Inflight { + packet: Arc, + last: bool, + stamp: event::EventValue, + slot: usize, + /// Queue publications up to and including this command, counted from take-over. + ordinal: u64, + started: Instant, + _bind: mmu::VmBind, +} + +struct State { + peer: Peer, + root: crate::fw::types::GpuObject, + pool: CommandPool, + asc: AscControl, + queue: QueueInfo, + last: event::EventValue, + sequence: u64, + next_slot: usize, + waiting_unlink: bool, + /// Publications and retirements counted on the queue's position block. + published: u64, + retired_total: u64, + retired_raw: u32, + capacity: u32, + inflight: KVec, + pending: KVec<(Arc, usize)>, + submitted: u64, + retired: u64, +} + +#[pin_data(PinnedDrop)] +pub(crate) struct Runtime { + dev: ARef, + graph: Arc, + healthy: AtomicBool, + /// Poll work queued or running; `stop` waits for zero so no work outlives the module. + queued: AtomicU32, + #[pin] + state: Mutex>, + #[pin] + poll: DelayedWork, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Runtime { self.poll } +} + +impl WorkItem for Runtime { + type Pointer = Arc; + fn run(this: Arc) { + let busy = this.service(); + if this.healthy.load(Ordering::Acquire) { + this.schedule(if busy { 1 } else { IDLE_POLL_MS }); + } + this.queued.fetch_sub(1, Ordering::AcqRel); + } +} + +#[pinned_drop] +impl PinnedDrop for Runtime { + fn drop(self: Pin<&mut Self>) { + // The poll work holds a reference while scheduled, so this runs only once the + // runtime is idle; stop the firmware first if no one has. + if self.state.lock().is_some() { self.stop(); } + } +} + +impl Runtime { + fn schedule(self: &Arc, ms: u64) { + if !self.healthy() { return; } + self.queued.fetch_add(1, Ordering::AcqRel); + if workqueue::system_highpri() + .enqueue_delayed::, 0>(self.clone(), msecs_to_jiffies(ms as u32)).is_err() { + // Already queued: that run accounts for itself. + self.queued.fetch_sub(1, Ordering::AcqRel); + } + } + + pub(crate) fn healthy(&self) -> bool { self.healthy.load(Ordering::Acquire) } + + /// Queues a packet; the poll work publishes and retires it. + pub(crate) fn submit(self: &Arc, packet: Arc) -> Result { + if !self.healthy() { return Err(EIO); } + if packet.commands.is_empty() { + return Err(ENOTSUPP); + } + { + let mut guard = self.state.lock(); + let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + state.pending.push((packet, 0), GFP_KERNEL)?; + self.pump(state); + } + self.schedule(1); + Ok(()) + } + + /// Withdraws a packet's unpublished commands; published ones retire normally. + pub(crate) fn withdraw(&self, packet: &Arc) { + let mut guard = self.state.lock(); + if let Some(state) = Option::as_mut(&mut *guard) { + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + if !state.inflight.iter().any(|f| Arc::ptr_eq(&f.packet, packet)) { + packet.release_guard(); + } + } + } + + fn fail_all(&self, state: &mut State, error: Error) { + self.healthy.store(false, Ordering::Release); + for (packet, _) in state.pending.drain(..) { + packet.release_guard(); + packet.finish(Err(error)); + } + // Published work stays owned: the firmware may still read it. + for f in state.inflight.iter() { + if let Some(status) = f.packet.vm.status() { status.record(error); } + f.packet.finish(Err(error)); + } + } + + /// Publishes pending commands while pool slots are free. + fn pump(&self, state: &mut State) { + 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. + match state.pool.registered(state.next_slot) { + Ok(false) => {} + Ok(true) => { + if !state.waiting_unlink { + // Wake the firmware's service once so its retirement scan runs. + state.waiting_unlink = true; + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK); + } + return; + } + Err(e) => { self.fail_all(state, e); return; } + } + state.waiting_unlink = false; + 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)); + continue; + }; + let result = (|| -> Result<(mmu::VmBind, event::EventValue)> { + 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, + cdm_base: control.base, + cdm_end: control.end, + usc_base: control.usc_base, + preempt, + }; + let command = state.pool.encode(state.next_slot, &state.queue, stamp.raw(), &job)?; + packet.mark_published(); + state.root.publish(command)?; + state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + Ok((bind, stamp)) + })(); + match result { + Ok((bind, stamp)) => { + state.last = stamp; + state.sequence += 1; + let slot = state.next_slot; + state.published += 1; + let ordinal = state.published; + state.next_slot = (state.next_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); + return; + } + if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } + } + 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)); + } + } + } + } + + /// Retires completed commands, publishes more and keeps the firmware's rings drained. + /// Returns whether work remains. + fn service(&self) -> bool { + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return false; }; + let _ = state.root.drain(); + if state.peer.is_crashed() { + dev_err!(self.dev, "GPU firmware crashed; failing {} pending and {} published commands\n", + state.pending.len(), state.inflight.len()); + self.fail_all(state, EIO); + return false; + } + let raw = match state.root.progress() { + Ok((_, raw)) => raw, + Err(e) => { self.fail_all(state, e); return false; } + }; + if state.capacity != 0 && raw < state.capacity { + let delta = (raw + state.capacity - state.retired_raw) % state.capacity; + state.retired_total += u64::from(delta); + state.retired_raw = raw; + } + while !state.inflight.is_empty() { + let front = &state.inflight[0]; + if state.retired_total >= front.ordinal { + if let Ok(done) = state.inflight.remove(0) { + if let Err(e) = state.pool.retire(done.slot) { + dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); + } + state.retired += 1; + if done.last { + done.packet.retired(); + } + } + continue; + } + if front.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", + state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); + self.fail_all(state, ETIMEDOUT); + return false; + } + break; + } + if self.healthy() { self.pump(state); } + !state.inflight.is_empty() || !state.pending.is_empty() + } + + /// 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 start = Instant::::now(); + while start.elapsed() < Delta::from_millis(2000) { + if !self.service() { break; } + fsleep(Delta::from_millis(1)); + } + self.healthy.store(false, Ordering::Release); + // No poll work may remain queued or running once this returns. + let start = Instant::::now(); + while self.queued.load(Ordering::Acquire) != 0 && start.elapsed() < Delta::from_millis(2000) { + fsleep(Delta::from_millis(5)); + } + // Let a run that just accounted for itself return out of this module. + fsleep(Delta::from_millis(20)); + let mut guard = self.state.lock(); + let Some(mut state) = guard.take() else { return; }; + self.fail_all(&mut state, ENODEV); + let allowed = set_idle_policy(&state.root, &mut state.peer, true); + let root = &state.root; + let _ = wait(root, 500, || Ok(root.firmware_running()? == 0)); + let running = root.firmware_running(); + let forced = (running != Ok(0)).then(|| { + // SAFETY: the RTKit instance is live and owned here. + kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) + }); + state.asc.halt(); + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={}\n", + allowed, running, forced, state.submitted, state.retired); + if running != Ok(0) && forced != Some(Ok(())) { + dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); + } + // Keep everything the firmware could reach for the rest of the boot, halted or not: + // its page tables still name these pages. + core::mem::forget(state); + core::mem::forget(self.graph.clone()); + } +} + +impl State { + fn queue_stamp(&self) -> u32 { + self.root.queue().1.raw() + } +} + +pub(crate) struct Backend { + graph: Arc, + runtime: Arc, + scheduler: Arc>, + ids: gpu::SequenceIDs, + preempt_bytes: usize, +} + +impl Backend { + /// Takes over the running firmware after the boot job. + #[allow(clippy::too_many_arguments)] + fn start( + drm: &crate::driver::AsahiDrmDevice, + dev: &device::Device, + peer: Peer, + root: crate::fw::types::GpuObject, + graph: Arc, + pool: CommandPool, + asc: AscControl, + cfg: &'static hw::HwConfig, + ) -> Result> { + // The runtime is created empty first, so no allocation failure can drop firmware-visible + // state. Every failure after the state is moved in goes through Runtime::stop, which + // halts the firmware and keeps all of its memory. + let runtime_graph = graph.clone(); + let runtime = match Arc::pin_init(try_pin_init!(Runtime { + dev: dev.into(), + graph: runtime_graph, + healthy: AtomicBool::new(true), + queued: AtomicU32::new(0), + state <- new_mutex!(None, "g14_v27_2::Runtime::state"), + poll <- new_delayed_work!("g14_v27_2::Runtime::poll"), + }), GFP_KERNEL) { + Ok(runtime) => runtime, + Err(e) => { + halt_unowned(dev, peer, root, asc, true); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + let (queue, last) = root.queue(); + let checked = (|| -> Result<(u32, u32)> { + let (head, retired) = root.progress()?; + if head != retired { return Err(EBUSY); } + Ok((head, root.capacity()?)) + })(); + let (head, capacity) = match checked { + Ok(v) => v, + Err(e) => { + halt_unowned(dev, peer, root, asc, true); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + *runtime.state.lock() = Some(State { + peer, root, pool, asc, queue, last, + sequence: u64::from(head), + next_slot: 0, + waiting_unlink: false, + published: 0, + retired_total: 0, + retired_raw: head, + capacity, + inflight: KVec::new(), + pending: KVec::new(), + submitted: 0, + retired: 0, + }); + runtime.schedule(IDLE_POLL_MS); + // One run queue per DRM scheduler priority (the front end maps queue priorities 0-3). + let scheduler = match sched::Scheduler::new(drm.as_ref().as_ref(), 4, POOL_SLOTS as u32 - 1, 0, 10000, + c"asahi_g14_sched").and_then(|s| Arc::new(s, GFP_KERNEL).map_err(Into::into)) { + Ok(scheduler) => scheduler, + Err(e) => { + runtime.stop(); + return Err(e); + } + }; + let preempt_bytes = cfg.compute_preempt1_size + 0x20; + match Arc::new(Self { graph, runtime: runtime.clone(), scheduler, ids: gpu::SequenceIDs::default(), preempt_bytes }, + GFP_KERNEL) { + Ok(backend) => Ok(backend), + Err(e) => { runtime.stop(); Err(e.into()) } + } + } + + pub(crate) fn stop(&self) { self.runtime.stop(); } +} + +impl Drop for Backend { + fn drop(&mut self) { self.runtime.stop(); } +} + +impl gpu::Gpu for Backend { + fn stats_snapshot(&self) -> Option> { None } + fn as_any(&self) -> &dyn core::any::Any { self } + fn arc_as_any(self: Arc) -> Arc { self as Arc } + fn manager(&self) -> Option<&dyn gpu::GpuManager> { None } + fn init(&self) -> Result { if self.runtime.healthy() { Ok(()) } else { Err(ENODEV) } } + fn ids(&self) -> &gpu::SequenceIDs { &self.ids } + fn is_crashed(&self) -> bool { !self.runtime.healthy() } + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { + ::get_params(&self.graph, params)?; + params.max_commands_per_submission = crate::m3::agx_uapi::UAPI_MAX_HARDWARE_COMMANDS; + params.max_attachments = crate::m3::agx_uapi::UAPI_MAX_ATTACHMENTS as u32; + Ok(()) + } + fn supports_vm_status(&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 + } + fn tracked_submission(&self) -> bool { true } + fn base_clock_hz(&self) -> u32 { ::base_clock_hz(&self.graph) } + fn uat_geometry(&self) -> mmu::UatGeometry { ::uat_geometry(&self.graph) } + fn new_vm(&self, range: Range) -> Result { + self.graph.kernel_uat().new_vm(self.ids.vm.next(), range)?.with_tracked_status() + } + fn new_queue(&self, vm: mmu::Vm, _ualloc: Arc>, + ualloc_priv: Arc>, priority: u32, + usc_exec_base: u64, _usage: Arc) -> Result> { + Ok(KBox::new(crate::m3::m3_submit::Queue::new_g14_v27_2(self.runtime.clone(), self.scheduler.clone(), + vm, priority, usc_exec_base, ualloc_priv, self.preempt_bytes)?, GFP_KERNEL)?) + } + fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) -> Result { + // Timestamp buffers would need new tables in the firmware window after boot. + Err(ENOTSUPP) + } +} diff --git a/drivers/gpu/drm/asahi/g15/uat.rs b/drivers/gpu/drm/asahi/g15/uat.rs index 0f91f7c9f0610..8168f32abe01b 100644 --- a/drivers/gpu/drm/asahi/g15/uat.rs +++ b/drivers/gpu/drm/asahi/g15/uat.rs @@ -118,7 +118,7 @@ fn clean_entries(pa: u64, first: usize, count: usize) -> Result { } /// Cleans a whole RAM table page to the point of coherency. -fn clean_page(pa: u64) -> Result { +pub(crate) fn clean_page(pa: u64) -> Result { clean_entries(pa, 0, ENTRIES) } diff --git a/drivers/gpu/drm/asahi/g17/fw/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/initdata.rs index a70b5763eac4d..9c827c6d8c188 100644 --- a/drivers/gpu/drm/asahi/g17/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/initdata.rs @@ -652,6 +652,7 @@ impl RegisterWindow { const RESERVED_SLOT_UNK_20: u32 = 2; /// One register-map slot of the hardware data. +#[derive(Debug)] #[repr(C)] pub(crate) struct RegisterMapEntry { /// Physical address of the window. diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index ded8c30ac41fd..848f2171278ae 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -1857,7 +1857,7 @@ const COMMON26_POLICY_BOOT_TIMESTAMP: usize = 0x6c14; /// initPowerAndPerformanceData stores (the G18 backend's G18G_26A428_POLICY_BANDS). 26A428 /// inserts 0x680 bytes between the AON PTD pointer and the boot timestamp; the 25G76 words /// there have no place. -const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ +pub(crate) const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ band(0x0000, 0x009c, 0, Evidence::ProducerChecked), band(0x00a0, 0x0200, 0x10, Evidence::ProducerChecked), band(0x09b8, 0x295c, 0x10, Evidence::ProducerChecked), diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index d923272a9a18d..546cab58bc3c5 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -375,6 +375,16 @@ enum CrashLogMap { FirmwareData(data_segment::DataSegmentLog), } +impl CrashLog { + /// Map only the range firmware requested within its loader-reserved data. + pub(crate) fn from_firmware(dev: &device::Device, iova: usize, size: usize) -> Result { + Ok(Self { + iova, + map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map(dev, iova, size)?), + }) + } +} + impl rtkit::Buffer for CrashLog { fn iova(&self) -> Result { Ok(self.iova) @@ -483,14 +493,7 @@ impl rtkit::Operations for RoleOps { }); } // The firmware places its buffers in its data segment, at their physical address. - Ok(CrashLog { - iova, - map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map( - &data.shared.dev, - iova, - size, - )?), - }) + CrashLog::from_firmware(&data.shared.dev, iova, size) } } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index d462ecbd1a7ae..2166a7e3dce1e 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -106,6 +106,17 @@ const EP_DOORBELL: u8 = 0x21; const MSG_INIT: u64 = 0x81 << 48; const INIT_DATA_MASK: u64 = (1 << 44) - 1; +/// The firmware-endpoint message that hands the firmware its root at `address`. +pub(crate) const fn init_message(address: u64) -> u64 { + MSG_INIT | (address & INIT_DATA_MASK) +} + +/// The G14 firmware-27.2 root and the records only it uses. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +mod v27_2; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) use v27_2::*; + const RX_WORK_PENDING: u32 = 1 << 0; const RX_WORK_RUNNING: u32 = 1 << 1; @@ -127,6 +138,10 @@ const DOORBELL_DEVCTRL: u64 = 0x11; // Upper kernel half VA address ranges. /// Private (cached) firmware structure VA range base. const IOVA_KERN_PRIV_RANGE: Range = 0xffffffa000000000..0xffffffa600000000; +/// The G14 firmware-27.2 timestamp aperture, inside the private range: the private allocator +/// stays below it in that profile. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +const IOVA_G14_V27_2_TIMESTAMP_RANGE: Range = 0xffffffa181400000..0xffffffa185400000; /// Private (cached) GPU-RO firmware structure VA range base. const IOVA_KERN_GPU_RO_RANGE: Range = 0xffffffa600000000..0xffffffa800000000; /// Shared (uncached) firmware structure VA range base. @@ -178,6 +193,17 @@ pub(crate) struct KernelAllocators { pub(crate) gpu_ro: alloc::DefaultAllocator, } +/// What [`GpuManager::build_graph`] builds the records for. +#[derive(Copy, Clone)] +pub(crate) enum GraphProfile { + /// The manager's own firmware: map the registers, use the whole private range. + Native, + /// The G14 firmware-27.2 root (gpu/v27_2.rs) built on these records: no register + /// mappings, and the private range ends below that firmware's timestamp aperture. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + G14V27_2, +} + /// Receive (GPU->driver) ring buffer channels. #[versions(AGX)] #[pin_data] @@ -659,13 +685,42 @@ impl GpuManager::ver { cfg: &'static hw::HwConfig, ) -> Result> { let uat = Self::make_uat(dev, cfg)?; + let mgr = Self::build_graph(dev, res, cfg, uat, GraphProfile::Native)?; + let rtkit = + rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; + + *mgr.rtkit.lock() = Some(rtkit); + + { + let mut rxc = mgr.rx_channels.lock(); + rxc.event.set_manager(mgr.clone()); + rxc.stats.set_manager(mgr.clone()); + } + + Ok(mgr) + } + + /// Build the manager and its firmware records without attaching RTKit. + #[inline(never)] + pub(crate) fn build_graph( + dev: &AsahiDrmDevice, + res: ®s::Resources<'_>, + cfg: &'static hw::HwConfig, + uat: KBox, + profile: GraphProfile, + ) -> Result> { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; + let private_end = match profile { + GraphProfile::Native => IOVA_KERN_PRIV_RANGE.end, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + GraphProfile::G14V27_2 => IOVA_G14_V27_2_TIMESTAMP_RANGE.start, + }; let mut alloc = KernelAllocators { private: alloc::DefaultAllocator::new( dev, uat.kernel_vm(), - IOVA_KERN_PRIV_RANGE, + IOVA_KERN_PRIV_RANGE.start..private_end, 0x80, mmu::PROT_FW_PRIV_RW, 1024 * 1024, @@ -808,14 +863,16 @@ impl GpuManager::ver { } }); + // The 27.2 root publishes its own register table (gpu/v27_2.rs). + let map_registers = matches!(profile, GraphProfile::Native); for (i, map) in cfg.io_mappings.iter().enumerate() { - if let Some(map) = map.as_ref() { + if let Some(map) = map.as_ref().filter(|_| map_registers) { Self::iomap(&mut mgr, cfg, i, map)?; } } #[ver(V >= V13_0B4)] - if let Some(base) = cfg.sram_base { + if let Some(base) = cfg.sram_base.filter(|_| map_registers) { let size = cfg.sram_size.unwrap(); let iova = mgr.as_mut().alloc_mmio_iova(size); @@ -838,20 +895,7 @@ impl GpuManager::ver { mgr.as_mut().io_mappings_mut().push(mapping, GFP_KERNEL)?; } - let mgr = Arc::from(mgr); - - let rtkit = - rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; - - *mgr.rtkit.lock() = Some(rtkit); - - { - let mut rxc = mgr.rx_channels.lock(); - rxc.event.set_manager(mgr.clone()); - rxc.stats.set_manager(mgr.clone()); - } - - Ok(mgr) + Ok(Arc::from(mgr)) } /// Return a mutable reference to the initdata member @@ -1596,7 +1640,7 @@ impl Gpu for GpuManager::ver { rtk.as_mut().start_endpoint(EP_FIRMWARE)?; rtk.as_mut().start_endpoint(EP_DOORBELL)?; rtk.as_mut() - .send_message(EP_FIRMWARE, MSG_INIT | (initdata & INIT_DATA_MASK))?; + .send_message(EP_FIRMWARE, init_message(initdata))?; rtk.as_mut() .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; core::mem::drop(guard); diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs new file mode 100644 index 0000000000000..0ee4c1ec07ed4 --- /dev/null +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -0,0 +1,1009 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The G14 root for GPU firmware 27.2, the boot compute job that starts the firmware's command +//! service, and the command pool the 27.2 compute runtime (`crate::g14_v27_2`) publishes from. +//! +//! The root is built on the records of a 13.5 G14 manager, made with +//! [`GraphProfile::G14V27_2`]: its hardware data supplies the calibrated values, and its +//! kernel UAT, allocators and buffer-manager control pages are shared. The firmware never sees +//! that manager's own root. + +use super::*; +use crate::g17::fw::m5::initdata as abi; +use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; +use crate::m3::m3_init_26 as directory26; + +/// The firmware build word this root carries in its version field. +const FIRMWARE_WORD: u64 = 0x0c8a_8342_8392_04c8; + +/// Kick message for the compute submission ring the root uses (group 2, compute). +pub(crate) const COMPUTE_KICK: u64 = MSG_TX_DOORBELL | (4 * PRIORITY_GROUP + COMPUTE) as u64; +/// Kick message for the device-control ring. +pub(crate) const DEVICE_CONTROL_KICK: u64 = MSG_FWCTL | DOORBELL_DEVCTRL; + +/// Data master of the root's queue, and its priority group: the legacy G14 priority row 2. +const COMPUTE: usize = 2; +const PRIORITY_GROUP: usize = 2; +const PRIORITY_ROW: usize = 2; +/// The submission descriptor the queue publishes on (three per group). +const SUBMISSION_RING: usize = 3 * PRIORITY_GROUP + COMPUTE; +/// Firmware event, log, trace and statistics rings in the 34-entry channel list. +const EVENT_RING: usize = 13; +const LOG_RINGS: usize = 14; +const TRACE_RING: usize = 15; +const STATISTICS_RING: usize = 16; +/// Ring geometries: the trace ring has 512 records of 0x48 bytes, the others 256. +const TRACE_RECORDS: u32 = 512; +const RING_RECORDS: u32 = 256; +/// Queue capacity at position block +0x50 (16 x the 0x50 channels). +const QUEUE_CAPACITY: u32 = 0x500; +/// Upper performance-state cap, in hundredths, at globals +0x98: the first state above idle. +/// Only this cap has run on hardware. +const STATE_CAP: u32 = 100; + +/// Board facts the root needs, read from the device tree at probe. +pub(crate) struct BoardV27_2 { + /// The SGX register window (`reg` "sgx"). + pub(crate) sgx: u64, + pub(crate) sgx_size: u64, + /// Bytes of the firmware's crash copy buffer (`apple,coredump-copy-buffer`). + pub(crate) copy_bytes: u32, + /// The chip's 27.2 register table. + pub(crate) registers: &'static [RegisterV27_2], + /// Slots whose stock mode is read-write (bit per slot). + pub(crate) writable: u64, +} + +/// Firmware-visible facts of the root's queue that every compute command names. +#[derive(Copy, Clone)] +pub(crate) struct QueueInfo { + pub(crate) queue: u64, + pub(crate) slot: u32, + pub(crate) stamp: u64, + pub(crate) fw_stamp: u64, + pub(crate) compute_state: u64, +} + +/// One compute command, as the 26.x submission front end hands it over. +pub(crate) struct ComputeJob { + pub(crate) context: u32, + pub(crate) sequence: u64, + pub(crate) cdm_base: u64, + pub(crate) cdm_end: u64, + pub(crate) usc_base: u64, + /// VA of the preemption buffer in the same context (13.5 layout: buffer 1 at +0, + /// buffers 2 to 5 at +compute_preempt1_size + 8n). + pub(crate) preempt: u64, +} + +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} + +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Encodes a type-3 compute command (0x358 bytes, the 13.5 G14 job parameters inside the +/// 27.2 wrapper) and its start/finish stream. Both buffers must be zeroed. +#[allow(clippy::too_many_arguments)] +fn encode_compute( + cmd: &mut [u8], cmd_va: u64, stream: &mut [u8], stream_va: u64, tracking: u64, + timestamps: u64, preempt1: u64, q: &QueueInfo, stamp_value: u32, job: &ComputeJob, +) { + put32(cmd, 0, 3); + put64(cmd, 4, job.sequence); + put32(cmd, 0xc, job.context); + put64(cmd, 0x10, tracking); + // 13.5 JobParameters1 at +0x68. + let p2 = job.preempt + preempt1; + for (at, v) in [(0x00, job.preempt), (0x08, job.cdm_base), (0x10, p2), (0x18, p2 + 8), + (0x20, p2 + 16), (0x28, p2 + 24), (0x30, job.usc_base), (0x38, 0x8c60), (0x58, 1)] { + put64(cmd, 0x68 + at, v); + } + put64(cmd, 0x1e8, stream_va); + put32(cmd, 0x1f0, 0x2c0); + // 13.5 JobParameters2: preemption buffer and CDM end; EncoderParams mask. + put64(cmd, 0x220, job.preempt); + put64(cmd, 0x228, job.cdm_end); + put32(cmd, 0x270, u32::MAX); + put64(cmd, 0x298, q.stamp); + put64(cmd, 0x2a0, q.fw_stamp); + put32(cmd, 0x2a8, stamp_value); + put32(cmd, 0x2b0, q.slot); + put64(cmd, 0x2cc, timestamps); + put64(cmd, 0x2d4, timestamps + 8); + // Command-local dependency latch, enabled with seed 0; the firmware clears 0x10 bytes + // through the pointer at +0x334. + put32(cmd, 0x33c, 1); + put64(cmd, 0x334, timestamps + 0x20); + + put32(stream, 0, 11); + put64(stream, 0x160, job.sequence); + put64(stream, 0x04, cmd_va + 0x18); + put64(stream, 0x0c, cmd_va + 0x68); + put64(stream, 0x14, q.compute_state); + put64(stream, 0x1c, q.queue); + put32(stream, 0x24, job.context); + put32(stream, 0x34, q.slot); + put64(stream, 0x3c, cmd_va + 0x1f4); + put64(stream, 0x158, cmd_va + 0x340); + for (at, op, selected) in [(0x16c, 0x8000_0003u32, 0x2ccu64), (0x1bc, 3, 0x2d4)] { + put32(stream, at, op); + put64(stream, at + 0x04, cmd_va + 0x2c4); + put64(stream, at + 0x0c, cmd_va + 0x2cc); + put64(stream, at + 0x14, cmd_va + selected); + put64(stream, at + 0x1c, q.queue); + put64(stream, at + 0x2c, cmd_va + 0x314); + put64(stream, at + 0x34, cmd_va + 0x264); + } + put32(stream, 0x1b8, 0x0080_0000); + let finish = 0x208; + put32(stream, finish, 12); + put64(stream, finish + 4, q.compute_state); + put64(stream, finish + 0x0c, q.queue); + put32(stream, finish + 0x14, job.context); + put64(stream, finish + 0x18, cmd_va + 0x1f4); + put64(stream, finish + 0x2c, q.fw_stamp); + put32(stream, finish + 0x34, stamp_value); + put32(stream, finish + 0x5c, (-(finish as i32)) as u32); + put64(stream, finish + 0x71, cmd_va + 0x340); + put64(stream, finish + 0x79, cmd_va + 0x304); + put32(stream, finish + 0x84, 0x4000_0002); +} + +/// The root's queue and the kernel-owned boot job published on it: one compute dispatch of an +/// empty control stream in context 0, which the firmware must retire before clients run. +struct BootJob { + queue: fw::types::GpuArray, + positions: fw::types::GpuArray, + pointers: fw::types::GpuArray, + command: fw::types::GpuArray, + stream: fw::types::GpuArray, + tracking: fw::types::GpuArray, + timestamps: fw::types::GpuArray, + event: event::Event, + expected_stamp: u32, + _owners: KVec>, + /// The job's buffers in context 0: mapping before backing. + _client: (mmu::KernelMapping, gem::ObjectRef), + client_va: u64, + preempt1: u64, +} + +impl BootJob { + fn new(alloc: &mut KernelAllocators, event: event::Event, uat: &mmu::Uat, dev: &AsahiDevice, + cfg: &'static hw::HwConfig) -> Result { + let mut queue = alloc.private.array_empty::(0x2cc0)?; + let mut positions = alloc.shared.array_empty::(0x2860)?; + let pointers = alloc.private.array_empty::(0x2860)?; + let mut scheduler = alloc.private.array_empty::(0x40)?; + let mut queue_stamps = alloc.shared.array_empty::(0x18)?; + let command = alloc.private.array_empty::(0x400)?; + let stream = alloc.private.array_empty::(0x400)?; + // A command-buffer tracking slot (0x100 stride, 0xc8 bytes kept by the firmware) + // whose first word names its own cleared retirement cursor. + let mut tracking = alloc.private.array_empty::(0x100)?; + let cursor = alloc.shared.array_empty::(0x90)?; + put64(tracking.as_mut_slice(), 0, cursor.gpu_va().get()); + crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), 0x100); + + let queue_stamps_va = queue_stamps.gpu_va().get(); + put64(queue_stamps.as_mut_slice(), 8, queue_stamps_va); + let ctx = scheduler.as_mut_slice(); + ctx[..2].copy_from_slice(&u16::MAX.to_le_bytes()); + ctx[5] = 1; + ctx[0x27] = 0xff; + let queue_va = queue.gpu_va().get(); + let q = queue.as_mut_slice(); + for (offset, value) in [(0, positions.gpu_va().get()), (8, pointers.gpu_va().get()), + (0x10, queue_stamps_va), (0x18, queue_va + 0x90), + (0x7c, scheduler.gpu_va().get())] { + put64(q, offset, value); + } + // The kernel-owned queue has no owning process. + for offset in [0x2c, 0x4c, 0x50] { + put32(q, offset, u32::MAX); + } + let row = crate::fw::workqueue::raw::PRIORITY[PRIORITY_ROW]; + put32(q, 0x30, row.0); + put32(q, 0x34, row.1); + put64(q, 0x38, row.2.0); + put32(q, 0x40, row.3); + put32(q, 0x44, row.4); + // The current lane stays at the all-ones sentinel; the firmware assigns it. + put32(q, 0x48, u32::MAX); + crate::pgtable::clean_poc(q.as_ptr(), q.len()); + put32(positions.as_mut_slice(), 0x50, QUEUE_CAPACITY); + + // The job's preemption buffer and control stream live in context 0 at a client VA. + let preempt1 = cfg.compute_preempt1_size; + let client_va = IOVA_KERN_GPU_BUFMGR_LOW + 0x10_0000; + let mut object = gem::new_kernel_object(dev, preempt1 + 0x4000)?; + let size = object.size(); + { + use kernel::io::Io; + let map = object.vmap()?; + for off in (0..size).step_by(8) { map.try_write64(0, off)?; } + // CDM control stream: one Stream Terminate block (block type 2 in bits 31:29). + map.try_write32(0x4000_0000, preempt1 + 0x2000)?; + } + let mapping = object.map_at(uat.kernel_lower_vm(), client_va, mmu::PROT_GPU_SHARED_RW, false)?; + let timestamps = alloc.shared.array_empty::(0x80)?; + + let mut owners = KVec::new(); + for owner in [&queue_stamps, &pointers, &scheduler] { + crate::pgtable::clean_poc(owner.as_slice().as_ptr(), owner.as_slice().len()); + } + for owner in [queue_stamps, scheduler, cursor] { + owners.push(owner, GFP_KERNEL)?; + } + let expected_stamp = event.current().next().raw(); + Ok(Self { queue, positions, pointers, command, stream, tracking, timestamps, event, + expected_stamp, _owners: owners, _client: (mapping, object), + client_va, preempt1: preempt1 as u64 }) + } + + fn info(&self, compute_state: u64) -> QueueInfo { + QueueInfo { + queue: self.queue.gpu_va().get(), + slot: self.event.slot(), + stamp: u64::from(self.event.stamp_pointer()), + fw_stamp: u64::from(self.event.fw_stamp_pointer()), + compute_state, + } + } + + /// Encodes the boot command and names it at queue position 0. + fn encode(&mut self, q: &QueueInfo) { + let cdm = self.client_va + self.preempt1 + 0x2000; + let job = ComputeJob { + context: 0, sequence: 0, cdm_base: cdm, cdm_end: cdm + 8, + usc_base: 0x11_0000_0000, preempt: self.client_va, + }; + let (cmd_va, stream_va) = (self.command.gpu_va().get(), self.stream.gpu_va().get()); + encode_compute(self.command.as_mut_slice(), cmd_va, self.stream.as_mut_slice(), stream_va, + self.tracking.gpu_va().get(), self.timestamps.gpu_va().get(), self.preempt1, + q, self.expected_stamp, &job); + crate::pgtable::clean_poc(self.stream.as_slice().as_ptr(), self.stream.as_slice().len()); + crate::pgtable::clean_poc(self.command.as_slice().as_ptr(), self.command.as_slice().len()); + put64(self.pointers.as_mut_slice(), 0, cmd_va); + crate::pgtable::clean_poc(self.pointers.as_slice().as_ptr(), 8); + crate::pgtable::poc_barrier(); + } +} + +/// Command slots for client compute work. They are allocated with the root, before the +/// firmware window's tables are mirrored, so every slot lies in a table the firmware already +/// translates. Slots are reused in order. +pub(crate) const POOL_SLOTS: usize = 48; + +pub(crate) struct CommandPool { + commands: fw::types::GpuArray, + streams: fw::types::GpuArray, + tracking: fw::types::GpuArray, + cursors: fw::types::GpuArray, + stamps: fw::types::GpuArray, + preempt1: u64, +} + +impl CommandPool { + pub(crate) fn new(alloc: &mut KernelAllocators, cfg: &'static hw::HwConfig) -> Result { + let commands = alloc.private.array_empty::(POOL_SLOTS * 0x400)?; + let streams = alloc.private.array_empty::(POOL_SLOTS * 0x400)?; + let mut tracking = alloc.private.array_empty::(POOL_SLOTS * 0x100)?; + // One 64-byte line per retirement cursor, so no firmware write can reach a neighbour. + let cursors = alloc.shared.array_empty::(POOL_SLOTS * 0x40)?; + let stamps = alloc.shared.array_empty::(POOL_SLOTS * 0x80)?; + let base = cursors.gpu_va().get(); + for (i, chunk) in tracking.as_mut_slice().chunks_mut(0x100).enumerate() { + put64(chunk, 0, base + 0x40 * i as u64); + } + crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), tracking.as_slice().len()); + Ok(Self { commands, streams, tracking, cursors, stamps, preempt1: cfg.compute_preempt1_size as u64 }) + } + + /// Builds slot `i` for `job` and returns the command's firmware VA. + pub(crate) fn encode(&mut self, i: usize, q: &QueueInfo, stamp_value: u32, job: &ComputeJob) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + let cmd_va = self.commands.gpu_va().get() + (i * 0x400) as u64; + let stream_va = self.streams.gpu_va().get() + (i * 0x400) as u64; + let tracking_va = self.tracking.gpu_va().get() + (i * 0x100) as u64; + let timestamps_va = self.stamps.gpu_va().get() + (i * 0x80) as u64; + // The firmware keeps 0xc8 bytes of the tracking slot; start each use cleared. + let tracking = &mut self.tracking.as_mut_slice()[i * 0x100..(i + 1) * 0x100]; + tracking[8..].fill(0); + crate::pgtable::clean_poc(tracking.as_ptr(), tracking.len()); + let stamps = &mut self.stamps.as_mut_slice()[i * 0x80..(i + 1) * 0x80]; + stamps.fill(0); + crate::pgtable::clean_poc(stamps.as_ptr(), 0x80); + let cmd = &mut self.commands.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + cmd.fill(0); + let stream = &mut self.streams.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + stream.fill(0); + encode_compute(cmd, cmd_va, stream, stream_va, tracking_va, timestamps_va, self.preempt1, + q, stamp_value, job); + crate::pgtable::clean_poc(stream.as_ptr(), stream.len()); + crate::pgtable::clean_poc(cmd.as_ptr(), cmd.len()); + crate::pgtable::poc_barrier(); + Ok(cmd_va) + } + + /// Retirement: advance slot `i`'s cursor to the value the firmware recorded at + /// tracking +0xc, so its retirement scan unlinks the slot from the queue's list. + pub(crate) fn retire(&self, i: usize) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + let expected = self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire); + self.cursors.shared_index(i * 0x40)?.store(expected, Ordering::Release); + crate::pgtable::clean_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Whether the firmware still holds slot `i` in the queue's tracking list (+0x94). + pub(crate) fn registered(&self, i: usize) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + Ok(self.tracking.shared_index(i * 0x100 + 0x94)?.load(Ordering::Acquire) != 0) + } +} + +/// The firmware 27.2 root and every record it names. +pub(crate) struct RootV27_2 { + graph: Arc, + boot: BootJob, + compute_state: u64, + channels: KVec>, + _owners: KVec>, + _register_mappings: KVec, + _controller: fw::types::GpuArray, + _directory: fw::types::GpuArray, + boot_page: fw::types::GpuArray, + globals: fw::types::GpuArray, + status: fw::types::GpuArray, + control: fw::types::GpuArray, + power: fw::types::GpuArray, + extra: fw::types::GpuArray, +} + +impl fw::types::GpuStruct for RootV27_2 { + type Raw<'a> = fw::initdata::raw::InitDataG14V27_2<'a>; +} + +impl GpuManagerG14V13_5 { + /// The kernel UAT these records live in. + pub(crate) fn kernel_uat(&self) -> &mmu::Uat { + &self.uat + } +} + +impl RootV27_2 { + fn word(a: &fw::types::GpuArray, at: usize) -> Result { + Ok(a.shared_index(at)?.load(Ordering::Acquire)) + } + + /// The queue's identity for client commands, and the stamp value it last reached. + pub(crate) fn queue(&self) -> (QueueInfo, event::EventValue) { + (self.boot.info(self.compute_state), self.boot.event.current()) + } + + /// The queue's capacity (position block +0x50). + pub(crate) fn capacity(&self) -> Result { + Self::word(&self.boot.positions, 0x50) + } + + /// The queue head and the firmware's retired position, which it advances in order. + pub(crate) fn progress(&self) -> Result<(u32, u32)> { + let positions = self.boot.positions.as_slice(); + crate::pgtable::clean_invalidate_poc(positions.as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + 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 { + let job = &self.boot; + 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 at = (old % capacity) 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); + } + 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(()) + } + + /// Publishes the boot job, whose command and ring entry the root already holds. The GPU + /// must be held powered (`operating_point`: the Fender state, nonzero index, no request + /// pending) and the command service installed. + pub(crate) fn publish_boot_job(&self, operating_point: u32) -> Result { + let job = &self.boot; + let index = operating_point & 0xf; + if operating_point & 0x10 != 0 || index == 0 || index > self.graph.dyncfg.pwr.perf_max_pstate + || self.idle_progress()? != [1; 3] + || self.idle_acknowledgement()? != Self::word(&self.globals, 0xe40)? + || self.command_service()?.1 != 0 { + return Err(EAGAIN); + } + let producer = self.channels[2 * SUBMISSION_RING].shared_index(0x20)?; + let head = job.positions.shared_index(0x40)?; + if Self::word(&self.status, 0x14)? != 1 || producer.load(Ordering::Acquire) != 0 + || head.load(Ordering::Acquire) != 0 { + return Err(EAGAIN); + } + crate::pgtable::poc_barrier(); + head.store(1, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(1, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Whether the boot job has retired: ring consumed, queue read and retired, stamp reached. + pub(crate) fn boot_job_complete(&self) -> Result { + self.drain()?; + let job = &self.boot; + Ok(Self::word(&self.channels[2 * SUBMISSION_RING], 0)? == 1 + && Self::word(&job.positions, 0x30)? == 1 + && Self::word(&job.positions, 0)? == 1 + && job.event.current().raw() == job.expected_stamp) + } + + /// Consumes everything the firmware published on its statistics, event, log and trace + /// rings. The firmware waits for space when one is full, and host consumer advancement is + /// the acknowledgement; completion is followed through the queue's position block, so the + /// records are not kept. + pub(crate) fn drain(&self) -> Result { + let consume = |state: &fw::types::GpuArray, base: usize, records: u32| -> Result { + let write = Self::word(state, base + 0x20)?; + let read = state.shared_index(base)?; + if write < records && read.load(Ordering::Acquire) != write { + read.store(write, Ordering::Release); + crate::pgtable::poc_barrier(); + } + Ok(()) + }; + consume(&self.channels[2 * STATISTICS_RING], 0, RING_RECORDS)?; + consume(&self.channels[2 * EVENT_RING], 0, RING_RECORDS)?; + // One log ring per log thread, state blocks 0x30 apart. + for thread in 0..directory26::LOG_THREADS { + consume(&self.channels[2 * LOG_RINGS], thread * 0x30, RING_RECORDS)?; + } + consume(&self.channels[2 * TRACE_RING], 0, TRACE_RECORDS) + } + + /// Shared status +0x10: nonzero while the firmware reports itself running. + pub(crate) fn firmware_running(&self) -> Result { + Self::word(&self.status, 0x10) + } + + /// Command-service state: (powered stage, pending installation request). + /// Engine entries may be published only at (2, 0). + pub(crate) fn command_service(&self) -> Result<(u32, u32)> { + Ok((Self::word(&self.control, 0x4c00)?, Self::word(&self.control, 0x4c24)?)) + } + + pub(crate) fn idle_acknowledgement(&self) -> Result { + Self::word(&self.control, 0xe838) + } + + /// Device-control ring consumer, target and producer. + pub(crate) fn idle_progress(&self) -> Result<[u32; 3]> { + self.drain()?; + let ring = &self.channels[2 * crate::m3::DEVICE_CONTROL]; + Ok([Self::word(ring, 0)?, Self::word(ring, 0x10)?, Self::word(ring, 0x20)?]) + } + + /// Publishes one of the two pre-encoded idle-policy records on the device-control ring: + /// keep powered first, then allow off. Returns the ring cursor and the counted generation + /// the firmware acknowledges, which follows the larger of the host's last publication and + /// the firmware's consumed count. + pub(crate) fn publish_idle_policy(&self, allow_off: bool) -> Result<(u32, u32)> { + let cursor = u32::from(allow_off); + let host = self.globals.shared_index(0xe40)?; + let firmware = self.idle_acknowledgement()?; + let producer = self.channels[2 * crate::m3::DEVICE_CONTROL].shared_index(0x20)?; + if Self::word(&self.status, 0x14)? != 1 || + crate::m3::idle_cursor(self.idle_progress()?).map_err(|_| EBUSY)? != cursor { + return Err(EAGAIN); + } + let action = crate::m3::Action::Idle { enabled: allow_off }; + let generation = action.generation(host.load(Ordering::Acquire), firmware).map_err(|_| EOVERFLOW)?; + host.store(generation, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(cursor + 1, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok((cursor + 1, generation)) + } + + /// Builds the root, the boot job and every record they name. + pub(crate) fn build(graph: &Arc, board: &BoardV27_2) -> Result> { + let cfg = graph.cfg; + let pwr = &graph.dyncfg.pwr; + let states = &pwr.perf_states; + let id = &graph.dyncfg.id; + // Inputs the controller below is built from, all from the DT and the ID registers. + let [core_mask] = id.core_masks.as_slice() else { return Err(EINVAL); }; + if !pwr.power_zones.is_empty() || pwr.max_power_mw == 0 || pwr.max_power_mw > i32::MAX as u32 + || states.last().map(|s| s.pwr_mw) != Some(pwr.max_power_mw) + || pwr.power_sample_period == 0 + || pwr.ppm_filter_time_constant_ms < pwr.power_sample_period + || pwr.avg_power_filter_tc_ms < pwr.power_sample_period + || pwr.avg_power_target_filter_tc == 0 + || !(2..=abi::COMMON26_HW_PERF_ROWS).contains(&states.len()) + || states.windows(2).any(|s| s[1].pwr_mw <= s[0].pwr_mw || s[1].freq_hz <= s[0].freq_hz) + || pwr.perf_base_pstate == 0 || pwr.perf_base_pstate as usize >= states.len() + || core_mask.count_ones() != id.total_active_cores || id.total_active_cores == 0 + || cfg.shared3_tab.len() != 16 + || board.copy_bytes == 0 || board.sgx_size < 0xe14000 { + return Err(EINVAL); + } + // Alarm sensors: the chip's fast-die selection, also its sensor inventory. + let sensors = cfg.fast_sensor_mask[0]; + if sensors == 0 || sensors >> 32 != 0 || cfg.fast_sensor_mask_alt[0] != sensors { + return Err(EINVAL); + } + // The SRAM voltage of each operating point, published by the loader from the ADT. + let sram_table = Self::sram_table(states.len())?; + + let mut alloc = graph.alloc(); + let mut boot = BootJob::new(&mut alloc, graph.event_manager.try_get_polled()?, + graph.kernel_uat(), &graph.dev, cfg)?; + // The 0x60-byte root child and the eight-byte temperature generation occupy + // consecutive, 64-byte-aligned shared suballocations. + let extra = alloc.shared.array_empty::(0x80 + 8)?; + + // The thirteen TX descriptors and four RX rings. + let mut channels = KVec::new(); + let mut addresses = [0; 34]; + for (index, address) in addresses.iter_mut().enumerate() { + let size = directory26::allocation(index).map_err(|_| EINVAL)?.size; + let owner = if index < 26 && index % 2 == 1 { + alloc.private.array_empty::(size)? + } else { + alloc.shared.array_empty::(size)? + }; + *address = owner.gpu_va().get(); + channels.push(owner, GFP_KERNEL)?; + } + { + // The boot job's entry is pending at index 0 of its empty ring. + let slot = u8::try_from(boot.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(COMPUTE as u32, boot.queue.gpu_va().get(), 1, slot, true) + .map_err(|_| EINVAL)?; + let ring = channels[2 * SUBMISSION_RING + 1].as_mut_slice(); + ring[..entry.len()].copy_from_slice(&entry); + crate::pgtable::clean_poc(ring.as_ptr(), ring.len()); + } + { + // The two idle-policy records: keep powered, then allow off. + let records = &mut channels[2 * crate::m3::DEVICE_CONTROL + 1].as_mut_slice() + [..2 * crate::m3::CONTROL_BYTES]; + for (index, record) in records.chunks_exact_mut(crate::m3::CONTROL_BYTES).enumerate() { + crate::m3::Action::Idle { enabled: index == 1 }.encode(record).map_err(|_| EINVAL)?; + } + crate::pgtable::clean_poc(records.as_ptr(), records.len()); + } + + let mut directory = alloc.private.array_empty::(0x4c8)?; + let bytes = directory.as_mut_slice(); + directory26::write_channels(bytes, &addresses).map_err(|_| EINVAL)?; + let base = &graph.initdata.runtime_pointers; + + // Hardware data: the 27.2 inline block. + use fw::initdata::raw::HwDataBG14V27_2 as Hw; + use crate::m3::m3_mmio_26::{write_record, RECORD_BYTES, TABLE_OFFSET}; + let mut hardware = alloc.private.array_empty::(0x2788)?; + let hw = hardware.as_mut_slice(); + let mode = |slot: usize| if board.writable & (1 << slot) != 0 { 2 } else { 0 }; + for slot in 0..60 { + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * slot..], 0, 0, 0, 0, 0, mode(slot)) + .map_err(|_| EINVAL)?; + } + let mut register_mappings = KVec::new(); + let mut io_va = IOVA_KERN_MMIO_RANGE.start; + for reg in board.registers { + let physical = match reg.base { + RegisterBaseV27_2::Physical(pa) => pa, + RegisterBaseV27_2::Sgx(offset) => board.sgx + offset, + }; + let Some(va_offset) = reg.install else { continue; }; + let subpage = physical as usize & mmu::UAT_PGMSK; + let span = (subpage + reg.size as usize + mmu::UAT_PGMSK) & !mmu::UAT_PGMSK; + let writable = mode(reg.slot) == 2; + let page_start = physical - subpage as u64; + let va = match va_offset { + 0 => io_va, + offset => IOVA_KERN_MMIO_RANGE.start + offset, + }; + let page = graph.uat.kernel_vm().map_io( + graph.dev.as_ref().as_ref(), va, page_start as usize, span, + if writable { mmu::PROT_FW_MMIO_RW } else { mmu::PROT_FW_MMIO_RO }, + )?; + if page.translate_offset(subpage)? != physical + || page.translate_offset(subpage + reg.size as usize - 1)? != physical + u64::from(reg.size) - 1 { + return Err(EINVAL); + } + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * reg.slot..], physical, + page.iova() + subpage as u64, reg.size, reg.size, reg.relative, mode(reg.slot)) + .map_err(|_| EINVAL)?; + if va_offset == 0 { + io_va = io_va.checked_add(span as u64).ok_or(EOVERFLOW)?; + } + register_mappings.push(page, GFP_KERNEL)?; + } + let dump = core::mem::offset_of!(Hw, coredump_copy_buffer_size); + put64(hw, dump, u64::from(board.copy_bytes)); + base.hwdata_b.with(|old, _| { + for (offset, value) in [ + (0x00, old.unk_8.0), (0x08, old.unk_18.0), + (0x10, 0x11_00000000), (0x18, 0x11_00000000), + (0x20, 0x6f_ffff8000), (0x28, IOVA_G14_V27_2_TIMESTAMP_RANGE.start), + (0x10cc, old.uat_ttb_base.0), + ] { + put64(hw, offset, value); + } + for (offset, value) in [(0x10d4, old.gpu_core_id), (0x10d8, old.gpu_rev_id), + (0x10dc, id.total_active_cores), (0x10e0, old.max_pstate)] { + put32(hw, offset, value); + } + let chip = core::mem::offset_of!(Hw, chip_id); + for (i, word) in [old.chip_id, old.unk_454, old.unk_458, old.unk_45c].into_iter().enumerate() { + put32(hw, chip + 4 * i, word); + } + }); + // Inline words the stock host producer fixes for a gpu,t8112 node without model-slow. + for (offset, value) in [(0xfc8u32, 0u32), (0xfd8, 1), (0xfec, 24000), (0xff0, 1), + (0xffc, 1), (0x2724, 1), (0x2754, 1), + (0xfc4, 1), (0xfdc, 1), (0xfe0, 0), (0x1028, 0), + (0x109c, 0), (0x1064, 0), (0x2728, 0)] { + put32(hw, offset as usize, value); + } + // Compute resource mask, one low bit per configured core; the firmware seeds the + // compute engine's population from it. + let cores = id.total_active_cores; + put32(hw, 0x2670, if cores < 32 { (1u32 << cores) - 1 } else { u32::MAX }); + // Firmware-managed operating points, CRE and event-assisted operating-point completion. + for offset in [0xfc0, 0x26b8, 0x1054] { + put32(hw, offset, 1); + } + put64(hw, 0x267c, u64::from(*core_mask)); + put32(hw, 0x2684, id.total_active_cores); + // Operating points: power above the lowest state, and frequency above the base state, + // as percentages; MHz and the per-lane core and SRAM voltages. + let top = states.len() - 1; + if old_max_pstate(base)? as usize != top { return Err(EINVAL); } + let baseline = states[0].pwr_mw; + let span = crate::float::F32::from(states[top].pwr_mw - baseline); + for (i, state) in states.iter().enumerate() { + let percentage = crate::float::F32::from(state.pwr_mw - baseline) * crate::f32!(100.0) / span; + put32(hw, abi::COMMON26_HW_PERF_RELATIVE_A + i * 4, percentage.to_bits()); + } + let base_idx = pwr.perf_base_pstate as usize; + let base_hz = states[base_idx].freq_hz; + let span = crate::float::F32::from(states[top].freq_hz - base_hz); + for (i, state) in states.iter().enumerate().skip(base_idx + 1) { + let relative = crate::float::F32::from(state.freq_hz - base_hz) * crate::f32!(100.0) / span; + put32(hw, abi::COMMON26_HW_PERF_RELATIVE_B + 4 * i, relative.to_bits()); + } + 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 mhz = state.freq_hz / 1_000_000; + for series in [abi::COMMON26_HW_PERF_FREQUENCY, 0x1924] { + put32(hw, series + i * 4, mhz); + } + for lane in 0..abi::COMMON26_HW_PERF_LANES { + let row = i * abi::COMMON26_HW_PERF_ROW_STRIDE + lane * 4; + put32(hw, abi::COMMON26_HW_PERF_CORE_VOLTAGE + row, *mv); + put32(hw, abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row, sram_mv); + } + } + crate::pgtable::clean_poc(hw.as_ptr(), hw.len()); + put64(bytes, 0, hardware.gpu_va().get()); + channels.push(hardware, GFP_KERNEL)?; + + // The directory's other records; +0x485 is the power controller. + let mut owners = KVec::new(); + let mut controller = None; + let mut compute_state = 0; + for (offset, size) in [(0x10, 0x88), (0x254, 0x678), (0x25c, 0x760), + (0x264, 0x6d0), (0x26c, 0x60), (0x485, 0x6c48)] { + let mut owner = alloc.private.array_empty::(size)?; + if offset == 0x485 { + Self::controller(owner.as_mut_slice(), graph, &extra, sensors)?; + } + let address = owner.gpu_va().get(); + put64(bytes, offset, address); + if offset == 0x10 { + put64(bytes, 8, address); + } + if offset == 0x264 { + // The compute engine state the start and finish records name. + compute_state = address; + } + if offset == 0x485 { + controller = Some(owner); + } else { + owners.push(owner, GFP_KERNEL)?; + } + } + let controller = controller.ok_or(EINVAL)?; + let ids = alloc.private.array_empty::(0x134c)?; + for (slot, offset) in [(0x2c8, 0), (0x2d0, 0x1000), (0x2d8, 0x1300)] { + put64(bytes, slot, ids.gpu_va().get() + offset); + } + owners.push(ids, GFP_KERNEL)?; + let low = base.buffer_mgr_ctl_low_mapping.as_ref().ok_or(EINVAL)?; + let high = base.buffer_mgr_ctl_high_mapping.as_ref().ok_or(EINVAL)?; + if low.translate_offset(0)? != high.translate_offset(0)? { return Err(EINVAL); } + put64(bytes, 0x2e0, low.iova()); + put64(bytes, 0x2e8, high.iova()); + bytes[0x3e4] = 0xff; + let payload = alloc.shared.array_empty::( + directory26::LOG_THREADS * RING_RECORDS as usize * directory26::LOG_PAYLOAD_BYTES)?; + put64(bytes, 0x200, payload.gpu_va().get()); + owners.push(payload, GFP_KERNEL)?; + crate::pgtable::clean_poc(bytes.as_ptr(), bytes.len()); + + let status = alloc.shared.array_empty::(0x20)?; + let boot_page = { + let page = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; + fw::types::GpuArray::empty(page, mmu::UAT_PGSZ)? + }; + let mut globals = alloc.shared_ro.array_empty::(0xe48)?; + { + let data = globals.as_mut_slice(); + for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { + data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); + } + let ceiling = pwr.perf_max_pstate * 100; + for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, STATE_CAP)] { + put32(data, at, value); + } + put32(data, 0x6e, 1); + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + } + let mut control = alloc.shared.array_empty::(0xe850)?; + { + // One shared backing: 0x20 bytes of indices, followed at +0x40 by 256 cache-flush + // requests. An empty ring still needs both VAs. + let flush = alloc.shared.array_empty::(0x40 + 256 * 0x18)?; + let state = flush.gpu_va().get(); + directory26::write_flush_ring(control.as_mut_slice(), 0x4be0, state, state + 0x40) + .map_err(|_| EINVAL)?; + // Request command-handler installation during powered initialization. + put32(control.as_mut_slice(), 0x4c24, 1); + owners.push(flush, GFP_KERNEL)?; + } + let mut power = alloc.shared.array_empty::(0x6a0)?; + { + // Cold mirrors of the controller's power and temperature-loop values. + let gains = base.hwdata_a.with(|a, _| (a.ppm_kp.to_bits(), a.ppm_ki_dt.to_bits())); + let data = power.as_mut_slice(); + for (at, value) in [(0x12c, pwr.max_power_mw), (0x130, gains.0), (0x134, gains.1)] { + put32(data, at, value); + } + let initial = controller.as_slice(); + for (dst, src) in [(0xc8, 0x22d4), (0xcc, 0x2280), (0xd0, 0x2284), + (0xd4, 0x22cc), (0xd8, 0x22b4), (0xdc, 0x22a4)] { + data[dst..dst + 4].copy_from_slice(&initial[src..src + 4]); + } + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + } + + boot.encode(&boot.info(compute_state)); + let (page_size, page_bits, levels, descriptors) = graph.initdata.with(|r, _| + (r.uat_page_size, r.uat_page_bits, r.uat_num_levels, r.uat_level_info)); + let root = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; + core::mem::drop(alloc); + let root = fw::types::GpuObject::::new_init_prealloc(root, + |_| try_init!(Self { + graph: graph.clone(), boot, compute_state, channels, _owners: owners, + _register_mappings: register_mappings, _controller: controller, _directory: directory, + boot_page, globals, status, control, power, extra, + }), + |owners, _| { + try_init!(fw::initdata::raw::InitDataG14V27_2 { + ver_info: fw::types::Array::new(core::array::from_fn(|i| (FIRMWARE_WORD >> (16 * i)) as u16)), + unk_buf: owners.boot_page.gpu_pointer(), + unk_8: 0, + unk_c: 0, + runtime_pointers: owners._directory.gpu_pointer(), + globals: owners.globals.gpu_pointer(), + role: 0, + host_mapped_fw_allocations: 1, + uat_page_size: page_size, + uat_page_bits: page_bits, + uat_num_levels: levels, + uat_level_info: descriptors, + __pad0: Default::default(), + status_record: owners.status.gpu_pointer(), + control: owners.control.gpu_pointer(), + power: owners.power.gpu_pointer(), + extra: owners.extra.gpu_pointer(), + }) + }, + )?; + root.with(|r, _| crate::pgtable::clean_poc(core::ptr::from_ref(r).cast(), core::mem::size_of_val(r))); + Ok(root) + } + + /// 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>> { + 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) + }; + for parent in chosen.children() { + 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); } + return Ok(table); + } + } + } + Err(EINVAL) + } + + /// The power and thermal controller (directory +0x485): the 13.5 calibrated values of the + /// hardware data A, moved to the 27.2 layout. + fn controller(policy: &mut [u8], graph: &GpuManagerG14V13_5, extra: &fw::types::GpuArray, + sensors: u64) -> Result { + let pwr = &graph.dyncfg.pwr; + let cfg = graph.cfg; + let base = &graph.initdata.runtime_pointers; + let max_state = (pwr.perf_states.len() as u32 - 1) * 100; + for offset in [0x222c, 0x2880] { + put32(policy, offset, max_state); + } + let generation = extra.gpu_va().get() + 0x80; + if generation & 0x3f != 0 || extra.as_slice()[0x80..] != [0; 8] { + return Err(EINVAL); + } + put64(policy, 0x3b98, generation); + // Secure metrology sensor set, and the fast-die release temperature, mask and gains. + put64(policy, 0x3ba0, sensors); + let (release, mask, integral, proportional) = base.hwdata_a.with(|old, _| + (old.fast_die0_release_temp_cc, old.fast_die0_sensor_mask.0, + old.fast_die0_ki_dt.to_bits(), old.fast_die0_kp.to_bits())); + for (source, value, width) in [(0x2270, u64::from(release), 4), (0x2268, mask, 8), + (0x2294, u64::from(integral), 4), (0x22a4, u64::from(proportional), 4)] { + let at = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; + policy.get_mut(at..at + width).ok_or(EINVAL)?.copy_from_slice(&value.to_le_bytes()[..width]); + } + // Thermal thresholds and corrections, then the SoC-hot alarm selection. + for (at, value) in [(0x22d4, 11000), (0x2284, 900), (0x2288, 4), + (0x229c, crate::f32!(1.0).to_bits()), (0x2f30, 125), (0x2f34, 1)] { + put32(policy, at, value); + } + for at in [0x2320, 0x2420, 0x2f38, 0x3038] { + for sid in (0..64).filter(|sid| sensors & (1u64 << sid) != 0) { + put32(policy, at + 4 * sid, crate::f32!(5.3).to_bits()); + } + } + put64(policy, 0x2f28, sensors); + put32(policy, 0x3ba8, 1); + for (word, value) in policy[0x62b8..0x62f8].chunks_exact_mut(4).zip(cfg.shared3_tab) { + word.copy_from_slice(&value.to_le_bytes()); + } + // Cold-wake operand: the board's base operating point. + put32(policy, 0xa4, pwr.perf_base_pstate); + for (source, bits) in [ + (4, pwr.pwr_sample_period_aic_clks), + (8, pwr.pwr_sample_period_aic_clks), + // Two initial state sources; the current state at +0x38 belongs to the firmware. + (0x2c, pwr.perf_base_pstate), + (0x30, pwr.perf_base_pstate), + (0x9f0, pwr.pwr_min_duty_cycle), + (0xb5c, pwr.perf_integral_gain.to_bits()), + (0xb60, pwr.perf_integral_gain2.to_bits()), + (0xb6c, pwr.perf_proportional_gain.to_bits()), + (0xb70, pwr.perf_proportional_gain2.to_bits()), + ] { + let target = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; + policy.get_mut(target..target + 4).ok_or(EINVAL)?.copy_from_slice(&bits.to_le_bytes()); + } + // The calibrated values of the 13.5 producer; only the layout and the peak length unit + // differ. No power zones. + let samples = pwr.ppm_filter_time_constant_ms / pwr.power_sample_period; + let fields = base.hwdata_a.with(|a, _| [ + (0x50, 100), (0xa80, a.ppm_filter_tc_periods_x4), + (0xa8c, a.ppm_filter_a_neg.to_bits()), (0xa94, a.ppm_filter_a.to_bits()), + (0xa9c, a.ppm_ki_dt.to_bits()), (0xaa8, a.unk_6fc.to_bits()), + (0xaac, a.ppm_kp.to_bits()), (0xab8, a.pwr_min_duty_cycle), + (0xabc, a.max_pstate_scaled_4), (0xacc, a.max_power_3), + (0xad8, samples), (0x2200, a.unk_6fc.to_bits()), + (0xa48, max_state), + (0xb38, a.perf_tgt_utilization), (0xb40, a.perf_boost_min_util), + (0xb44, a.perf_boost_ce_step), (0xb58, a.perf_filter_drop_threshold), + (0xb5c, a.perf_filter_a_neg.to_bits()), (0xb60, a.perf_filter_a2_neg.to_bits()), + (0xb64, a.perf_filter_a.to_bits()), (0xb68, a.perf_filter_a2.to_bits()), + (0xb74, a.perf_integral_min_clamp.to_bits()), (0xb78, a.unk_79c.to_bits()), + (0xb84, a.boost_state_unk_k.to_bits()), (0xb88, a.base_pstate_scaled_2), + (0xb8c, a.max_pstate_scaled_5), (0xb90, a.base_pstate_scaled_3), + (0xb9c, a.perf_tgt_utilization_2), (0xbd0, a.base_pstate_scaled_4), + (0x2204, a.pwr_min_duty_cycle_2.to_bits()), (0x2208, a.max_pstate_scaled_6.to_bits()), + (0x220c, pwr.max_freq_mhz), + (0x22b0, a.unk_8a8.to_bits()), (0x22c0, a.pwr_min_duty_cycle_4), + (0x22c4, a.max_pstate_scaled_8), (0x22c8, a.max_pstate_scaled_9), + (0x2308, a.max_pstate_scaled_10), + (0x28e8, 0), (0x28f0, a.max_power_4), + (0x28f4, a.max_power_5), (0x28f8, a.max_power_6), + (0x2904, a.avg_power_target_filter_a_neg.to_bits()), + (0x2908, a.avg_power_target_filter_a.to_bits()), + (0x29f0, a.avg_power_filter_a_neg.to_bits()), + (0x29f8, a.avg_power_filter_a.to_bits()), + (0x2a00, a.avg_power_ki_dt.to_bits()), (0x2a10, a.avg_power_kp.to_bits()), + (0x2a0c, a.unk_d20.to_bits()), (0x2a1c, a.avg_power_min_duty_cycle), + (0x2a20, a.max_pstate_scaled_12), (0x2a2c, a.max_power_7.to_bits()), + (0x2a30, a.max_power_8), + (0x2b80, a.unk_e10_0.gpu_se_filter_a_neg.to_bits()), + (0x2b84, a.unk_e10_0.gpu_se_filter_1_a_neg.to_bits()), + (0x2b88, a.unk_e10_0.gpu_se_filter_a.to_bits()), + (0x2b8c, a.unk_e10_0.gpu_se_filter_1_a.to_bits()), + (0x2b90, a.unk_e10_0.gpu_se_ki_dt.to_bits()), + (0x2b94, a.unk_e10_0.gpu_se_ki_1_dt.to_bits()), + (0x2b9c, a.unk_e10_0.unk_7c.to_bits()), + (0x2ba0, a.unk_e10_0.gpu_se_kp.to_bits()), + (0x2ba4, a.unk_e10_0.gpu_se_kp_1.to_bits()), + (0x2bac, a.unk_e10_0.unk_8c), (0x2bb0, a.unk_e10_0.max_pstate_scaled_1), + (0x2c10, a.unk_e10_0.unk_3c), (0x2c14, a.unk_e10_0.unk_38), + (0x2c28, a.unk_e10_0.gpu_se_reset_criteria), + (0x6ac8, 1), + ]); + for (at, value) in fields { + put32(policy, at, value); + } + put64(policy, 0xae0, u64::from(samples) * u64::from(pwr.pwr_sample_period_aic_clks)); + crate::pgtable::clean_poc(policy.as_ptr(), policy.len()); + Ok(()) + } +} + +/// The 13.5 hardware data's highest operating-point index. +fn old_max_pstate(base: &fw::initdata::RuntimePointersG14V13_5) -> Result { + Ok(base.hwdata_b.with(|old, _| old.max_pstate)) +} diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index a58fac5e12c37..2fd17c298d68d 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -122,6 +122,30 @@ pub(crate) struct PowerZone { pub(crate) filter_tc: u32, } +/// Base of a window in the firmware 27.2 register table. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[derive(Debug, Copy, Clone)] +pub(crate) enum RegisterBaseV27_2 { + /// A fixed physical address. + Physical(u64), + /// An offset into the GPU's SGX window (its `sgx` resource). + Sgx(u64), +} + +/// One record of the firmware 27.2 register table: 60 slots, each naming one window. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[derive(Debug, Copy, Clone)] +pub(crate) struct RegisterV27_2 { + pub(crate) slot: usize, + pub(crate) base: RegisterBaseV27_2, + pub(crate) size: u32, + /// Offset of the window within the GPU's register space, as the record carries it. + pub(crate) relative: u64, + /// Where the window is mapped for the firmware: `None` leaves the record without a + /// mapping, `Some(0)` takes the next free MMIO VA, `Some(offset)` a fixed MMIO VA offset. + pub(crate) install: Option, +} + /// An MMIO mapping used by the firmware. #[derive(Debug, Copy, Clone)] pub(crate) struct IOMapping { diff --git a/drivers/gpu/drm/asahi/hw/t8112.rs b/drivers/gpu/drm/asahi/hw/t8112.rs index bac2757175f2c..1879be7f8cead 100644 --- a/drivers/gpu/drm/asahi/hw/t8112.rs +++ b/drivers/gpu/drm/asahi/hw/t8112.rs @@ -104,3 +104,47 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_base: None, sram_size: None, }; + +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, install: Option) -> RegisterV27_2 { + RegisterV27_2 { slot, base, size, relative, install } +} + +/// The firmware 27.2 register table. Writable windows outside SGX are left unmapped, except +/// the push-telemetry window (slot 9), which the firmware shares with the PMP; it is mapped +/// apart from the others. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { + use RegisterBaseV27_2::{Physical, Sgx}; + &[ + reg(0, Physical(0x23b0c4000), 0x4000, 0, None), // AIC software interrupt + reg(1, Physical(0x23b2c0000), 0x1000, 0, Some(0)), // Analog temperature controller + reg(3, Physical(0x200f04000), 0x18000, 0, None), // Memory cache + reg(8, Physical(0x27d050000), 0x4000, 0, None), // Streaming codec + reg(9, Physical(0x23b3d0000), 0x1000, 0, Some(0x10_0000)), // Push telemetry + reg(10, Physical(0x23b3c0000), 0x1000, 0, Some(0)), // Push telemetry readback + reg(12, Physical(0x26b45c000), 0x4000, 0, None), // ANE doorbell + reg(17, Sgx(0), 0x20000, 0, Some(0)), // GPU core + reg(31, Sgx(0xd04000), 0xc000, 0xd04000, Some(0)), // Fender configuration + reg(32, Sgx(0xd61000), 0x1000, 0xd61000, Some(0)), // GIFAF + reg(33, Sgx(0xe0c000), 0x4000, 0xe0c000, Some(0)), // CRE + reg(34, Sgx(0xd10000), 0x4000, 0xd10000, Some(0)), // CPMS + reg(37, Sgx(0xe10000), 0x1000, 0xe10000, Some(0)), // Fender scratch RAM + reg(40, Sgx(0xd00000), 0x4000, 0xd00000, Some(0)), // Fender multi-GPU configuration + reg(44, Sgx(0xd80000), 0x8000, 0, Some(0)), // Metrology sensors + ] +}; + +/// Slots of the 27.2 register table whose stock mode is read-write. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) const WRITABLE_V27_2: u64 = { + let mut mask = 0u64; + let mut slot = 0; + while slot < 60 { + if matches!(slot, 0 | 2 | 3 | 5..=9 | 12 | 17 | 25..=27 | 31..=40 | 42..=48 | 52..=55 | 58) { + mask |= 1 << slot; + } + slot += 1; + } + mask +}; diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 155bda714e9d9..70116b7116622 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -2,6 +2,7 @@ //! Bounded M3 compute and graphics submissions through the common DRM scheduler/syncobjs. use kernel::{c_str,dma_fence::*,drm::sched,prelude::*,sync::{Arc,Mutex},new_mutex,xarray}; use crate::{file,m3::agx_uapi,mmu,queue,m3::m3_drm::Shared}; +use crate::alloc::Allocator as _; use core::sync::atomic::{AtomicBool, Ordering}; #[derive(Default)] pub(crate) struct Completion; @@ -53,7 +54,12 @@ pub(crate) struct Packet { /// Who submitted the packet, for the failure log only. pub(crate) owner:Owner, vm_job:Pin>>>, + /// G14 firmware 27.2: the compute preemption buffer in the packet's VM, kept until retirement. + pub(crate) preempt:Option>, } +/// The runtime a queue's packets go to: the M3 runtime or the G14 firmware-27.2 compute runtime. +#[derive(Clone)] +pub(crate) enum Sink { M3(Shared), G14V27_2(Arc) } /// The process and thread that submitted a packet, recorded in the submit ioctl. Only logged: /// a renamed task leaves a stale name, which is harmless. #[derive(Copy,Clone)] @@ -118,9 +124,9 @@ impl Packet { } } } -pub(crate) struct Job {shared:Shared,packet:Arc} +pub(crate) struct Job {shared:Sink,packet:Arc} /// Timeout state of a [`Job`], owned by the scheduler's timeout worker. -pub(crate) struct JobTimeout {shared:Shared,packet:Arc} +pub(crate) struct JobTimeout {shared:Sink,packet:Arc} impl sched::JobImpl for Job { type TimeoutData = JobTimeout; fn timeout_data(&self)->JobTimeout { @@ -129,7 +135,11 @@ impl sched::JobImpl for Job { fn run(job:&mut Self)->Result> { // Queue the packet and return its fence; the completion worker publishes and retires // it, so the scheduler can hand over further ready jobs meanwhile. - if let Err(e)=crate::m3::m3_runtime::Runtime::submit(&job.shared,job.packet.clone()) { + let submitted=match &job.shared { + Sink::M3(shared)=>crate::m3::m3_runtime::Runtime::submit(shared,job.packet.clone()), + Sink::G14V27_2(runtime)=>runtime.submit(job.packet.clone()), + }; + if let Err(e)=submitted { pr_err!("M3 scheduler: submission failed {:?}\n",e); // submit() failed before this packet could be published. job.packet.release_guard();job.packet.finish(Err(e)); @@ -137,13 +147,23 @@ impl sched::JobImpl for Job { Ok(Some(Fence::from_fence(&job.packet.completion))) } fn timed_out(job:&mut JobTimeout,_finished:bool)->sched::Status { + let shared=match &job.shared { + Sink::M3(shared)=>shared.clone(), + Sink::G14V27_2(runtime)=>{ + // The runtime's own command timeout fails a hung GPU; a healthy one is late. + if runtime.healthy() {return sched::Status::NoHang;} + runtime.withdraw(&job.packet); + job.packet.finish(Err(EIO)); + return sched::Status::NoDevice; + } + }; // Retain the publishing branch's explicit diagnostic override. if !crate::m3::m3_params::timeout_nohang() { - if let Some(r)=Option::as_mut(&mut *job.shared.lock()) {r.health().mark_failed();} - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + if let Some(r)=Option::as_mut(&mut *shared.lock()) {r.health().mark_failed();} + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(ETIMEDOUT));return sched::Status::NoDevice; } - let guard=job.shared.lock(); + let guard=shared.lock(); let Some(runtime)=guard.as_ref() else { job.packet.finish(Err(ENODEV)); return sched::Status::NoDevice; @@ -154,12 +174,15 @@ impl sched::JobImpl for Job { // device loss or corrupting an already signaled fence. if runtime.health().healthy() { return sched::Status::NoHang; } drop(guard); - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(EIO)); sched::Status::NoDevice } fn cancel(job:&mut Self) { - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + match &job.shared { + Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} + Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), + } job.packet.finish(Err(ECANCELED)); } } @@ -175,7 +198,10 @@ impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { } pub(crate) struct Queue { entity:sched::Entity,_scheduler:Arc>, - shared:Shared,vm:mmu::Vm,usc:u64,fences:FenceContexts, + shared:Sink,vm:mmu::Vm,usc:u64,fences:FenceContexts, + /// G14 firmware 27.2: the VM's private allocator and the size of the per-packet + /// preemption buffer it provides. + preempt_alloc:Option<(Arc>,usize)>, /// Whether the SoC advertises early tiling (`m3_soc::Features::fragment_dependency`). early_tiling:bool, wide_visibility:bool, @@ -190,8 +216,19 @@ impl Queue { let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, - shared,vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, - early_tiling,wide_visibility,urgency}) + shared:Sink::M3(shared),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, + early_tiling,wide_visibility,urgency,preempt_alloc:None}) + } + /// A G14 firmware-27.2 compute queue: the same front end, published by that runtime. + pub(crate) fn new_g14_v27_2(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, + ualloc_priv:Arc>,preempt_bytes:usize)->Result { + agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; + let urgency=3u8.saturating_sub(priority.min(3) as u8); + let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, + 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; + Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, + shared:Sink::G14V27_2(runtime),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_g14_queue"),kernel::static_lock_class!())?, + early_tiling:false,wide_visibility:false,urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes))}) } } impl queue::Queue for Queue { @@ -201,6 +238,8 @@ impl queue::Queue for Queue { let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { + // The G14 firmware-27.2 runtime is compute-only. + if self.preempt_alloc.is_some() {return Err(EINVAL);} if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); return Err(e); @@ -237,13 +276,21 @@ impl queue::Queue for Queue { pr_err!("M3 compute translation rejected {:?}: stream={:#x}..{:#x} helper={:?}\n",e,payload.control_stream_base,payload.control_stream_end,payload.helper); EINVAL })?; - crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + // The launch check decodes the 26.x G15 CDM launch format; G14 streams differ. + if self.preempt_alloc.is_none() { + crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + } timestamps.push([Destination::resolve(objects,payload.timestamps.start)?, Destination::resolve(objects,payload.timestamps.end)?,None,None],GFP_KERNEL)?; commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc}),GFP_KERNEL)?; } parser.finish().map_err(|_|EINVAL)?; - let packet=Arc::new(Packet{vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, + let preempt=match &self.preempt_alloc { + Some((alloc,bytes)) if commands.iter().any(|c| matches!(c, Command::Compute(_))) => + Some(alloc.lock().array_empty::(*bytes)?), + _ => None, + }; + let packet=Arc::new(Packet{preempt,vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, completion:self.fences.new_fence(0,Completion)?.into(), finish_claimed:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index eafd5732bceac..cb64aa8f1ecbc 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -81,7 +81,7 @@ mod agx_resources; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_status; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_uapi; +pub(crate) mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -125,7 +125,7 @@ mod m3_rtkit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_runtime; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod m3_submit; +pub(crate) mod m3_submit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_thermal; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -201,11 +201,15 @@ pub(crate) mod m3_soc; mod t8122_hwdata; -mod m3_init_26; +pub(crate) mod m3_init_26; mod m3_profile; -mod m3_mmio_26; +pub(crate) mod m3_mmio_26; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_power_26; -mod m3_channel_format; +pub(crate) mod m3_channel_format; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) use m3_channel_format::{idle_cursor, submission_entry, Action, CONTROL_BYTES}; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) use m3_init_storage::DEVICE_CONTROL; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 484a471f1190c..a4fd3c7a7a594 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4521,3 +4521,142 @@ mod execution_context_tests { assert!(pick_returned(core::iter::empty(), &returns, &fences, 0).is_none()); } } + +/// The word GPU firmware 27.2 on G14 exchanges through the handoff region's magic fields. +#[cfg(CONFIG_DRM_ASAHI_G15)] +const MAGIC_G14_V27_2: u64 = 0x4b1d000000000003; + +/// The loader's UAT regions as GPU firmware 27.2 on G14 uses them. The driver mirrors its +/// kernel window into the firmware's shared second-level table and names its own trees in +/// TTBAT context 0 before the ASC starts. +#[cfg(CONFIG_DRM_ASAHI_G15)] +pub(crate) struct FirmwareWindow { + handoff: UatRegion, + ttbs: UatRegion, + tables: UatRegion, + shared_l2: UatRegion, + entries: KVec, + lower_root: u64, + pa_mask: u64, +} + +#[cfg(CONFIG_DRM_ASAHI_G15)] +impl FirmwareWindow { + /// Maps the four regions. Fails with `EBUSY` unless the handoff is idle and the shared + /// table and context 0 are empty. + pub(crate) fn reserve(dev: &device::Device, geometry: UatGeometry) -> Result { + let handoff = Uat::map_region(dev, c"handoff", HANDOFF_SIZE, true)?; + let ttbs = Uat::map_region(dev, c"ttbs", UAT_PGSZ, true)?; + let tables = Uat::map_region(dev, c"pagetables", UAT_PGSZ, true)?; + let shared_l2 = Uat::map_region(dev, c"shared-l2", UAT_PGSZ, true)?; + let this = Self { + handoff, ttbs, tables, shared_l2, + entries: KVec::from_elem(0u64, UAT_PGSZ / 8, GFP_KERNEL)?, + lower_root: 0, + pa_mask: ((1u64 << geometry.oas) - 1) & !(UAT_PGMSK as u64), + }; + let h = this.handoff(); + if h.magic_ap.load(Ordering::Acquire) != 0 || h.magic_fw.load(Ordering::Acquire) != 0 + || h.lock_ap.load(Ordering::Acquire) != 0 || h.lock_fw.load(Ordering::Acquire) != 0 + || !this.empty() { + return Err(EBUSY); + } + Ok(this) + } + + fn handoff(&self) -> &Handoff { + // SAFETY: map_region checked the size of the handoff reservation; only its aligned + // atomic fields are used. + unsafe { &*self.handoff.map.ptr().cast::() } + } + + fn shared(&self) -> &[AtomicU64; UAT_PGSZ / 8] { + // SAFETY: the shared-l2 reservation is one mapped 16 KiB table. + unsafe { &*self.shared_l2.map.ptr().cast::<[AtomicU64; UAT_PGSZ / 8]>() } + } + + fn context(&self) -> &SlotTTBS { + // SAFETY: the TTBAT reservation holds at least one aligned slot. + unsafe { &*self.ttbs.map.ptr().cast::() } + } + + fn empty(&self) -> bool { + let context = self.context(); + self.shared().iter().all(|w| w.load(Ordering::Acquire) == 0) + && context.ttb0.load(Ordering::Acquire) == 0 && context.ttb1.load(Ordering::Acquire) == 0 + } + + /// The regions to adopt the UAT from. + pub(crate) fn regions(&self) -> AdoptedRegions { + AdoptedRegions { + handoff: self.handoff.base..self.handoff.base + UAT_PGSZ as PhysicalAddr, + ttbs: self.ttbs.base..self.ttbs.base + UAT_PGSZ as PhysicalAddr, + kernel_root: self.tables.base, + } + } + + /// Copies the kernel window's second-level entries from `uat` and writes all of its tables + /// back. Call after the last allocation the firmware is to reach. + pub(crate) fn mirror(&mut self, uat: &Uat) -> Result { + let mask = self.pa_mask; + let root = uat.kernel_window_root(); + let entries = &mut self.entries; + // SAFETY: the adopted UAT's driver-owned window root and its second level are live + // RAM tables. + unsafe { + let upper = pgtable::with_root_entries(None, root, 3, |w| w[2].load(Ordering::Acquire))?; + if upper & 3 != 3 { return Err(EINVAL); } + pgtable::with_root_entries(None, upper & mask, entries.len(), |w| { + for (entry, word) in entries.iter_mut().zip(w) { + *entry = word.load(Ordering::Acquire); + } + })?; + } + // The window's last 4 GiB is the MMIO range: its register mappings use one table. + let first_io = (0xf_0000_0000u64 >> 25) as usize; + if entries[first_io..].iter().filter(|w| **w != 0).count() != 1 { return Err(EINVAL); } + for &w in entries.iter().filter(|w| **w != 0) { + if w & 3 != 3 { return Err(EINVAL); } + crate::g15::uat::clean_page(w & mask)?; + } + crate::g15::uat::clean_lower(uat)?; + self.lower_root = uat.kernel_lower_root(); + Ok(()) + } + + /// Installs the mirrored window and names the driver's trees in context 0. + pub(crate) fn install(&self) -> Result { + if !self.empty() || self.lower_root == 0 { return Err(EBUSY); } + for (word, value) in self.shared().iter().zip(self.entries.iter()) { + if *value != 0 { word.store(*value, Ordering::Release); } + } + let context = self.context(); + context.ttb0.store(self.lower_root | TTBR_VALID, Ordering::Release); + context.ttb1.store(self.tables.base | TTBR_VALID, Ordering::Release); + pgtable::clean_poc(self.ttbs.map.ptr(), size_of::()); + pgtable::clean_poc(self.shared_l2.map.ptr(), UAT_PGSZ); + pgtable::poc_barrier(); + Ok(()) + } + + /// Announces the host to the firmware; call just before starting the ASC. + pub(crate) fn announce(&self) { + self.handoff().magic_ap.store(MAGIC_G14_V27_2, Ordering::Release); + fence(Ordering::SeqCst); + } + + /// Whether the firmware has answered the announcement. + pub(crate) fn answered(&self) -> bool { + self.handoff().magic_fw.load(Ordering::Acquire) == MAGIC_G14_V27_2 + } + + /// Whether the firmware still names the shared table and context 0 as installed. + pub(crate) fn intact(&self) -> bool { + // SAFETY: the firmware's kernel root is one mapped 16 KiB table. + let root = unsafe { &*self.tables.map.ptr().cast::<[AtomicU64; 4]>() }; + let context = self.context(); + root[2].load(Ordering::Acquire) & self.pa_mask == self.shared_l2.base + && context.ttb0.load(Ordering::Acquire) == self.lower_root | TTBR_VALID + && context.ttb1.load(Ordering::Acquire) == self.tables.base | TTBR_VALID + } +} diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index 0c9e6f62b5bbe..e3ce17cb7cb7e 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -697,6 +697,23 @@ impl> GpuArray { } } +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +impl> GpuArray { + /// Aligned index in a shared firmware ring, accessed without borrowing its payload. + pub(crate) fn shared_index(&self, offset: usize) -> Result<&core::sync::atomic::AtomicU32> { + if offset.checked_add(4).is_none_or(|end| end > self.len) { + return Err(EINVAL); + } + let ptr = self.raw.wrapping_add(offset).cast::(); + if !ptr.is_aligned() { + return Err(EINVAL); + } + // SAFETY: bounds and alignment checked; the shared ring ABI accesses + // this word only in aligned 32-bit transactions while the ring is live. + Ok(unsafe { core::sync::atomic::AtomicU32::from_ptr(ptr) }) + } +} + impl> Deref for GpuArray { type Target = GpuOnlyArray; diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 1fde883e6c6df..658c98de1e77a 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -349,6 +349,13 @@ impl Resources<'_> { .expect("64-bit read failed!") } + /// The G14 Fender operating-point word: requested index in bits 3:0, request pending in + /// bit 4. Sampled while the firmware holds the GPU powered. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + pub(crate) fn operating_point(&self) -> u32 { + self.sgx_read32::<0xd01000>() + } + /// Initialize the MMIO registers for the GPU. pub(crate) fn init_mmio(&self) -> Result { // Nothing to do for now... diff --git a/drivers/gpu/drm/asahi/rtkit_dump.c b/drivers/gpu/drm/asahi/rtkit_dump.c new file mode 100644 index 0000000000000..c7b147c35a286 --- /dev/null +++ b/drivers/gpu/drm/asahi/rtkit_dump.c @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size); + +/* RTKit owns its immutable shadow only during the crash callback. */ +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size) +{ + void *copy; + + if (!size) + return; + copy = vmalloc(size); + if (copy) { + memcpy(copy, data, size); + dev_coredumpv(dev, copy, size, GFP_KERNEL); + } +} diff --git a/rust/macros/versions.rs b/rust/macros/versions.rs index b13a5d55c0e17..21a6d5985332c 100644 --- a/rust/macros/versions.rs +++ b/rust/macros/versions.rs @@ -93,7 +93,7 @@ static AGX_VERSIONS: VersionConfig = VersionConfig { fields: &["G", "V"], enums: &[ &["G13", "G14", "G14X"], - &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5"], + &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5", "V27_2"], ], versions: &[ &["G13", "V12_3"], @@ -276,8 +276,11 @@ fn filter_versions( } pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { - let config = match attr.to_string().as_str() { - "AGX" => &AGX_VERSIONS, + // AGX_V27_2 is AGX plus G14/V27_2: only the firmware 27.2 root and hardware-data layouts + // are instantiated for that version. + let group = attr.to_string(); + let config = match group.as_str() { + "AGX" | "AGX_V27_2" => &AGX_VERSIONS, _ => panic!("Unknown version group {}", attr), }; @@ -321,7 +324,8 @@ pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { body.extend(it); - for ver in config.versions { + let candidate = (group == "AGX_V27_2").then_some(&["G14", "V27_2"][..]); + for ver in config.versions.iter().copied().chain(candidate) { let tag = ver.join(""); let mut ver_num = Vec::::new(); for (i, comp) in ver.iter().enumerate() { From a47acf0bf9faf421fb4a6cb83eb86eee9597b777 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 06:40:39 -0500 Subject: [PATCH 02/10] drm/asahi: run the G14 firmware-27.2 runtime from firmware notifications Review asked for no sleep or poll loops where the firmware gives a signal. The runtime polled from delayed work every 1 ms while busy and every 20 ms when idle, and dropped every endpoint message. The firmware sends endpoint 0x20 a message after it publishes event, statistics or log records. Each message now queues one run of the service, which consumes the rings and retires completed commands; there is no idle poll and no timer. The DRM scheduler's job timeout runs the service once more, so a command the firmware never completes still hits the command timeout. A firmware crash also runs it. The service runs on its own ordered workqueue. Stop waits for published work on a condition variable the service signals, detaches the message route so nothing queues more work, and drains the workqueue, replacing the fsleep loops and the fixed 20 ms sleep. Start waits for the firmware's ready status (+0x14) instead of a fixed 1 s, and fails if the command handlers are not installed in time instead of ignoring the timeout. Installation is acknowledged by the firmware clearing the request word (+0x4c24); the old wait also required the powered-stage word (+0x4c00) to read 2, which it never did after the handlers were installed, so it always ran out its 500 ms. A failed start names the step. These and the idle-policy and running-flag waits stay bounded checks of a shared word: the firmware writes it and sends no message, as with the existing G14 device-control channel. The completion stamp is written before the firmware's post-processing advances the queue's retired position, which sends no message. When the stamp is there and the position is not, the service waits for the position for at most 2 ms. Faster retirement showed that the firmware keeps a retired command's tracking slot (+0x94) linked for a while, and can link one again after releasing it; with a fixed round-robin the pool stopped at the first reuse. Pump now takes the next slot that is neither in flight nor held. If all are held it kicks the firmware's retirement scan once and the next notification, submission or scheduler timeout retries; there is no message for a slot's release. The stop line reports the notifications received, how often the position wait ran and how many held slots were passed over. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g14_v27_2.rs | 316 +++++++++++++++++--------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 16 +- drivers/gpu/drm/asahi/m3/m3_submit.rs | 2 + 3 files changed, 226 insertions(+), 108 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index ea585628b1e4f..91e327b361c81 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -8,24 +8,26 @@ //! through the 26.x submission front end (`m3_submit`): each compute command is encoded in the //! 27.2 layout and published, in order, on the root's queue. Render commands are refused. //! -//! Completion follows the queue's retired position, which the firmware advances in order. -//! The firmware's event, statistics, log and trace rings are consumed as they fill, since -//! the firmware waits for space in them. +//! The runtime is driven by the firmware's endpoint-0x20 notifications, which it sends after +//! publishing records on its event, statistics and log rings: each one runs the service, which +//! consumes those rings (the firmware waits for space in them) and retires completed commands. +//! Completion follows the queue's retired position, which the firmware advances in order. There +//! is no timer: the DRM scheduler's job timeout runs the service as the backstop for a hang. use core::ops::Range; -use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ device, drm::sched, - new_delayed_work, new_mutex, + new_condvar, new_mutex, new_spinlock, new_work, platform, prelude::*, soc::apple::rtkit, - sync::{aref::ARef, Arc, Mutex}, + sync::{aref::ARef, Arc, ArcBorrow, CondVar, Mutex, SpinLock}, time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, uapi, - workqueue::{self, impl_has_delayed_work, DelayedWork, WorkItem}, + workqueue::{impl_has_work, OwnedQueue, Work, WorkItem}, }; use crate::{ @@ -45,8 +47,10 @@ const ASC_RUN: u32 = 0x10; /// Commands slower than this are a hang; the firmware state is then not trusted. const COMMAND_TIMEOUT_MS: i64 = 5000; -/// Idle polling keeps the firmware's rings drained and bounds completion latency. -const IDLE_POLL_MS: u64 = 20; +/// How long `stop` lets published work retire before it fails what is left. +const STOP_DRAIN_MS: u32 = 2000; +/// Bound on the wait between a command's completion stamp and its retired position. +const RETIRE_WAIT_US: i64 = 2000; /// The ASC control page, kept mapped until the firmware is stopped. pub(crate) struct AscControl(*mut u8); @@ -83,37 +87,87 @@ impl Drop for AscControl { } } +/// Where the firmware's messages go: the runtime once it exists, nowhere before or after. +#[pin_data] +pub(crate) struct Notify { + dev: ARef, + #[pin] + runtime: SpinLock>>, + /// Endpoint-0x20 messages received, reported when the firmware stops. + messages: AtomicU64, +} + +impl Notify { + fn new(dev: &device::Device) -> Result> { + Arc::pin_init(pin_init!(Self { + dev: dev.into(), + runtime <- new_spinlock!(None, "g14_v27_2::Notify::runtime"), + messages: AtomicU64::new(0), + }), GFP_KERNEL) + } + + /// Queues one service run if a runtime is attached. A run already queued covers this one. + fn wake(&self) { + if let Some(runtime) = self.runtime.lock().as_ref() { + let _ = runtime.queue.enqueue::, 0>(runtime.clone()); + } + } + + fn attach(&self, runtime: Arc) { + *self.runtime.lock() = Some(runtime); + } + + /// After this returns, nothing queues service work. + fn detach(&self) -> Option> { + self.runtime.lock().take() + } +} + /// RTKit operations of the GPU firmware: its crash log lives in the loader's data segment. pub(crate) struct Firmware; #[vtable] impl rtkit::Operations for Firmware { - type Data = Arc>; + type Data = Arc; type Buffer = crate::g17::CrashLog; const COPROC_PLACES_BUFFERS: bool = true; - fn shmem_map(dev: kernel::sync::ArcBorrow<'_, ARef>, iova: usize, size: usize) -> Result { - crate::g17::CrashLog::from_firmware(&dev, iova, size) + fn shmem_map(notify: ArcBorrow<'_, Notify>, iova: usize, size: usize) -> Result { + crate::g17::CrashLog::from_firmware(¬ify.dev, iova, size) } - fn crashed(dev: kernel::sync::ArcBorrow<'_, ARef>, log: Option<&[u8]>) { + fn crashed(notify: ArcBorrow<'_, Notify>, log: Option<&[u8]>) { unsafe extern "C" { fn asahi_save_rtkit_dump(dev: *mut core::ffi::c_void, data: *const u8, size: usize); } - dev_err!(&**dev, "GPU firmware crashed\n"); + dev_err!(&*notify.dev, "GPU firmware crashed\n"); if let Some(log) = log { // SAFETY: RTKit and the device remain live throughout this synchronous copy. - unsafe { asahi_save_rtkit_dump(dev.as_raw().cast(), log.as_ptr(), log.len()) }; + unsafe { asahi_save_rtkit_dump(notify.dev.as_raw().cast(), log.as_ptr(), log.len()) }; } + // The service sees the crash and fails outstanding work. + notify.wake(); } - fn recv_message(_dev: kernel::sync::ArcBorrow<'_, ARef>, _ep: u8, _message: u64) {} + /// The firmware sends endpoint 0x20 a message after it publishes event, statistics or log + /// records. Whatever the message, the service reads every ring and the queue's position, + /// so each one is a wakeup. + fn recv_message(notify: ArcBorrow<'_, Notify>, ep: u8, _message: u64) { + if ep == EP_FIRMWARE { + notify.messages.fetch_add(1, Ordering::Relaxed); + notify.wake(); + } + } } type Peer = Pin>>; -/// Polls `done` every millisecond, draining the firmware's rings, for at most `ms`. +/// Waits for a shared-word acknowledgement, checking `done` every millisecond and draining the +/// firmware's rings, for at most `ms`. Only for the start/stop handshakes whose acknowledgement +/// is a word the firmware writes with no message: the ready status, the command-service +/// installation, device-control (idle-policy) consumption and the running flag. The existing G14 +/// path waits for its device-control channel the same way (`channel::TxChannel::wait_for`). fn wait(root: &RootV27_2, ms: i64, mut done: impl FnMut() -> Result) -> Result { let start = Instant::::now(); loop { @@ -170,8 +224,9 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?; let control = asc.read(ASC_CPU_CONTROL); if control & ASC_RUN != 0 { return Err(EBUSY); } + let notify = Notify::new(dev)?; let mut peer = KBox::pin( - rtkit::RtKit::::new(dev, None, 0, Arc::new(ARef::from(dev), GFP_KERNEL)?)?, + rtkit::RtKit::::new(dev, None, 0, notify.clone())?, GFP_KERNEL)?; let resources = crate::regs::Resources::new(pdev)?; let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; @@ -198,29 +253,37 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta // From here the firmware may read everything the window names: nothing is freed. let mut booted = false; + let mut step = "loader handoff"; let result = (|| -> Result { let start = Instant::::now(); while !window.answered() { if start.elapsed() >= Delta::from_millis(1000) { return Err(ETIMEDOUT); } fsleep(Delta::from_millis(1)); } + step = "RTKit boot"; peer.as_mut().boot()?; booted = true; peer.as_mut().start_endpoint(EP_FIRMWARE)?; peer.as_mut().start_endpoint(EP_DOORBELL)?; if !window.intact() { return Err(EIO); } + step = "initialization"; peer.as_mut().send_message(EP_FIRMWARE, gpu::init_message(root.gpu_va().get()))?; - // Let initialization settle before the first control record. - let _ = wait(&root, 1000, || Ok(false)); + // The firmware sets status +0x14 when it has initialized; the first control record + // waits for it. + wait(&root, 2000, || root.initialized())?; + step = "keep-powered policy"; set_idle_policy(&root, &mut peer, false)?; - // Command-handler installation completes during powered initialization. - let _ = wait(&root, 500, || Ok(root.command_service()? == (2, 0))); + // Powered initialization installs the command handlers and then clears the + // installation request the root set (+0x4c24). + step = "command-handler installation"; + wait(&root, 500, || root.commands_installed())?; + step = "boot job"; root.publish_boot_job(resources.operating_point())?; peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; wait(&root, 3000, || root.boot_job_complete()) })(); if let Err(e) = result { - dev_err!(dev, "GPU firmware 27.2 did not start: {:?}\n", e); + dev_err!(dev, "GPU firmware 27.2 did not start: {}: {:?}\n", step, e); halt_unowned(dev, peer, root, asc, booted); core::mem::forget(window); core::mem::forget(pool); @@ -229,7 +292,7 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta } // The firmware keeps using the window until it is stopped; it stays for the life of the boot. core::mem::forget(window); - let backend = Backend::start(&drm, dev, peer, root, graph, pool, asc, cfg)?; + let backend = Backend::start(&drm, dev, notify, peer, root, graph, pool, asc, cfg)?; Ok(Started { backend, drm, binding, resources }) } @@ -256,6 +319,12 @@ struct State { waiting_unlink: bool, /// Publications and retirements counted on the queue's position block. published: u64, + /// Completion stamps seen before the retired position they precede. + late: u64, + /// Pool slots holding a published command, one bit each. + busy: u64, + /// Free slots passed over because the firmware still held them. + skipped: u64, retired_total: u64, retired_raw: u32, capacity: u32, @@ -270,64 +339,56 @@ pub(crate) struct Runtime { dev: ARef, graph: Arc, healthy: AtomicBool, - /// Poll work queued or running; `stop` waits for zero so no work outlives the module. - queued: AtomicU32, + notify: Arc, + /// Runs the service; only `Notify::wake` queues on it, and `stop` drains it. + queue: OwnedQueue, #[pin] state: Mutex>, + /// Signalled when no work is pending or published, or the runtime fails. #[pin] - poll: DelayedWork, + idle: CondVar, + #[pin] + work: Work, } -impl_has_delayed_work! { - impl HasDelayedWork for Runtime { self.poll } +impl_has_work! { + impl HasWork for Runtime { self.work } } impl WorkItem for Runtime { type Pointer = Arc; fn run(this: Arc) { - let busy = this.service(); - if this.healthy.load(Ordering::Acquire) { - this.schedule(if busy { 1 } else { IDLE_POLL_MS }); - } - this.queued.fetch_sub(1, Ordering::AcqRel); + this.service(); } } #[pinned_drop] impl PinnedDrop for Runtime { fn drop(self: Pin<&mut Self>) { - // The poll work holds a reference while scheduled, so this runs only once the - // runtime is idle; stop the firmware first if no one has. + // `Notify` holds a reference until `stop`, so this runs only after it, or for a + // runtime that never took over the firmware. if self.state.lock().is_some() { self.stop(); } } } impl Runtime { - fn schedule(self: &Arc, ms: u64) { - if !self.healthy() { return; } - self.queued.fetch_add(1, Ordering::AcqRel); - if workqueue::system_highpri() - .enqueue_delayed::, 0>(self.clone(), msecs_to_jiffies(ms as u32)).is_err() { - // Already queued: that run accounts for itself. - self.queued.fetch_sub(1, Ordering::AcqRel); - } - } - pub(crate) fn healthy(&self) -> bool { self.healthy.load(Ordering::Acquire) } - /// Queues a packet; the poll work publishes and retires it. + /// Runs the service once more: the DRM scheduler's job timeout calls this, so a command the + /// firmware never completes still reaches the command timeout. + pub(crate) fn wake(&self) { self.notify.wake(); } + + /// Queues a packet and publishes what the pool has room for; the firmware's completion + /// notifications run the service, which retires it and publishes the rest. pub(crate) fn submit(self: &Arc, packet: Arc) -> Result { if !self.healthy() { return Err(EIO); } if packet.commands.is_empty() { return Err(ENOTSUPP); } - { - let mut guard = self.state.lock(); - let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; - state.pending.push((packet, 0), GFP_KERNEL)?; - self.pump(state); - } - self.schedule(1); + let mut guard = self.state.lock(); + let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + state.pending.push((packet, 0), GFP_KERNEL)?; + self.pump(state); Ok(()) } @@ -346,6 +407,7 @@ impl Runtime { fn fail_all(&self, state: &mut State, error: Error) { self.healthy.store(false, Ordering::Release); + self.idle.notify_all(); for (packet, _) in state.pending.drain(..) { packet.release_guard(); packet.finish(Err(error)); @@ -360,19 +422,30 @@ impl Runtime { /// Publishes pending commands while pool slots are free. fn pump(&self, state: &mut State) { 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. - match state.pool.registered(state.next_slot) { - Ok(false) => {} - Ok(true) => { - if !state.waiting_unlink { - // Wake the firmware's service once so its retirement scan runs. - state.waiting_unlink = true; - let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK); - } - return; + // A slot is reused only once the firmware has unlinked it from its tracking list + // (+0x94). It normally has by the time the pool comes round to it, but the firmware + // can link a retired slot again and keep it; take the next free slot instead. + let mut chosen = None; + for k in 0..POOL_SLOTS { + let slot = (state.next_slot + k) % POOL_SLOTS; + if state.busy & (1 << slot) != 0 { continue; } + match state.pool.registered(slot) { + Ok(false) => { chosen = Some(slot); break; } + Ok(true) => state.skipped += 1, + Err(e) => { self.fail_all(state, e); return; } } - Err(e) => { self.fail_all(state, e); return; } } + let Some(slot) = chosen else { + if !state.waiting_unlink { + // Every free slot is held: wake the firmware's service once so its + // retirement scan runs. The scan sends nothing; the next notification, + // submission or scheduler timeout retries. + state.waiting_unlink = true; + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK); + } + return; + }; + state.next_slot = slot; state.waiting_unlink = false; let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); let Command::Compute(control) = packet.commands[index] else { @@ -405,6 +478,7 @@ impl Runtime { 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; @@ -430,26 +504,47 @@ impl Runtime { } } - /// Retires completed commands, publishes more and keeps the firmware's rings drained. - /// Returns whether work remains. - fn service(&self) -> bool { + /// Reads the queue's retired position into `retired_total`. + fn advance(&self, state: &mut State) -> Result { + let (_, raw) = state.root.progress()?; + if state.capacity != 0 && raw < state.capacity { + let delta = (raw + state.capacity - state.retired_raw) % state.capacity; + state.retired_total += u64::from(delta); + state.retired_raw = raw; + } + Ok(()) + } + + /// Retires completed commands, publishes more and consumes the firmware's rings. + fn service(&self) { let mut guard = self.state.lock(); - let Some(state) = Option::as_mut(&mut *guard) else { return false; }; + 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(); } + } + + fn service_locked(&self, state: &mut State) { let _ = state.root.drain(); if state.peer.is_crashed() { dev_err!(self.dev, "GPU firmware crashed; failing {} pending and {} published commands\n", state.pending.len(), state.inflight.len()); self.fail_all(state, EIO); - return false; + return; } - let raw = match state.root.progress() { - Ok((_, raw)) => raw, - Err(e) => { self.fail_all(state, e); return false; } - }; - if state.capacity != 0 && raw < state.capacity { - let delta = (raw + state.capacity - state.retired_raw) % state.capacity; - state.retired_total += u64::from(delta); - state.retired_raw = raw; + if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } + // The completion stamp is written before the firmware's post-processing advances the + // retired position, and that advance sends no message. If the front command's stamp + // is there but its position is not, the advance is imminent: wait for it, bounded, + // rather than for a notification that does not come. + if let Some((ordinal, stamp)) = state.inflight.first().map(|f| (f.ordinal, f.stamp)) { + if state.retired_total < ordinal && state.root.queue().1 >= stamp { + state.late += 1; + let start = Instant::::now(); + while state.retired_total < ordinal && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { + fsleep(Delta::from_micros(20)); + if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } + } + } } while !state.inflight.is_empty() { let front = &state.inflight[0]; @@ -458,6 +553,7 @@ impl Runtime { if let Err(e) = state.pool.retire(done.slot) { dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); } + state.busy &= !(1 << done.slot); state.retired += 1; if done.last { done.packet.retired(); @@ -469,30 +565,32 @@ impl Runtime { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); self.fail_all(state, ETIMEDOUT); - return false; + return; } break; } - if self.healthy() { self.pump(state); } - !state.inflight.is_empty() || !state.pending.is_empty() + if !self.healthy() { return; } + self.pump(state); } /// 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 start = Instant::::now(); - while start.elapsed() < Delta::from_millis(2000) { - if !self.service() { break; } - fsleep(Delta::from_millis(1)); + // Let published work retire; the service signals `idle` when nothing is left. + { + let mut guard = self.state.lock(); + 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)); + } } self.healthy.store(false, Ordering::Release); - // No poll work may remain queued or running once this returns. - let start = Instant::::now(); - while self.queued.load(Ordering::Acquire) != 0 && start.elapsed() < Delta::from_millis(2000) { - fsleep(Delta::from_millis(5)); - } - // Let a run that just accounted for itself return out of this module. - fsleep(Delta::from_millis(20)); + // 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()); + self.queue.drain(); let mut guard = self.state.lock(); let Some(mut state) = guard.take() else { return; }; self.fail_all(&mut state, ENODEV); @@ -505,8 +603,9 @@ impl Runtime { kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) }); state.asc.halt(); - dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={}\n", - allowed, running, forced, state.submitted, state.retired); + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={}\n", + allowed, running, forced, state.submitted, state.retired, + self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped); if running != Ok(0) && forced != Some(Ok(())) { dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); } @@ -537,6 +636,7 @@ impl Backend { fn start( drm: &crate::driver::AsahiDrmDevice, dev: &device::Device, + notify: Arc, peer: Peer, root: crate::fw::types::GpuObject, graph: Arc, @@ -548,14 +648,18 @@ impl Backend { // state. Every failure after the state is moved in goes through Runtime::stop, which // halts the firmware and keeps all of its memory. let runtime_graph = graph.clone(); - let runtime = match Arc::pin_init(try_pin_init!(Runtime { - dev: dev.into(), - graph: runtime_graph, - healthy: AtomicBool::new(true), - queued: AtomicU32::new(0), - state <- new_mutex!(None, "g14_v27_2::Runtime::state"), - poll <- new_delayed_work!("g14_v27_2::Runtime::poll"), - }), GFP_KERNEL) { + let runtime_notify = notify.clone(); + let runtime = match OwnedQueue::new_ordered(c"asahi-g14-v27-2").and_then(|queue| + Arc::pin_init(try_pin_init!(Runtime { + dev: dev.into(), + graph: runtime_graph, + healthy: AtomicBool::new(true), + notify: runtime_notify, + queue, + state <- new_mutex!(None, "g14_v27_2::Runtime::state"), + idle <- new_condvar!("g14_v27_2::Runtime::idle"), + work <- new_work!("g14_v27_2::Runtime::work"), + }), GFP_KERNEL)) { Ok(runtime) => runtime, Err(e) => { halt_unowned(dev, peer, root, asc, true); @@ -585,6 +689,9 @@ impl Backend { next_slot: 0, waiting_unlink: false, published: 0, + late: 0, + busy: 0, + skipped: 0, retired_total: 0, retired_raw: head, capacity, @@ -593,7 +700,10 @@ impl Backend { submitted: 0, retired: 0, }); - runtime.schedule(IDLE_POLL_MS); + // From here the firmware's messages run the service; one run consumes anything it + // published before. + notify.attach(runtime.clone()); + notify.wake(); // One run queue per DRM scheduler priority (the front end maps queue priorities 0-3). let scheduler = match sched::Scheduler::new(drm.as_ref().as_ref(), 4, POOL_SLOTS as u32 - 1, 0, 10000, c"asahi_g14_sched").and_then(|s| Arc::new(s, GFP_KERNEL).map_err(Into::into)) { diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 0ee4c1ec07ed4..1690ff60342be 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -450,7 +450,7 @@ impl RootV27_2 { if operating_point & 0x10 != 0 || index == 0 || index > self.graph.dyncfg.pwr.perf_max_pstate || self.idle_progress()? != [1; 3] || self.idle_acknowledgement()? != Self::word(&self.globals, 0xe40)? - || self.command_service()?.1 != 0 { + || !self.commands_installed()? { return Err(EAGAIN); } let producer = self.channels[2 * SUBMISSION_RING].shared_index(0x20)?; @@ -500,15 +500,21 @@ impl RootV27_2 { consume(&self.channels[2 * TRACE_RING], 0, TRACE_RECORDS) } + /// Shared status +0x14: the firmware sets it to 1 once it has initialized. + pub(crate) fn initialized(&self) -> Result { + Ok(Self::word(&self.status, 0x14)? == 1) + } + /// Shared status +0x10: nonzero while the firmware reports itself running. pub(crate) fn firmware_running(&self) -> Result { Self::word(&self.status, 0x10) } - /// Command-service state: (powered stage, pending installation request). - /// Engine entries may be published only at (2, 0). - pub(crate) fn command_service(&self) -> Result<(u32, u32)> { - Ok((Self::word(&self.control, 0x4c00)?, Self::word(&self.control, 0x4c24)?)) + /// Whether the firmware has installed its command handlers: it clears the installation + /// request (+0x4c24), which the root sets, once powered initialization has copied them. + /// Engine entries may be published only after that. + pub(crate) fn commands_installed(&self) -> Result { + Ok(Self::word(&self.control, 0x4c24)? == 0) } pub(crate) fn idle_acknowledgement(&self) -> Result { diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 70116b7116622..b8a377264be8f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -151,6 +151,8 @@ impl sched::JobImpl for Job { Sink::M3(shared)=>shared.clone(), Sink::G14V27_2(runtime)=>{ // The runtime's own command timeout fails a hung GPU; a healthy one is late. + // Run its service once, so a hang is found without a notification. + runtime.wake(); if runtime.healthy() {return sched::Status::NoHang;} runtime.withdraw(&job.packet); job.packet.finish(Err(EIO)); From 660936a3b0509ca334fe6dded99a48cb0c33e39c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 12:54:38 -0500 Subject: [PATCH 03/10] drm/asahi: advance a G14 27.2 pool slot's cursor only after the firmware records it On phellos (J413, firmware 27.2) the 300-dispatch compute check stalled at the first pool wrap on most boots: every slot was still linked in the queue's tracking list (+0x94), so no slot could be reused and the 49th command timed out (submitted=48 completed=48 skipped-slots=480). Dumps of the tracking slots at the wrap show why. The firmware records the value a slot's retirement cursor must reach (+0xc, 1 for every use) in its post-processing, which can run after the queue's retired position advances. The service retires a command as soon as the position moves, so it usually read +0xc as 0 and wrote 0 to the cursor. The firmware then never unlinked the slot. In the boots that passed, the read happened to land after the record for one slot; only that slot was ever unlinked, and the pool reused it for the rest of the run (skipped-slots near 47 per command). The polled runtime before the notification rework retired 1 to 20 ms later and usually missed the window, which is why it mostly passed. Retirement now advances the cursor only once +0xc is recorded. A slot retired before that is kept in a pending set, and its cursor is advanced when the service next runs: on the firmware's next notification, submission or scheduler timeout. That is no fixed wait. The stop line counts the deferred cursors. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g14_v27_2.rs | 47 ++++++++++++++++++++++++++---- drivers/gpu/drm/asahi/gpu/v27_2.rs | 11 +++++-- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 91e327b361c81..533ddf48dd86c 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -325,6 +325,11 @@ struct State { busy: u64, /// Free slots passed over because the firmware still held them. skipped: u64, + /// Retired slots whose cursor is not advanced yet: the firmware had not recorded the + /// value to advance it to (`CommandPool::retire`). One bit each. + unacked: u64, + /// Retirements whose cursor had to wait for the firmware's record. + deferred: u64, retired_total: u64, retired_raw: u32, capacity: u32, @@ -419,12 +424,31 @@ impl Runtime { } } + /// Advances the cursors of retired slots that were waiting for the firmware's record. + fn acknowledge(&self, state: &mut State) { + let mut pending = state.unacked; + while pending != 0 { + let slot = pending.trailing_zeros() as usize; + pending &= pending - 1; + match state.pool.retire(slot) { + Ok(false) => {} + Ok(true) => state.unacked &= !(1 << slot), + Err(e) => { + dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); + state.unacked &= !(1 << slot); + } + } + } + } + /// Publishes pending commands while pool slots are free. fn pump(&self, state: &mut State) { + self.acknowledge(state); 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). It normally has by the time the pool comes round to it, but the firmware - // can link a retired slot again and keep it; take the next free slot instead. + // (+0x94), which its retirement scan does after the slot's cursor is advanced. + // Slots retire in order but are unlinked whenever the scan runs; take the next + // free slot that is unlinked. let mut chosen = None; for k in 0..POOL_SLOTS { let slot = (state.next_slot + k) % POOL_SLOTS; @@ -447,6 +471,8 @@ impl Runtime { }; state.next_slot = slot; state.waiting_unlink = false; + // Unlinked already: its cursor needs no further advance. + state.unacked &= !(1 << slot); 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). @@ -550,8 +576,15 @@ impl Runtime { let front = &state.inflight[0]; if state.retired_total >= front.ordinal { if let Ok(done) = state.inflight.remove(0) { - if let Err(e) = state.pool.retire(done.slot) { - dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); + match state.pool.retire(done.slot) { + Ok(true) => {} + // The firmware has not recorded the cursor value yet; `acknowledge` + // retries on its next notification. + Ok(false) => { + state.unacked |= 1 << done.slot; + state.deferred += 1; + } + Err(e) => dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e), } state.busy &= !(1 << done.slot); state.retired += 1; @@ -603,9 +636,9 @@ impl Runtime { kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) }); state.asc.halt(); - dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={}\n", + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={} deferred-cursors={}\n", allowed, running, forced, state.submitted, state.retired, - self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped); + self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped, state.deferred); if running != Ok(0) && forced != Some(Ok(())) { dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); } @@ -692,6 +725,8 @@ impl Backend { late: 0, busy: 0, skipped: 0, + unacked: 0, + deferred: 0, retired_total: 0, retired_raw: head, capacity, diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 1690ff60342be..8db6c0ded49fd 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -331,15 +331,22 @@ impl CommandPool { /// Retirement: advance slot `i`'s cursor to the value the firmware recorded at /// tracking +0xc, so its retirement scan unlinks the slot from the queue's list. - pub(crate) fn retire(&self, i: usize) -> Result { + /// + /// The firmware records +0xc in its post-processing, which can run after the queue's + /// retired position has advanced. Until then +0xc reads 0 (the slot is cleared for each + /// use) and nothing is written: the cursor would stay behind and the firmware would keep + /// the slot linked for good. Returns whether the cursor was advanced; the caller retries a + /// slot that returned `false` on the firmware's next notification. + pub(crate) fn retire(&self, i: usize) -> Result { if i >= POOL_SLOTS { return Err(EINVAL); } crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); crate::pgtable::poc_barrier(); let expected = self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire); + if expected == 0 { return Ok(false); } self.cursors.shared_index(i * 0x40)?.store(expected, Ordering::Release); crate::pgtable::clean_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); crate::pgtable::poc_barrier(); - Ok(()) + Ok(true) } /// Whether the firmware still holds slot `i` in the queue's tracking list (+0x94). From 4c4f313592fa57186dba793752de61c1b41edda0 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 16:40:47 -0500 Subject: [PATCH 04/10] drm/asahi: let the G14 firmware-27.2 GPU through suspend-to-idle With the G14 firmware-27.2 runtime bound, a suspend-to-idle on phellos (J413) left the GPU unusable. At the wake the GFX power domain did not come back ("PS gfx: Failed to reach power state 0xf"), and the next GPU access, a compute dispatch or an unbind, hung a CPU. The driver had no callback for that sleep. Linux gated the domain under the running firmware, as on J713 before apple,sleep-retained. The domain is now kept through the sleep by the device tree (apple,sleep-retained on the J413 firmware-27 GFX domain). Before suspend-to-idle, the runtime holds new publications and lets published commands retire, so the sleep starts with nothing in flight; after the wake it publishes what was held. The firmware keeps running with its keep-powered policy. The ASC, the root and every mapping stay as they are. Its own power-off handshake (idle policy allow-off before the sleep, keep-powered after it) was tried and not kept: the firmware crashed in the wake that followed it. The sleep is refused (EBUSY) if published work does not retire within the stop drain time. A sleep that powers the SoC down is still refused: the firmware would be lost, and this runtime has no cold restart. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/driver.rs | 22 +++++++++++-- drivers/gpu/drm/asahi/g14_v27_2.rs | 52 ++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 1526566cf68a5..ae25ebbd5255b 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -270,12 +270,23 @@ unsafe fn sleep_data<'a>(dev: *mut bindings::device) -> &'a AsahiPlatformDriverD /// Runs before any device suspends, so the GPU goes first and work still in flight can finish. unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_int { + // SAFETY: Called by the PM core. + let data = unsafe { sleep_data(dev) }; + // G14 on firmware 27.2: the firmware keeps running through suspend-to-idle, with nothing in + // flight; a sleep that powers the SoC down would lose it, and it has no cold restart, so that + // is refused. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = data.g14_v27_2.as_ref() { + // SAFETY: Reads a global flag word. + if unsafe { bindings::pm_suspend_via_firmware() } { + return EBUSY.to_errno(); + } + return kernel::error::from_result(|| backend.sleep_prepare().map(|_| 0)); + } // SAFETY: Reads a global flag word. if !unsafe { bindings::pm_suspend_via_firmware() } { return 0; } - // SAFETY: Called by the PM core. - let data = unsafe { sleep_data(dev) }; match data.g17.as_ref() { Some(gpu) => kernel::error::from_result(|| gpu.sleep_prepare().map(|_| 0)), None => EBUSY.to_errno(), @@ -285,7 +296,12 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i /// Runs after every device resumed. Does nothing unless [`sleep_prepare`] stopped the firmware. unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { // SAFETY: Called by the PM core. - if let Some(gpu) = unsafe { sleep_data(dev) }.g17.as_ref() { + let data = unsafe { sleep_data(dev) }; + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = data.g14_v27_2.as_ref() { + backend.sleep_complete(); + } + if let Some(gpu) = data.g17.as_ref() { gpu.sleep_complete(); } } diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 533ddf48dd86c..773693a0cdfcb 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -344,6 +344,9 @@ pub(crate) struct Runtime { dev: ARef, graph: Arc, healthy: AtomicBool, + /// Set between [`Runtime::sleep_prepare`] and [`Runtime::sleep_complete`]: nothing is + /// published across a system sleep. + asleep: AtomicBool, notify: Arc, /// Runs the service; only `Notify::wake` queues on it, and `stop` drains it. queue: OwnedQueue, @@ -444,6 +447,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; } 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. @@ -606,6 +610,51 @@ impl Runtime { self.pump(state); } + /// Before a suspend-to-idle: holds new publications and lets published work retire, so the + /// sleep starts with nothing in flight. The firmware keeps running with its keep-powered + /// policy: its GPU power domain is kept through the sleep (`apple,sleep-retained`), and the + /// ASC, its memory and the root stay as they are. Refuses the sleep (EBUSY) if published work + /// does not retire within the stop drain time. + /// + /// The firmware's own power-off handshake (idle policy allow-off, then keep-powered again + /// after the wake) is not used: on phellos the firmware crashed in the wake that followed it. + pub(crate) fn sleep_prepare(&self) -> Result { + let mut guard = self.state.lock(); + if !self.healthy() || guard.is_none() { return Ok(()); } + // 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(); + loop { + let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; + if !self.healthy() { return Ok(()); } + if state.inflight.is_empty() { + dev_info!(self.dev, "GPU held for sleep: submitted={} completed={} pending={}\n", + state.submitted, state.retired, state.pending.len()); + return Ok(()); + } + if start.elapsed() >= Delta::from_millis(STOP_DRAIN_MS.into()) { + 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)); + } + } + + /// After the sleep: publishes the work held during it. + pub(crate) fn sleep_complete(&self) { + let mut guard = self.state.lock(); + if !self.asleep.swap(false, Ordering::AcqRel) { return; } + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + dev_info!(self.dev, "GPU released after sleep: running={:?} pending={}\n", + state.root.firmware_running(), state.pending.len()); + if self.healthy() { self.pump(state); } + } + /// 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) { @@ -687,6 +736,7 @@ impl Backend { dev: dev.into(), graph: runtime_graph, healthy: AtomicBool::new(true), + asleep: AtomicBool::new(false), notify: runtime_notify, queue, state <- new_mutex!(None, "g14_v27_2::Runtime::state"), @@ -757,6 +807,8 @@ impl Backend { } pub(crate) fn stop(&self) { self.runtime.stop(); } + pub(crate) fn sleep_prepare(&self) -> Result { self.runtime.sleep_prepare() } + pub(crate) fn sleep_complete(&self) { self.runtime.sleep_complete() } } impl Drop for Backend { From 27d1f77bb267eaea865880fe20c9fbda3223d313 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:57:08 +1100 Subject: [PATCH 05/10] drm/asahi: establish G14 compute ownership before firmware publication Stage both ring entries before changing the producers. Store the packet and VM binding in the in-flight list, publish the cursors, then notify the firmware. Keep that ownership if the kick fails or another command in the packet is still in flight. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 48 ++++++++++-------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 79 ++++++++++++++++++++---------- 2 files changed, 82 insertions(+), 45 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 773693a0cdfcb..9e6697eda1d2e 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -395,6 +395,7 @@ impl Runtime { } let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + if !self.healthy() { return Err(EIO); } state.pending.push((packet, 0), GFP_KERNEL)?; self.pump(state); Ok(()) @@ -417,7 +418,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 +450,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. @@ -485,10 +488,13 @@ impl Runtime { packet.finish(Err(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,35 +503,33 @@ 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, + 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) { + if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &packet)) { packet.release_guard(); } packet.finish(Err(e)); @@ -594,6 +598,10 @@ impl Runtime { state.retired += 1; 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; diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 8db6c0ded49fd..e4692492ff8b4 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 From 027f0b26de789e05f4ea094f559afbbdcd0ee7b5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:43 +1100 Subject: [PATCH 06/10] drm/asahi: drain G14 submissions before completing or stopping Close submission admission under the runtime mutex before unbind drains the queue. If staging a later command fails, retain the packet and its VM guard until the already-published prefix retires, then complete the fence with the staging error. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 43 +++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 9e6697eda1d2e..682a23f0c96e2 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -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, @@ -396,6 +413,7 @@ 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(()) @@ -483,9 +501,7 @@ 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 slot = state.next_slot; @@ -506,7 +522,7 @@ impl Runtime { 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, - started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; packet.mark_published(); publication.commit(); Ok(()) @@ -528,11 +544,7 @@ impl Runtime { 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); - if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &packet)) { - packet.release_guard(); - } - packet.finish(Err(e)); + state.fail_publication(&packet, e); } } } @@ -596,7 +608,10 @@ 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)) @@ -666,17 +681,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()); @@ -790,6 +808,7 @@ impl Backend { capacity, inflight: KVec::new(), pending: KVec::new(), + accepting: true, submitted: 0, retired: 0, }); From 6f67df239dd57bc0bf8e24c631c75c4d714ee4bf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:43 +1100 Subject: [PATCH 07/10] drm/asahi: require the firmware handoff SRAM voltage table Read each SRAM operating-point voltage from the loader-provided ADT table. Refuse the handoff if the table is absent or inconsistent with the core operating points. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index e4692492ff8b4..37d09ac8a19be 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -758,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); @@ -911,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) @@ -921,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); } } From 9111ff5b88741778a2f36778cf90eb80d8144034 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 00:43:45 +1100 Subject: [PATCH 08/10] drm/asahi: select G14 by firmware compatibility and signal suspend drain Select the wire layout from the loader compatibility tuple before starting the GPU and pass the register description selected by the GPU compatible. Notify suspend when the in-flight queue empties. Pending commands stay held until resume, and unrelated wakeups exhaust the original timeout budget. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/driver.rs | 40 ++++++++++++++++-------------- drivers/gpu/drm/asahi/g14_v27_2.rs | 31 +++++++++++++---------- 2 files changed, 39 insertions(+), 32 deletions(-) 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 682a23f0c96e2..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())?; @@ -566,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) { @@ -647,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(()); } @@ -656,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, + }; } } From 25ac88ae153c432faafdf64d5096a6f63e501f39 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 04:28:05 -0500 Subject: [PATCH 09/10] drm/asahi: build the G14 firmware-27.2 path without the M3 runtime The G14 firmware-27.2 runtime reuses the 26.x submission front end (m3_submit, agx_uapi and their helpers), so it was built only with CONFIG_DRM_ASAHI_M3_T8122. Give it its own option, DRM_ASAHI_G14_V27_2 (default y), and build the shared front end when either user is enabled: - m3/mod.rs: agx_uapi, agx_compute, agx_attachments, agx_memory and m3_submit build with DRM_ASAHI_M3_T8122 or DRM_ASAHI_G14_V27_2. - m3_submit.rs: the M3 sink, queue constructor, render validation, CDM launch check, timeout handling and fence-timing profile build only with the M3 runtime; without it a render command gets EINVAL. task_comm() moves here from m3_client.rs, which now calls it here. - The G14 path's own code is gated on the new option. Like the M3 runtime, the option depends on DRM_ASAHI_G15: the firmware's UAT is adopted through that backend's handoff helpers (Uat::new_adopted, the G15 UAT table cleaning). Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/Kconfig | 12 +++++ drivers/gpu/drm/asahi/asahi_core.rs | 2 +- drivers/gpu/drm/asahi/driver.rs | 30 +++++------ drivers/gpu/drm/asahi/event.rs | 4 +- drivers/gpu/drm/asahi/gpu.rs | 10 ++-- drivers/gpu/drm/asahi/hw/mod.rs | 4 +- drivers/gpu/drm/asahi/hw/t8112.rs | 6 +-- drivers/gpu/drm/asahi/m3/m3_client.rs | 15 +----- drivers/gpu/drm/asahi/m3/m3_submit.rs | 72 +++++++++++++++++++++------ drivers/gpu/drm/asahi/m3/mod.rs | 15 +++--- drivers/gpu/drm/asahi/mmu.rs | 6 +-- drivers/gpu/drm/asahi/object.rs | 2 +- drivers/gpu/drm/asahi/regs.rs | 2 +- 13 files changed, 110 insertions(+), 70 deletions(-) diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index d383802ee8825..c440219020779 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -95,6 +95,18 @@ config DRM_ASAHI_M3_T8122 boards and firmware do not gain automatic admission. Other GPUs are not affected. +config DRM_ASAHI_G14_V27_2 + bool "Apple M2 (G14G) on GPU firmware 27.2, compute only" + depends on DRM_ASAHI + # The firmware's UAT is adopted through the G15 backend's handoff helpers. + depends on DRM_ASAHI_G15 + default y + help + Start an M2 GPU (G14G) whose boot loader reports GPU firmware + 27.2, and register a compute-only DRM device on it. Clients use + the 26.x submission interface; render commands are refused. + Other GPUs and firmware versions are not affected. + config DRM_ASAHI_G15 bool "Apple M3 Pro/Max (G15) support" depends on DRM_ASAHI diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 5f180203f8369..e0de39368342d 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -27,7 +27,7 @@ mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; mod gpu; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod g14_v27_2; mod hw; mod initdata; diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 95971eaac3031..bf014730a868e 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -54,7 +54,7 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { pub(crate) g16: Option>, m3: Option, /// The G14 firmware-27.2 backend, whose firmware must be stopped on unbind. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: Option>, /// Raw `struct device *` of the platform device. Stored once at probe /// time so the `Drop` impl can find the sysfs file on unregister. @@ -276,7 +276,7 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i // G14 on firmware 27.2: the firmware keeps running through suspend-to-idle, with nothing in // flight; a sleep that powers the SoC down would lose it, and it has no cold restart, so that // is refused. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = data.g14_v27_2.as_ref() { // SAFETY: Reads a global flag word. if unsafe { bindings::pm_suspend_via_firmware() } { @@ -298,7 +298,7 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { // SAFETY: Called by the PM core. let data = unsafe { sleep_data(dev) }; - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = data.g14_v27_2.as_ref() { backend.sleep_complete(); } @@ -357,7 +357,7 @@ impl platform::Driver for AsahiPlatformDriver { if let Some(m3) = this.m3.as_ref() { m3.stop(); } - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = this.g14_v27_2.as_ref() { backend.stop(); } @@ -400,11 +400,11 @@ impl platform::Driver for AsahiPlatformDriver { // 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))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] 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)))] + #[cfg(not(CONFIG_DRM_ASAHI_G14_V27_2))] return Err(ENODEV); } @@ -484,7 +484,7 @@ impl platform::Driver for AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -499,7 +499,7 @@ impl platform::Driver for AsahiPlatformDriver { impl AsahiPlatformDriver { /// G14 with firmware 27.2: start the firmware and register a compute-only DRM device. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] fn probe_g14_v27_2<'bound>( pdev: &'bound platform::Device>, cfg: &'static hw::HwConfig, @@ -561,7 +561,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -605,7 +605,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: Some(backend), - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, raw_dev: core::ptr::null_mut(), raw_stats: core::ptr::null_mut(), @@ -683,7 +683,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: Some(gpu), m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -732,7 +732,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -773,7 +773,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, g16: Some(gpu), raw_dev, @@ -831,7 +831,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -866,7 +866,7 @@ impl Drop for AsahiPlatformDriverData<'_> { if let Some(m3) = self.m3.as_ref() { m3.stop(); } - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = self.g14_v27_2.as_ref() { backend.stop(); } diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index a993bca69f507..dbea26792b6c0 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -54,7 +54,7 @@ pub(crate) type Event = slotalloc::Guard; pub(crate) struct EventValue(u32); impl EventValue { - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn raw(self) -> u32 { self.0 } @@ -205,7 +205,7 @@ impl EventManager { } /// Reserve the normal stamp pair for a kernel queue that polls its own completion. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn try_get_polled(&self) -> Result { self.alloc.try_get(None) } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 2166a7e3dce1e..e9b715aeca980 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -112,9 +112,9 @@ pub(crate) const fn init_message(address: u64) -> u64 { } /// The G14 firmware-27.2 root and the records only it uses. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod v27_2; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use v27_2::*; const RX_WORK_PENDING: u32 = 1 << 0; @@ -140,7 +140,7 @@ const DOORBELL_DEVCTRL: u64 = 0x11; const IOVA_KERN_PRIV_RANGE: Range = 0xffffffa000000000..0xffffffa600000000; /// The G14 firmware-27.2 timestamp aperture, inside the private range: the private allocator /// stays below it in that profile. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const IOVA_G14_V27_2_TIMESTAMP_RANGE: Range = 0xffffffa181400000..0xffffffa185400000; /// Private (cached) GPU-RO firmware structure VA range base. const IOVA_KERN_GPU_RO_RANGE: Range = 0xffffffa600000000..0xffffffa800000000; @@ -200,7 +200,7 @@ pub(crate) enum GraphProfile { Native, /// The G14 firmware-27.2 root (gpu/v27_2.rs) built on these records: no register /// mappings, and the private range ends below that firmware's timestamp aperture. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] G14V27_2, } @@ -712,7 +712,7 @@ impl GpuManager::ver { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; let private_end = match profile { GraphProfile::Native => IOVA_KERN_PRIV_RANGE.end, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] GraphProfile::G14V27_2 => IOVA_G14_V27_2_TIMESTAMP_RANGE.start, }; diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index 2fd17c298d68d..934c52380c43d 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -123,7 +123,7 @@ pub(crate) struct PowerZone { } /// Base of a window in the firmware 27.2 register table. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] #[derive(Debug, Copy, Clone)] pub(crate) enum RegisterBaseV27_2 { /// A fixed physical address. @@ -133,7 +133,7 @@ pub(crate) enum RegisterBaseV27_2 { } /// One record of the firmware 27.2 register table: 60 slots, each naming one window. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] #[derive(Debug, Copy, Clone)] pub(crate) struct RegisterV27_2 { pub(crate) slot: usize, diff --git a/drivers/gpu/drm/asahi/hw/t8112.rs b/drivers/gpu/drm/asahi/hw/t8112.rs index 1879be7f8cead..d22238d90247b 100644 --- a/drivers/gpu/drm/asahi/hw/t8112.rs +++ b/drivers/gpu/drm/asahi/hw/t8112.rs @@ -105,7 +105,7 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_size: None, }; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, install: Option) -> RegisterV27_2 { RegisterV27_2 { slot, base, size, relative, install } } @@ -113,7 +113,7 @@ const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, ins /// The firmware 27.2 register table. Writable windows outside SGX are left unmapped, except /// the push-telemetry window (slot 9), which the firmware shares with the PMP; it is mapped /// apart from the others. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { use RegisterBaseV27_2::{Physical, Sgx}; &[ @@ -136,7 +136,7 @@ pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { }; /// Slots of the 27.2 register table whose stock mode is read-write. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) const WRITABLE_V27_2: u64 = { let mut mask = 0u64; let mut slot = 0; diff --git a/drivers/gpu/drm/asahi/m3/m3_client.rs b/drivers/gpu/drm/asahi/m3/m3_client.rs index c1a07d61120d1..7d9169fe1ecc0 100644 --- a/drivers/gpu/drm/asahi/m3/m3_client.rs +++ b/drivers/gpu/drm/asahi/m3/m3_client.rs @@ -63,7 +63,7 @@ pub(crate) fn admit_vm_for( let refusals = REFUSALS.fetch_add(1, Ordering::Relaxed).saturating_add(1); if refusals <= REFUSALS_LOGGED { let task = kernel::current!(); - let comm = task_comm(task); + let comm = super::m3_submit::task_comm(task); let len = comm.iter().position(|&b| b == 0).unwrap_or(comm.len()); let name = core::str::from_utf8(&comm[..len]).unwrap_or("?"); let last = if refusals == REFUSALS_LOGGED { @@ -87,19 +87,6 @@ pub(crate) fn admit_vm_for( } } -/// The name of `task`, for log lines only. -pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { - let mut name = [0u8; 16]; - // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with - // volatile loads because a concurrent rename may change it; a torn name is only printed. - unsafe { - let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); - for (i, byte) in name.iter_mut().enumerate() { - *byte = comm.add(i).read_volatile(); - } - } - name -} /// Bytes at the start of a compute control stream whose launch records are checked. const LAUNCH_WINDOW: usize = 4096; diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index b8a377264be8f..df0a26e4babc9 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT //! Bounded M3 compute and graphics submissions through the common DRM scheduler/syncobjs. use kernel::{c_str,dma_fence::*,drm::sched,prelude::*,sync::{Arc,Mutex},new_mutex,xarray}; -use crate::{file,m3::agx_uapi,mmu,queue,m3::m3_drm::Shared}; +use crate::{file,m3::agx_uapi,mmu,queue}; +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +use crate::m3::m3_drm::Shared; use crate::alloc::Allocator as _; use core::sync::atomic::{AtomicBool, Ordering}; #[derive(Default)] @@ -59,7 +61,12 @@ pub(crate) struct Packet { } /// The runtime a queue's packets go to: the M3 runtime or the G14 firmware-27.2 compute runtime. #[derive(Clone)] -pub(crate) enum Sink { M3(Shared), G14V27_2(Arc) } +pub(crate) enum Sink { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + M3(Shared), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + G14V27_2(Arc), +} /// The process and thread that submitted a packet, recorded in the submit ioctl. Only logged: /// a renamed task leaves a stale name, which is harmless. #[derive(Copy,Clone)] @@ -68,8 +75,7 @@ impl Owner { fn current()->Self { let task=kernel::current!(); let leader=task.group_leader(); - Self {pid:leader.pid(),process:crate::m3::m3_client::task_comm(leader), - thread:crate::m3::m3_client::task_comm(task)} + Self {pid:leader.pid(),process:task_comm(leader),thread:task_comm(task)} } fn name(comm:&[u8;16])->&str { let len=comm.iter().position(|&b|b==0).unwrap_or(comm.len()); @@ -78,6 +84,19 @@ impl Owner { pub(crate) fn process(&self)->&str {Self::name(&self.process)} pub(crate) fn thread(&self)->&str {Self::name(&self.thread)} } +/// The name of `task`, for log lines only. +pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { + let mut name = [0u8; 16]; + // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with + // volatile loads because a concurrent rename may change it; a torn name is only printed. + unsafe { + let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); + for (i, byte) in name.iter_mut().enumerate() { + *byte = comm.add(i).read_volatile(); + } + } + name +} impl Packet { pub(crate) fn profile_id(&self)->usize {self as *const Self as usize} pub(crate) fn timestamp_addresses(&self,index:usize)->[u64;2] { @@ -113,9 +132,12 @@ impl Packet { // nonzero: GEM closes otherwise accumulate across completed frames. // Signalling an error is not retirement. crate::m3::agx_memory::publish(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let profile=crate::debug::debug_enabled(crate::debug::DebugFlags::M3PassTiming); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let before=if profile {crate::m3::m3_runtime::physical_counter()} else {0}; self.completion.signal(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if profile { let after=crate::m3::m3_runtime::physical_counter(); let status=match result {Ok(())=>0,Err(e)=>e.to_errno()}; @@ -136,7 +158,9 @@ impl sched::JobImpl for Job { // Queue the packet and return its fence; the completion worker publishes and retires // it, so the scheduler can hand over further ready jobs meanwhile. let submitted=match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] Sink::M3(shared)=>crate::m3::m3_runtime::Runtime::submit(shared,job.packet.clone()), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] Sink::G14V27_2(runtime)=>runtime.submit(job.packet.clone()), }; if let Err(e)=submitted { @@ -147,8 +171,10 @@ impl sched::JobImpl for Job { Ok(Some(Fence::from_fence(&job.packet.completion))) } fn timed_out(job:&mut JobTimeout,_finished:bool)->sched::Status { - let shared=match &job.shared { - Sink::M3(shared)=>shared.clone(), + match job.shared.clone() { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>Self::timed_out_m3(shared,job), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] Sink::G14V27_2(runtime)=>{ // The runtime's own command timeout fails a hung GPU; a healthy one is late. // Run its service once, so a hang is found without a notification. @@ -156,9 +182,23 @@ impl sched::JobImpl for Job { if runtime.healthy() {return sched::Status::NoHang;} runtime.withdraw(&job.packet); job.packet.finish(Err(EIO)); - return sched::Status::NoDevice; + sched::Status::NoDevice } - }; + } + } + fn cancel(job:&mut Self) { + match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), + } + job.packet.finish(Err(ECANCELED)); + } +} +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +impl Job { + fn timed_out_m3(shared:Shared,job:&mut JobTimeout)->sched::Status { // Retain the publishing branch's explicit diagnostic override. if !crate::m3::m3_params::timeout_nohang() { if let Some(r)=Option::as_mut(&mut *shared.lock()) {r.health().mark_failed();} @@ -180,13 +220,6 @@ impl sched::JobImpl for Job { job.packet.finish(Err(EIO)); sched::Status::NoDevice } - fn cancel(job:&mut Self) { - match &job.shared { - Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} - Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), - } - job.packet.finish(Err(ECANCELED)); - } } struct AddressSpace<'a>(&'a mmu::Vm); impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { @@ -210,6 +243,7 @@ pub(crate) struct Queue { urgency:u8, } impl Queue { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] pub(crate) fn new(shared:Shared,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, early_tiling:bool, wide_visibility:bool)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; @@ -222,6 +256,7 @@ impl Queue { early_tiling,wide_visibility,urgency,preempt_alloc:None}) } /// A G14 firmware-27.2 compute queue: the same front end, published by that runtime. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn new_g14_v27_2(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, ualloc_priv:Arc>,preempt_bytes:usize)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; @@ -239,8 +274,11 @@ impl queue::Queue for Queue { let vm_job=self.vm.retain_job()?; let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { + // Only the M3 runtime renders; the G14 firmware-27.2 runtime is compute-only. + #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] + if let agx_uapi::ParsedHardwareCommand::Render{..}=command {return Err(EINVAL);} + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { - // The G14 firmware-27.2 runtime is compute-only. if self.preempt_alloc.is_some() {return Err(EINVAL);} if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); @@ -279,6 +317,7 @@ impl queue::Queue for Queue { EINVAL })?; // The launch check decodes the 26.x G15 CDM launch format; G14 streams differ. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if self.preempt_alloc.is_none() { crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; } @@ -325,6 +364,7 @@ fn encode_attachments(vm: &mmu::Vm, list: &agx_uapi::UapiAttachmentList) Ok(out) } +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpace<'_>, early_tiling: bool) -> Result { use agx_uapi::{GpuAddressSpace, GpuAccess}; diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index cb64aa8f1ecbc..eec633d130199 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -70,17 +70,18 @@ pub(crate) fn t8122_admitted(pdev: &platform::Device>) -> Result<&'stat } // The T8122 runtime, ported from the 7.1.12 release-20 kernel (c46d7dcdb871). -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +// The 26.x submission front end, shared with the G14 firmware-27.2 runtime. +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_attachments; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_compute; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_memory; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_resources; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_status; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] pub(crate) mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; @@ -124,7 +125,7 @@ mod m3_resources; mod m3_rtkit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_runtime; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] pub(crate) mod m3_submit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_thermal; @@ -209,7 +210,7 @@ pub(crate) mod m3_mmio_26; mod m3_power_26; pub(crate) mod m3_channel_format; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use m3_channel_format::{idle_cursor, submission_entry, Action, CONTROL_BYTES}; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use m3_init_storage::DEVICE_CONTROL; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 053dccbcc965c..3cca4f5a37fe6 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4521,13 +4521,13 @@ mod execution_context_tests { } /// The word GPU firmware 27.2 on G14 exchanges through the handoff region's magic fields. -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const MAGIC_G14_V27_2: u64 = 0x4b1d000000000003; /// The loader's UAT regions as GPU firmware 27.2 on G14 uses them. The driver mirrors its /// kernel window into the firmware's shared second-level table and names its own trees in /// TTBAT context 0 before the ASC starts. -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) struct FirmwareWindow { handoff: UatRegion, ttbs: UatRegion, @@ -4538,7 +4538,7 @@ pub(crate) struct FirmwareWindow { pa_mask: u64, } -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] impl FirmwareWindow { /// Maps the four regions. Fails with `EBUSY` unless the handoff is idle and the shared /// table and context 0 are empty. diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index e3ce17cb7cb7e..ef7027ff1a636 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -697,7 +697,7 @@ impl> GpuArray { } } -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] impl> GpuArray { /// Aligned index in a shared firmware ring, accessed without borrowing its payload. pub(crate) fn shared_index(&self, offset: usize) -> Result<&core::sync::atomic::AtomicU32> { diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 658c98de1e77a..7e40d4b137ba9 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -351,7 +351,7 @@ impl Resources<'_> { /// The G14 Fender operating-point word: requested index in bits 3:0, request pending in /// bit 4. Sampled while the firmware holds the GPU powered. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn operating_point(&self) -> u32 { self.sgx_read32::<0xd01000>() } From 181fe1878c158e60c3b55a24f246b114d4262f8b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:01:30 +1100 Subject: [PATCH 10/10] drm/asahi: take the G14 27.2 thermal controller values from the chip config RootV27_2::controller() wrote the fast-die target, its offset, the SoC-hot alarm and the per-sensor corrections as literals. They are the values the 13.5 InitData takes from the T8112 chip config, so take them from there: HwDataA unk_8cc, unk_87c and unk_e24 (cfg.da), and the corrections from unk_coef_a/unk_coef_b, indexed from the first fast-die sensor id (7). A sensor without a coefficient refuses the start. The three remaining words (filter stages, unity scale, alarm enable) are controller constants that the 13.5 InitData also sets; they are named here. What the firmware receives is unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 37d09ac8a19be..a8812643dd54d 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -950,14 +950,29 @@ impl RootV27_2 { let at = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; policy.get_mut(at..at + width).ok_or(EINVAL)?.copy_from_slice(&value.to_le_bytes()[..width]); } - // Thermal thresholds and corrections, then the SoC-hot alarm selection. - for (at, value) in [(0x22d4, 11000), (0x2284, 900), (0x2288, 4), - (0x229c, crate::f32!(1.0).to_bits()), (0x2f30, 125), (0x2f34, 1)] { + // Thermal thresholds, then the SoC-hot alarm selection: the chip's values, as the 13.5 + // InitData writes them (HwDataA unk_8cc, unk_87c and unk_e24). + for (at, value) in [(0x22d4, cfg.da.unk_8cc), (0x2284, cfg.da.unk_87c as u32), + (0x2f30, cfg.da.unk_e24)] { put32(policy, at, value); } - for at in [0x2320, 0x2420, 0x2f38, 0x3038] { - for sid in (0..64).filter(|sid| sensors & (1u64 << sid) != 0) { - put32(policy, at + 4 * sid, crate::f32!(5.3).to_bits()); + // Controller constants the 13.5 InitData also sets (unk_880, unk_894 = 1.0, unk_e28). + const FILTER_STAGES: u32 = 4; + const ALARM_ENABLE: u32 = 1; + for (at, value) in [(0x2288, FILTER_STAGES), (0x229c, crate::f32!(1.0).to_bits()), + (0x2f34, ALARM_ENABLE)] { + put32(policy, at, value); + } + // Per-sensor corrections from the chip's coefficient tables (13.5 unk_coef_a/unk_coef_b), + // indexed from the first fast-die sensor id. A sensor without a coefficient refuses. + const FIRST_SENSOR: usize = 7; + let coef_a = cfg.unk_coef_a.first().ok_or(EINVAL)?; + let coef_b = cfg.unk_coef_b.first().ok_or(EINVAL)?; + for (at, coef) in [(0x2320, coef_a), (0x2420, coef_a), (0x2f38, coef_b), (0x3038, coef_b)] { + for sid in (0..64usize).filter(|sid| sensors & (1u64 << sid) != 0) { + let value = sid.checked_sub(FIRST_SENSOR).and_then(|index| coef.get(index)) + .ok_or(EINVAL)?; + put32(policy, at + 4 * sid, value.to_bits()); } } put64(policy, 0x2f28, sensors);