diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index f0fb22fa392e0..e1b0eb9d82628 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -8,6 +8,6 @@ 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 aurora-$(CONFIG_DRM_ASAHI_G18) += g18/sync_input.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/demand.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 c950804a77892..7435d3a3f1df3 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, @@ -150,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, @@ -197,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"), @@ -267,12 +271,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(), @@ -282,7 +297,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(); } } @@ -339,6 +359,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(); } @@ -355,8 +379,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) } @@ -370,6 +395,21 @@ impl platform::Driver for AsahiPlatformDriver { ProbeConfig::M5 => 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. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; @@ -381,11 +421,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. @@ -451,6 +486,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, @@ -463,6 +500,43 @@ 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, + 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, 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 + // 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>, @@ -489,6 +563,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(), @@ -531,6 +607,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, @@ -612,6 +690,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, @@ -659,6 +739,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(), @@ -698,6 +780,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, @@ -754,6 +838,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(), @@ -789,5 +875,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..b77cd15cc9a20 --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -0,0 +1,885 @@ +// 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. +//! +//! 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, AtomicU64, Ordering}; + +use kernel::{ + device, + drm::sched, + new_condvar, new_mutex, new_spinlock, new_work, + platform, + prelude::*, + soc::apple::rtkit, + 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}, +}; + +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; +/// 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); +// 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()) } + } +} + +/// 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 Buffer = crate::g17::CrashLog; + + const COPROC_PLACES_BUFFERS: bool = true; + + fn shmem_map(notify: ArcBorrow<'_, Notify>, iova: usize, size: usize) -> Result { + crate::g17::CrashLog::from_firmware(¬ify.dev, iova, size) + } + + 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!(&*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(notify.dev.as_raw().cast(), log.as_ptr(), log.len()) }; + } + // The service sees the crash and fails outstanding work. + notify.wake(); + } + + /// 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>>; + +/// 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 { + 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, + registers: &'static [hw::RegisterV27_2], + writable: u64, +) -> Result> { + use kernel::dma::{Device as _, DmaMask}; + let dev: &device::Device = pdev.as_ref(); + 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 notify = Notify::new(dev)?; + let mut peer = KBox::pin( + 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)?; + 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 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()))?; + // 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)?; + // 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", step, 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, notify, peer, root, graph, pool, asc, cfg)?; + Ok(Started { backend, drm, binding, resources }) +} + +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. + 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, + /// 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 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, + 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, + 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, + #[pin] + state: Mutex>, + /// Signalled when no work is pending or published, or the runtime fails. + #[pin] + idle: CondVar, + #[pin] + work: Work, +} + +impl_has_work! { + impl HasWork for Runtime { self.work } +} + +impl WorkItem for Runtime { + type Pointer = Arc; + fn run(this: Arc) { + this.service(); + } +} + +#[pinned_drop] +impl PinnedDrop for Runtime { + fn drop(self: Pin<&mut Self>) { + // `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 { + pub(crate) fn healthy(&self) -> bool { self.healthy.load(Ordering::Acquire) } + + /// 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)?; + if !self.healthy() { return Err(EIO); } + if !state.accepting { return Err(ENODEV); } + state.pending.push((packet, 0), GFP_KERNEL)?; + self.pump(state); + 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); + self.idle.notify_all(); + for (packet, _) in state.pending.drain(..) { + 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. + for f in state.inflight.iter() { + if let Some(status) = f.packet.vm.status() { status.record(error); } + f.packet.finish(Err(error)); + } + } + + /// 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); + 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. + // 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; + 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; } + } + } + 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; + // 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). + state.fail_publication(&packet, EINVAL); + continue; + }; + 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 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(slot, &state.queue, stamp.raw(), &job)?; + let publication = state.root.stage_compute(command)?; + state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, + publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + packet.mark_published(); + publication.commit(); + Ok(()) + })(); + match result { + Ok(()) => { + state.last = stamp; + state.sequence += 1; + state.busy |= 1 << slot; + state.published = ordinal; + state.next_slot = (slot + 1) % POOL_SLOTS; + state.submitted += 1; + 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; + } + } + Err(EBUSY) if !state.inflight.is_empty() => return, + Err(e) => { + dev_err!(self.dev, "GPU: compute publication failed {:?}\n", e); + state.fail_publication(&packet, e); + } + } + } + } + + /// 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; }; + self.service_locked(state); + 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) { + 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; + } + 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]; + if state.retired_total >= front.ordinal { + if let Ok(done) = state.inflight.remove(0) { + 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; + if let Some(err) = done.publication_error { + done.packet.release_guard(); + done.packet.finish(Err(err)); + } else if done.last { + done.packet.retired(); + } else if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &done.packet)) + && !state.pending.iter().any(|(packet, _)| Arc::ptr_eq(packet, &done.packet)) + { + done.packet.release_guard(); + } + } + continue; + } + 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; + } + break; + } + if !self.healthy() { return; } + 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 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(()); } + 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 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); + } + remaining = match self.idle.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => jiffies, + _ => 0, + }; + } + } + + /// 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) { + // 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); + } + // 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); + 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={} notifications={} late={} skipped-slots={} deferred-cursors={}\n", + allowed, running, forced, state.submitted, state.retired, + 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"); + } + // 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, + notify: Arc, + 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_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), + asleep: AtomicBool::new(false), + 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); + 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, + late: 0, + busy: 0, + skipped: 0, + unacked: 0, + deferred: 0, + retired_total: 0, + retired_raw: head, + capacity, + inflight: KVec::new(), + pending: KVec::new(), + accepting: true, + submitted: 0, + retired: 0, + }); + // 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)) { + 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(); } + 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 { + 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 c0317461c2f6c..d89a2c5756b22 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 53f127f188b58..4d3867ea5e38b 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 4817bed0c2078..703ef75135803 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] @@ -663,13 +689,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, @@ -812,14 +867,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); @@ -842,20 +899,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 @@ -1606,7 +1650,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..a8812643dd54d --- /dev/null +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -0,0 +1,1060 @@ +// 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. + /// + /// 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(true) + } + + /// 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) + } +} + +/// 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, + 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)?)) + } + + /// 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)?; + 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 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); + 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(); + 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 + /// 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.commands_installed()? { + 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 +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) + } + + /// 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 { + 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 (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); + } + 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). + 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")? + .ok_or(ENODEV)?; + if table.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, 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); + } + // 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); + 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..b8a377264be8f 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,25 @@ 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. + // 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)); + 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 +176,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 +200,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 +218,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 +240,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 +278,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 2c6eef966db72..053dccbcc965c 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4519,3 +4519,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() {