From e5f0dad9346cc2f40e6e42a6d6766cf9eb04ce54 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 1 Nov 2026 21:39:33 +0100 Subject: [PATCH 1/7] soc: apple: rtkit: Take a crash buffer the firmware maps itself The T8142 AOP keeps its crash buffer in its own slot of its DART stream and asks for it on endpoint 1 with that IOVA. A client without shmem_setup refused the request, so the firmware never got its crash buffer acknowledged. APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG takes such a buffer as the firmware's, without a CPU mapping, and acknowledges the request unchanged; a later crash is reported without a log. RtKit::new_with_firmware_crashlog() selects it at runtime, so a driver can use it for one SoC only. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/rtkit.c | 15 +++++++++++++++ include/linux/soc/apple/rtkit.h | 7 +++++++ rust/bindings/bindings_helper.h | 1 + rust/kernel/soc/apple/rtkit.rs | 16 ++++++++++++++++ 4 files changed, 39 insertions(+) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index d352083aaa26c..9eaa28d16c46d 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -410,6 +410,13 @@ static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, dev_dbg(rtk->dev, "RTKit: buffer request for 0x%zx bytes at %pad\n", request.size, &request.iova); + if ((rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG) && + ep == APPLE_RTKIT_EP_CRASHLOG && request.iova) { + *buffer = request; + buffer->is_mapped = true; + return apple_rtkit_send_message(rtk, ep, msg, NULL, false); + } + if (request.iova && !rtk->ops->shmem_setup && !rtk->ops->shmem_setup_ep) { err = -EINVAL; goto error; @@ -734,6 +741,14 @@ static void apple_rtkit_crashlog_rx(struct apple_rtkit *rtk, u64 msg) dev_err(rtk->dev, "RTKit: co-processor has crashed\n"); + /* A firmware-owned crash buffer has no CPU mapping to read the log from. */ + if (!rtk->crashlog_buffer.buffer && !rtk->crashlog_buffer.iomem) { + rtk->crashed = true; + if (rtk->ops->crashed) + rtk->ops->crashed(rtk->cookie, NULL, 0); + return; + } + /* * create a shadow copy here to make sure the co-processor isn't able * to change the log while we're dumping it. this also ensures diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 65bd28a6f0240..4c27e012c2c75 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -57,6 +57,13 @@ struct apple_rtkit_inherited_buffer { /* This client requires endpoint 7 setup before IOP power can be acknowledged. */ #define APPLE_RTKIT_NEEDS_COREANALYTICS BIT(1) +/* + * The co-processor keeps its crash buffer in memory it maps itself (the T8142 + * AOP) and asks for it with that IOVA: take the buffer as the firmware's, + * without a CPU mapping, and acknowledge the request unchanged. + */ +#define APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG BIT(2) + /* * Struct to represent implementation-specific RTKit operations. * diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 56f9f84689804..2731a39a0255c 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -158,6 +158,7 @@ const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL const fop_flags_t RUST_CONST_HELPER_FOP_UNSIGNED_OFFSET = FOP_UNSIGNED_OFFSET; const u32 RUST_CONST_HELPER_APPLE_RTKIT_COPROC_PLACES_BUFFERS = APPLE_RTKIT_COPROC_PLACES_BUFFERS; const u32 RUST_CONST_HELPER_APPLE_RTKIT_NEEDS_COREANALYTICS = APPLE_RTKIT_NEEDS_COREANALYTICS; +const u32 RUST_CONST_HELPER_APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG = APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG; const u64 BINDINGS_SNDRV_PCM_FMTBIT_FLOAT_LE = SNDRV_PCM_FMTBIT_FLOAT_LE; const u64 BINDINGS_SNDRV_PCM_FMTBIT_S32_LE = SNDRV_PCM_FMTBIT_S32_LE; diff --git a/rust/kernel/soc/apple/rtkit.rs b/rust/kernel/soc/apple/rtkit.rs index 73896fea53e00..ef9c9e7f27b0f 100644 --- a/rust/kernel/soc/apple/rtkit.rs +++ b/rust/kernel/soc/apple/rtkit.rs @@ -245,6 +245,11 @@ impl RtKit { ..Self::VTABLE }; + const FIRMWARE_CRASHLOG_VTABLE: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { + flags: Self::VTABLE.flags | bindings::APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG, + ..Self::VTABLE + }; + /// Creates a new RTKit client for a given device and optional mailbox name or index. pub fn new( dev: &device::Device, @@ -268,6 +273,17 @@ impl RtKit { Self::new_with_ops(dev, mbox_name, mbox_idx, data, &Self::COREANALYTICS_VTABLE) } + /// Creates a client whose co-processor keeps its crash buffer in memory it + /// maps itself and asks for it with that IOVA (the T8142 AOP). + pub fn new_with_firmware_crashlog( + dev: &device::Device, + mbox_name: Option<&'static CStr>, + mbox_idx: usize, + data: T::Data, + ) -> Result { + Self::new_with_ops(dev, mbox_name, mbox_idx, data, &Self::FIRMWARE_CRASHLOG_VTABLE) + } + fn new_with_ops( dev: &device::Device, mbox_name: Option<&'static CStr>, From ae7ce6378b2e86c09ee7fb7e1fdd2d67d691d46f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Mon, 2 Nov 2026 07:26:19 +0100 Subject: [PATCH 2/7] drm/asahi: mmu: Map at a fixed address with a guard of any size Vm::map_at() reserves at most one guard page after a mapping. The M5 backend maps the driver's pools at the same address in each client VM with two guard pages after each, as it does when it allocates them. Add Vm::map_at_with_guard_size() and express map_at() through it. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/mmu.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 122b42ccd1b6d..cffb0e2306d4d 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -2551,9 +2551,24 @@ impl Vm { prot: Prot, guard: bool, ) -> Result { - let reserved_size = size - .checked_add(if guard { UAT_PGSZ } else { 0 }) - .ok_or(EOVERFLOW)?; + self.map_at_with_guard_size(addr, size, gem, prot, if guard { UAT_PGSZ } else { 0 }) + } + + /// Map a GEM object into this Vm at a specific address, followed by an unmapped guard of + /// `guard_size` bytes (a multiple of the page size). + #[inline(never)] + pub(crate) fn map_at_with_guard_size( + &self, + addr: u64, + size: usize, + gem: &gem::Object, + prot: Prot, + guard_size: usize, + ) -> Result { + if guard_size & UAT_PGMSK != 0 { + return Err(EINVAL); + } + let reserved_size = size.checked_add(guard_size).ok_or(EOVERFLOW)?; let _residency = self.enter_residency()?; // End the bound-device lease before entering firmware/GPUVM waits. let (_bind_lease, vm_bo) = { From 588d462030a96495269574523f7c6e64afc0e3f4 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Mon, 2 Nov 2026 07:26:20 +0100 Subject: [PATCH 3/7] drm/asahi: mmu: Keep the kernel range of a VM The kernel range of a VM, reserved at VM_CREATE for kernel-managed objects, is only handed to GPUVM. The M5 backend places its per-client objects in that range and checks that userspace commands stay out of it. Keep the range in the Vm and add an accessor. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/mmu.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index cffb0e2306d4d..ae4663134344c 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -1046,6 +1046,9 @@ pub(crate) struct Vm { device_binding: Arc, dev: ARef, id: u64, + /// The range reserved for kernel-managed objects at creation. + #[cfg_attr(not(CONFIG_DRM_ASAHI_M5), allow(dead_code))] + kernel_range: Range, mapping_epoch: Option>, bind_sequence: Arc, lifetime: Option>, @@ -2172,7 +2175,7 @@ impl Vm { &dev, &*dummy_obj.gem, gpuvm_range, - kernel_range, + kernel_range.clone(), VmInner { dev: dev.clone(), is_kernel, @@ -2194,6 +2197,7 @@ impl Vm { device_binding, dev: dev.as_ref().as_ref().into(), id, + kernel_range, gpuvm, mapping_epoch, bind_sequence, @@ -2207,6 +2211,12 @@ impl Vm { }) } + /// The range reserved for kernel-managed objects when this VM was created. + #[cfg_attr(not(CONFIG_DRM_ASAHI_M5), allow(dead_code))] + pub(crate) fn kernel_range(&self) -> Range { + self.kernel_range.clone() + } + /// Attach a status before sharing a newly created user VM with queues. pub(crate) fn with_status(mut self) -> Result { self.status = Some(Arc::pin_init( From 44bfb4a02aa50aa1d4e392096e03e93671582348 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Mon, 2 Nov 2026 07:26:20 +0100 Subject: [PATCH 4/7] drm/asahi: mmu: Add M5 application contexts The M5 (T8142) 25G76 firmware runs application work in a TTBAT context whose lower half is the client VM's root and whose upper half is an empty root of its own; the firmware's upper mappings are not shared with applications. The context is claimed when the work is set up and published explicitly once it is prepared, and a later client takes it over without giving up the context number. Add M5ExecutionContext for that, built only with the M5 backend. It claims numbers from the execution context mask, publishes and retracts under the handoff lock, and a mapping change reaches it through the existing invalidation of every context that names a VM's root. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/mmu.rs | 4 + drivers/gpu/drm/asahi/mmu/m5_context.rs | 173 ++++++++++++++++++++++++ 2 files changed, 177 insertions(+) create mode 100644 drivers/gpu/drm/asahi/mmu/m5_context.rs diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index ae4663134344c..71f1a4b7ba269 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -113,11 +113,15 @@ const DEBUG_CLASS: DebugFlags = DebugFlags::Mmu; mod bind; mod context; mod lifetime; +#[cfg(CONFIG_DRM_ASAHI_M5)] +mod m5_context; mod ppl; mod residency; mod shared; pub(crate) use bind::PreparedUserBindBatch; pub(crate) use lifetime::VmJobGuard; +#[cfg(CONFIG_DRM_ASAHI_M5)] +pub(crate) use m5_context::M5ExecutionContext; pub(crate) use residency::{Gate as ResidencyGate, VmShrinker}; /// PPL magic number for the handoff region diff --git a/drivers/gpu/drm/asahi/mmu/m5_context.rs b/drivers/gpu/drm/asahi/mmu/m5_context.rs new file mode 100644 index 0000000000000..5548d5d0dab6c --- /dev/null +++ b/drivers/gpu/drm/asahi/mmu/m5_context.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! M5 (T8142) application contexts. +//! +//! The 25G76 firmware runs application work in a context whose lower half is the client VM's +//! root and whose upper half is a private, empty root: the firmware's own upper mappings are +//! not shared into application contexts. The context is claimed when a queue is set up and its +//! roots are published explicitly, once the work that names it has been prepared. Mapping +//! changes reach a published context through [`VmInner::tlbi_contexts_naming_root`]. + +use super::*; + +/// A claimed M5 application context and the VMs it names. +pub(crate) struct M5ExecutionContext { + inner: Arc, + id: u8, + low: Vm, + high: Vm, + published: bool, +} + +impl Uat { + /// Claims an application context for `vm`, a client VM of this UAT. Nothing is published. + pub(crate) fn new_m5_execution_context(&self, vm: &Vm) -> Result { + self.check_client_vm(vm)?; + let id = { + let mut inner = self.inner.lock(); + let free = !inner.execution_contexts & EXECUTION_CONTEXT_MASK; + if free == 0 { + return Err(ENOSPC); + } + let id = free.trailing_zeros() as usize; + inner.execution_contexts |= 1u64 << id; + id + }; + let high = match self.new_vm(0x8142_1000 + id as u64, self.geometry.user_range()) { + Ok(high) => high, + Err(error) => { + self.inner.lock().execution_contexts &= !(1u64 << id); + return Err(error); + } + }; + Ok(M5ExecutionContext { + inner: self.inner.clone(), + id: id as u8, + low: vm.clone(), + high, + published: false, + }) + } + + fn check_client_vm(&self, vm: &Vm) -> Result { + let owner = vm.gpuvm.lock_inner(); + if owner.is_kernel || !core::ptr::eq(Arc::as_ptr(&owner.uat_inner), Arc::as_ptr(&self.inner)) + { + return Err(EINVAL); + } + Ok(()) + } +} + +impl M5ExecutionContext { + /// The client VM named as the lower half. + pub(crate) fn vm(&self) -> &Vm { + &self.low + } + + /// The hardware context number, as the firmware records name it. + pub(crate) fn context_id(&self) -> u8 { + self.id + } + + /// The TTBAT words of this context. + pub(crate) fn roots(&self) -> [u64; 2] { + let id = usize::from(self.id); + [tagged_root(self.low.ttb(), id), tagged_root(self.high.ttb(), id)] + } + + /// Publishes the roots. A slot that is not empty is never replaced. + pub(crate) fn publish(&mut self) -> Result { + if self.published { + return Err(EBUSY); + } + let [low, high] = self.roots(); + let id = usize::from(self.id); + { + let inner = self.inner.lock(); + inner.handoff_lock(); + let slot = &inner.ttbs()[id]; + let empty = + slot.ttb0.load(Ordering::Acquire) == 0 && slot.ttb1.load(Ordering::Acquire) == 0; + if empty { + slot.ttb0.store(low, Ordering::Release); + slot.ttb1.store(high, Ordering::Release); + inner.publish_slot(id); + } + inner.handoff_unlock(); + if !empty { + return Err(EBUSY); + } + } + self.published = true; + mem::sync(); + mem::tlbi_asid(self.id); + mem::sync(); + Ok(()) + } + + /// Whether this context's roots are published and still in place. + pub(crate) fn is_current(&self) -> bool { + if !self.published { + return false; + } + let [low, high] = self.roots(); + let inner = self.inner.lock(); + let slot = &inner.ttbs()[usize::from(self.id)]; + slot.ttb0.load(Ordering::Acquire) == low && slot.ttb1.load(Ordering::Acquire) == high + } + + /// Names another client VM of the same UAT, keeping the context number. Published roots + /// are retracted first; the caller has made sure no work of the previous VM is outstanding. + pub(crate) fn rebind(&mut self, vm: &Vm) -> Result { + { + let owner = vm.gpuvm.lock_inner(); + if owner.is_kernel + || !core::ptr::eq(Arc::as_ptr(&owner.uat_inner), Arc::as_ptr(&self.inner)) + { + return Err(EINVAL); + } + } + self.retract(); + self.low = vm.clone(); + Ok(()) + } + + fn retract(&mut self) { + if !self.published { + return; + } + let [low, high] = self.roots(); + let id = usize::from(self.id); + { + let inner = self.inner.lock(); + inner.handoff_lock(); + let slot = &inner.ttbs()[id]; + // Only our own pair is retracted. + if slot.ttb0.load(Ordering::Acquire) == low && slot.ttb1.load(Ordering::Acquire) == high + { + slot.ttb0.store(0, Ordering::Release); + slot.ttb1.store(0, Ordering::Release); + inner.publish_slot(id); + } + inner.handoff_unlock(); + } + mem::sync(); + mem::tlbi_asid(self.id); + mem::sync(); + self.published = false; + } +} + +impl Drop for M5ExecutionContext { + fn drop(&mut self) { + self.retract(); + let id = usize::from(self.id); + let mut inner = self.inner.lock(); + let slot = &inner.ttbs()[id]; + // A slot someone else filled is not ours to hand out again: keep it claimed. + if slot.ttb0.load(Ordering::Acquire) == 0 && slot.ttb1.load(Ordering::Acquire) == 0 { + inner.execution_contexts &= !(1u64 << id); + } + } +} From 3488398d99576bcb01e062f89daa0803d15b2869 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Mon, 2 Nov 2026 07:26:25 +0100 Subject: [PATCH 5/7] drm/asahi: regs: Add the M5 PMGR boot control The native 25G76 driver sets the low bit of the GPU's PMGR boot control word (SGX + 0xe90000) before either M5 firmware instance starts; the word reads 0x30000 on J813. Add the write, for the M5 backend only, refusing any other starting value. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/regs.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 2b04726e43878..7ed0d552a4879 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -770,6 +770,26 @@ impl G17Resources { self.sgx_read32::() } + /// M5: set the low bit of the PMGR boot control word at SGX+0xe90000, as the native + /// 25G76 driver does before either firmware role starts. The word reads 0x30000 (or + /// 0x30001 when already set) on J813; anything else is refused. + #[cfg(CONFIG_DRM_ASAHI_M5)] + pub(crate) fn m5_match_pmgr_boot_control(&self) -> Result { + const OFFSET: usize = 0xe90000; + let sgx = self.sgx.try_access().ok_or(ENODEV)?; + let sgx = (&*sgx).as_view(); + let before = sgx.try_read32(OFFSET)?; + if before != 0x30000 && before != 0x30001 { + dev_err!(self.dev.as_ref(), "M5: unexpected PMGR boot control {:#x}\n", before); + return Err(EIO); + } + sgx.try_write32(before | 1, OFFSET)?; + if sgx.try_read32(OFFSET)? != 0x30001 { + return Err(EIO); + } + Ok(()) + } + /// Enable dynamic power gating of idle G17 GPU cores. The firmware expects this before it is /// initialized. pub(crate) fn enable_g17_gating(&self) -> Result { From db779e90187743eba7344a2d963e784617ab4ac1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Mon, 2 Nov 2026 07:27:08 +0100 Subject: [PATCH 6/7] drm/asahi: Add the M5 (T8142) backend Add a backend for the M5 GPU (J813, G17G) running the 25G76 firmware (RTKit-3255.160.4), as ProbeConfig::M5 for apple,agx-t8142 behind CONFIG_DRM_ASAHI_M5. It changes nothing for the other SoCs. The 25G76 firmware has two coprocessors, GFX and GFX1, as the A18 Pro has, but a HAL300 interface that differs from the 26A428 and 25G83 builds the shared G17 code runs. The backend therefore builds its own initialization graph and talks to the firmware over its own queues, while using the shared parts of the driver: - the UAT is the shared one with published roots, adopted and mirrored as on the A18 Pro, plus the M5 application contexts; - user VMs carry a status and a job lifetime, and the backend uses the tracked submission model of file.rs; - the UAPI is the shared one. The backend reports VM_STATUS and SOFT_FAULTS and one hardware command per submission. The boot loader (aura) loads the firmware, checks both TEXT images against the 25G76 build and says so in /chosen/aurora,m5-gpu-firmware-profile; the backend refuses to start without it. One render pair and one compute queue serve all clients and are handed from client VM to client VM; a submission is polled to retirement before the ioctl returns. Renders and compute are admitted only within the state the firmware programs are known to handle, and refused with ENOTSUPP otherwise. There is no recovery yet: a job that fails stops both coprocessors and retains every firmware-visible object until reboot. The driver's pools are mapped at their own address in each client VM the job is handed to, except in the VM that owns them, and the compute storage is reserved together with the parameter buffer, so that its address is free in every such VM. Tested on J813 (M5, 8 GPU cores) on the aura one-shot trial boot, with Mesa j813, against the same Mesa on the J813 kernel this code comes from: GLES2 16016 pass, 930 fail (identical per case); GLES3 40832 pass, 3547 fail, 2 timeouts (identical but for one known flake); GLES31 32813 pass, 4517 fail (t70: 32804/4520; the 32 differing cases are 9 fail->pass and flakes); the sway desktop renders on the GPU from boot, also during the CTS runs. This consolidates the M5 work of Acelogic and the G17P render, UAPI and initdata encoders of DjDeveloperr , with contributions by Ryan Murray, Eryk Wieliczko and Chris Kearney, from the J813 kernel tree, ported onto integration's driver. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/Kconfig | 8 + drivers/gpu/drm/asahi/asahi_core.rs | 6 + drivers/gpu/drm/asahi/driver.rs | 41 + drivers/gpu/drm/asahi/m5/channel.rs | 183 ++ drivers/gpu/drm/asahi/m5/command.rs | 1233 +++++++++++++ drivers/gpu/drm/asahi/m5/completion.rs | 61 + drivers/gpu/drm/asahi/m5/compute.rs | 246 +++ drivers/gpu/drm/asahi/m5/drm.rs | 386 ++++ drivers/gpu/drm/asahi/m5/fw_msg.rs | 57 + drivers/gpu/drm/asahi/m5/initdata.rs | 1630 +++++++++++++++++ drivers/gpu/drm/asahi/m5/live_boot.rs | 527 ++++++ drivers/gpu/drm/asahi/m5/mapped.rs | 145 ++ drivers/gpu/drm/asahi/m5/mod.rs | 91 + drivers/gpu/drm/asahi/m5/provider.rs | 199 ++ drivers/gpu/drm/asahi/m5/render.rs | 508 +++++ drivers/gpu/drm/asahi/m5/render_desc.rs | 1138 ++++++++++++ drivers/gpu/drm/asahi/m5/render_target.rs | 72 + drivers/gpu/drm/asahi/m5/resources.rs | 631 +++++++ .../asahi/m5/resources/application_compute.rs | 305 +++ .../drm/asahi/m5/resources/firmware_view.rs | 75 + .../drm/asahi/m5/resources/graphics_job.rs | 512 ++++++ .../drm/asahi/m5/resources/graphics_memory.rs | 198 ++ .../drm/asahi/m5/resources/graphics_queues.rs | 261 +++ .../drm/asahi/m5/resources/graphics_usc.rs | 203 ++ .../asahi/m5/resources/parameter_buffer.rs | 139 ++ .../drm/asahi/m5/resources/target_memory.rs | 75 + drivers/gpu/drm/asahi/m5/sksm.rs | 271 +++ drivers/gpu/drm/asahi/m5/submission.rs | 51 + drivers/gpu/drm/asahi/m5/vm_layout.rs | 38 + include/uapi/drm/asahi_drm.h | 5 +- 30 files changed, 9293 insertions(+), 2 deletions(-) create mode 100644 drivers/gpu/drm/asahi/m5/channel.rs create mode 100644 drivers/gpu/drm/asahi/m5/command.rs create mode 100644 drivers/gpu/drm/asahi/m5/completion.rs create mode 100644 drivers/gpu/drm/asahi/m5/compute.rs create mode 100644 drivers/gpu/drm/asahi/m5/drm.rs create mode 100644 drivers/gpu/drm/asahi/m5/fw_msg.rs create mode 100644 drivers/gpu/drm/asahi/m5/initdata.rs create mode 100644 drivers/gpu/drm/asahi/m5/live_boot.rs create mode 100644 drivers/gpu/drm/asahi/m5/mapped.rs create mode 100644 drivers/gpu/drm/asahi/m5/mod.rs create mode 100644 drivers/gpu/drm/asahi/m5/provider.rs create mode 100644 drivers/gpu/drm/asahi/m5/render.rs create mode 100644 drivers/gpu/drm/asahi/m5/render_desc.rs create mode 100644 drivers/gpu/drm/asahi/m5/render_target.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/application_compute.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/firmware_view.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/graphics_job.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/graphics_memory.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/graphics_queues.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs create mode 100644 drivers/gpu/drm/asahi/m5/resources/target_memory.rs create mode 100644 drivers/gpu/drm/asahi/m5/sksm.rs create mode 100644 drivers/gpu/drm/asahi/m5/submission.rs create mode 100644 drivers/gpu/drm/asahi/m5/vm_layout.rs diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index 6b28266b6b4d1..af5e7e9e8cb87 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -43,6 +43,14 @@ config DRM_ASAHI_G16 An aborted receipt disables that command class until reboot. Suspend, hibernation and kexec are blocked while native graphics owns DMA. +config DRM_ASAHI_M5 + bool "Apple M5 (G17G, T8142) support (experimental)" + depends on DRM_ASAHI && ARM64 + help + Backend for the M5 GPU (J813 MacBook Air) running the 25G76 + firmware (RTKit-3255.160.4), as loaded and published by the aura + boot loader (/chosen/aurora,m5-gpu-firmware-profile). + config DRM_ASAHI_DEBUG_ALLOCATOR bool "Use debug allocator" depends on DRM_ASAHI diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index decf16ea09647..17b64ec578d5f 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -22,6 +22,8 @@ mod gem; #[cfg(CONFIG_DRM_ASAHI_G16)] mod g16; +#[cfg(CONFIG_DRM_ASAHI_M5)] +mod m5; mod gpu; mod hw; mod initdata; @@ -198,6 +200,10 @@ module! { default: 1, description: "Count held GPU memory in its creator's RSS for the OOM killer (1 = on)", }, + m5_fw_trace: u32 { + default: 0, + description: "M5: firmware trace classes (power bit 0, submission bit 1, recovery classifier bit 9)", + }, g16_deadline_ms: u32 { default: 5000, description: "G16: administrative completion-stamp deadline, ms (0 disables; long running work can exceed it)", diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index ff82d8c118e85..554a82285c865 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -142,6 +142,8 @@ pub(crate) enum ProbeConfig { Legacy(&'static hw::HwConfig), G17(&'static g17::Config), M3(crate::m3::Chip), + /// The M5 (T8142) backend, refused unless it is built. + M5, } // OF Device ID table. Linux 7.3's of_device_table!() takes no attributes on @@ -165,6 +167,10 @@ macro_rules! asahi_of_device_table { of::DeviceId::new(c"apple,agx-t6041"), ProbeConfig::G17(&hw::t6041::CONFIG) ), + ( + of::DeviceId::new(c"apple,agx-t8142"), + ProbeConfig::M5 + ), ( of::DeviceId::new(c"apple,agx-t8103"), ProbeConfig::Legacy(&hw::t8103::HWCONFIG) @@ -253,6 +259,10 @@ impl platform::Driver for AsahiPlatformDriver { ProbeConfig::Legacy(cfg) => *cfg, ProbeConfig::G17(cfg) => return AsahiPlatformDriver::probe_g17(pdev, cfg), ProbeConfig::M3(chip) => return Err(crate::m3::refuse_probe(pdev, *chip)), + #[cfg(CONFIG_DRM_ASAHI_M5)] + ProbeConfig::M5 => return AsahiPlatformDriver::probe_m5(pdev), + #[cfg(not(CONFIG_DRM_ASAHI_M5))] + ProbeConfig::M5 => return Err(ENODEV), }; // SAFETY: The selected SoC's UAT output width bounds all device DMA. @@ -444,6 +454,37 @@ impl AsahiPlatformDriver { } } +#[cfg(CONFIG_DRM_ASAHI_M5)] +impl AsahiPlatformDriver { + fn probe_m5<'bound>( + pdev: &'bound platform::Device>, + ) -> Result> { + // SAFETY: The M5 UAT has 42 output bits. + unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(42)?)? }; + let resources = regs::Resources::new(pdev)?; + let res = regs::G17Resources::new(pdev)?; + let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; + let gpu = crate::m5::probe(pdev, &drm, res)?; + let data = try_pin_init!(AsahiDrmRegistrationData { + gpu: gpu as Arc, + resources, + }); + // SAFETY: The registration is stored and unregistered by platform data destruction. + // The M5 firmware session retains its firmware-visible state until reboot. + let reg = unsafe { drm::Registration::new(pdev.as_ref(), drm, data, 0)? }; + Ok(AsahiPlatformDriverData { + _device: reg.device().into(), + _reg: reg, + g17: None, + #[cfg(CONFIG_DRM_ASAHI_G16)] + g16: None, + raw_dev: core::ptr::null_mut(), + raw_stats: core::ptr::null_mut(), + stats: None, + }) + } +} + #[cfg(CONFIG_DRM_ASAHI_G16)] impl AsahiPlatformDriver { pub(crate) fn probe_g16<'bound>( diff --git a/drivers/gpu/drm/asahi/m5/channel.rs b/drivers/gpu/drm/asahi/m5/channel.rs new file mode 100644 index 0000000000000..259d79209a0f7 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/channel.rs @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +#![cfg_attr(not(test), allow(dead_code))] + +//! T8142/25G76 channel configuration, separate from Neo's HAL200 path. +//! +//! Native AGXCLChannelSKSM::submitBuffer inlines this packed 0x86-byte +//! record at 0xfffffe000898488c..0x8984bd8. The controlled native sequence +//! is a selector-3 register program, this tag-15 record, then a tag-14 kick. +//! These builders do not map memory, install a queue or publish a producer. +//! Every pointer and event identifier must belong to the retained session. + +pub(crate) const M5_CHANNEL_CONFIG_BYTES: usize = 0x86; + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum M5ChannelError { + QueueId, + Priority, + Address, + Context, + DataMaster, +} + +/// Optional TA parameter-buffer event, separate from the first event tuple. +/// The native TA writer at 25G76 0x8a249ac..0x8a249e4 obtains these values +/// from its retained PM manager and command descriptor. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5ParameterBufferEvent { + pub(crate) address: u64, + pub(crate) timestamp: u64, + /// TA descriptor +0x1218, independently selected by the owned PB table. + pub(crate) hardware_buffer_id: u32, + /// Native PM manager +0x79c. This is not the SKSM queue ID. + pub(crate) manager_id: u32, +} + +/// Optional retained event-machine object, with the native timestamp and +/// index. None emits the native disabled branch's full-width sentinels. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5ChannelEvent { + pub(crate) address: u64, + pub(crate) timestamp: u64, + pub(crate) index: u32, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5ChannelConfig { + pub(crate) ring_low: u64, + pub(crate) ring_high: u64, + pub(crate) queue_id: u8, + pub(crate) priority: u8, + /// Native descriptor +0x181 bit 0. Mode 3 validates the first queue + /// installation on M5; an already-installed native capture has 0. + pub(crate) install_queue: bool, + /// Native descriptor +0x144, independently matched to the UAT context. + pub(crate) gpu_context: u8, + pub(crate) event: Option, + /// AGXCommandQueue +0x8b8: retained scheduler/control object. + pub(crate) channel_control: u64, + /// Native descriptor +0x2dc bit 0. + pub(crate) update_scheduler: bool, + /// AGXCommandQueue +0x898 object's +0x10. Not the GPU context ID. + pub(crate) scheduler_index: u32, + /// getStampIndex on descriptor +0x170. Not a fixed target constant. + pub(crate) channel_stamp_index: u32, + /// Native descriptor +0x180 bit 0. + pub(crate) update_context: bool, + /// Descriptor +0x58 owner's virtual context value. Distinct from UAT. + pub(crate) owner_context: u32, + /// Native channel-state +0x84 is nonzero. + pub(crate) extended_command: bool, +} + +fn firmware_address(address: u64) -> bool { + address >= 0xffff_fc00_0000_0000 && address & 7 == 0 +} + +fn put32(bytes: &mut [u8], offset: usize, value: u32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn put64(bytes: &mut [u8], offset: usize, value: u64) { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +pub(crate) fn encode_m5_channel_config( + p: M5ChannelConfig, +) -> Result<[u8; M5_CHANNEL_CONFIG_BYTES], M5ChannelError> { + encode_m5_channel_config_for(p, 2, 2, None, None) +} + +/// The two selectors are independent: native TA/fragment use 0/1 at +0x22 +/// while both retain 2 at +0x5e. Changing both by stage breaks that contract. +/// gpu_state_update retains the separate +0x26 flag/+0x2a value pair; +/// the native TA writer copies descriptor +0xe41/+0xe48 to these fields. +pub(crate) fn encode_m5_channel_config_for( + p: M5ChannelConfig, + data_master: u32, + channel_data_master: u32, + gpu_state_update: Option, + parameter_buffer: Option, +) -> Result<[u8; M5_CHANNEL_CONFIG_BYTES], M5ChannelError> { + if data_master > 2 + || channel_data_master > 2 + || (parameter_buffer.is_some() && data_master != 0) + { + return Err(M5ChannelError::DataMaster); + } + if p.queue_id > 127 { + return Err(M5ChannelError::QueueId); + } + if p.priority > 3 { + return Err(M5ChannelError::Priority); + } + if p.gpu_context == 0 { + return Err(M5ChannelError::Context); + } + if p.ring_low == 0 + || p.ring_low >= (1 << 42) + || p.ring_low & 0x3fff != 0 + || !firmware_address(p.ring_high) + || p.ring_high & 0x3fff != 0 + || !firmware_address(p.channel_control) + { + return Err(M5ChannelError::Address); + } + if let Some(event) = p.event { + if !firmware_address(event.address) { + return Err(M5ChannelError::Address); + } + } + if let Some(event) = parameter_buffer { + if !firmware_address(event.address) { + return Err(M5ChannelError::Address); + } + } + let mut bytes = [0; M5_CHANNEL_CONFIG_BYTES]; + put32(&mut bytes, 0, 15); + put64(&mut bytes, 8, p.ring_low); + put64(&mut bytes, 0x10, p.ring_high); + bytes[0x18..0x1a].copy_from_slice(&u16::from(p.queue_id).to_le_bytes()); + for (offset, value) in [ + (0x1a, u32::from(p.install_queue)), + (0x1e, u32::from(p.priority)), + (0x22, data_master), + (0x32, u32::from(p.gpu_context)), + (0x52, u32::from(p.update_scheduler)), + (0x56, p.scheduler_index), + (0x5a, p.channel_stamp_index), + (0x5e, channel_data_master), + (0x62, u32::from(p.update_context)), + (0x66, p.owner_context), + (0x6a, u32::from(p.extended_command)), + ] { + put32(&mut bytes, offset, value); + } + if let Some(value) = gpu_state_update { + put32(&mut bytes, 0x26, 1); + put64(&mut bytes, 0x2a, value); + } + match p.event { + Some(event) => { + put64(&mut bytes, 0x36, event.address); + put64(&mut bytes, 0x3e, event.timestamp); + put32(&mut bytes, 0x46, event.index); + } + None => { + put64(&mut bytes, 0x3e, u64::MAX); + put32(&mut bytes, 0x46, u32::MAX); + } + } + put64(&mut bytes, 0x4a, p.channel_control); + if let Some(event) = parameter_buffer { + put64(&mut bytes, 0x6e, event.address); + put64(&mut bytes, 0x76, event.timestamp); + put32(&mut bytes, 0x7e, event.hardware_buffer_id); + put32(&mut bytes, 0x82, event.manager_id); + } else { + bytes[0x76..0x86].fill(0xff); + } + Ok(bytes) +} + diff --git a/drivers/gpu/drm/asahi/m5/command.rs b/drivers/gpu/drm/asahi/m5/command.rs new file mode 100644 index 0000000000000..c4555602c781e --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/command.rs @@ -0,0 +1,1233 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +use crate::m5::{render_desc, submission}; + +use render_desc::{ + G17pRenderParameters, RenderBuildError, +}; + +pub(crate) const UAPI_COMMAND_HEADER_SIZE: usize = 8; + +pub(crate) const UAPI_RENDER_SIZE: usize = 272; + +pub(crate) const UAPI_COMPUTE_SIZE: usize = 88; + +pub(crate) const UAPI_G18_COMPUTE_SIZE: usize = 136; + +pub(crate) const COMPUTE_G18_RESOURCES: u32 = 1 << 2; + +/// `drm_asahi_cmd_render_g18`: the render payload plus its 80-byte suffix. +pub(crate) const UAPI_G18_RENDER_SIZE: usize = UAPI_RENDER_SIZE + 80; + +/// `DRM_ASAHI_RENDER_G18_RESOURCES`. Only the G18 adapter may consume and +/// strip it; the shared translator's RENDER_FLAGS keeps refusing it. +pub(crate) const RENDER_G18_RESOURCES: u32 = 1 << 21; + +pub(crate) const UAPI_ATTACHMENT_SIZE: usize = 24; + +pub(crate) const UAPI_MAX_ATTACHMENTS: usize = 16; + +pub(crate) const UAPI_MAX_HARDWARE_COMMANDS: u32 = 64; + +pub(crate) const M5_MAX_RENDER_DIMENSION: u32 = 16384; + +pub(crate) const UAPI_BARRIER_NONE: u16 = 0xffff; + +pub(crate) const USC_WINDOW_SIZE: u64 = 1 << 32; + +pub(crate) const COMPUTE_G17P_ADD3_PROOF: u32 = + kernel::uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_G17P_ADD3_PROOF as u32; + +const G17P_ADD3_BUFFER_BYTES: u64 = 64 * 4; + +const COMMAND_RENDER: u16 = 0; + +const COMMAND_COMPUTE: u16 = 1; + +const SET_VERTEX_ATTACHMENTS: u16 = 2; + +const SET_FRAGMENT_ATTACHMENTS: u16 = 3; + +const SET_COMPUTE_ATTACHMENTS: u16 = 4; + +const RENDER_VERTEX_SCRATCH: u32 = 1 << 0; + +const RENDER_PROCESS_EMPTY_TILES: u32 = 1 << 1; + +const RENDER_NO_VERTEX_CLUSTERING: u32 = 1 << 2; + +const RENDER_RSRC_SPEC_HI: u32 = 1 << 4; + +const RENDER_DBIAS_IS_INT: u32 = 1 << 18; + +const RENDER_FLAGS: u32 = RENDER_VERTEX_SCRATCH + | RENDER_PROCESS_EMPTY_TILES + | RENDER_NO_VERTEX_CLUSTERING + | RENDER_RSRC_SPEC_HI + | RENDER_DBIAS_IS_INT + // Private, opt-in matched-workload diagnostic. Ordinary builds reject it. + | if cfg!(g17p_aux_fb_small_probe) { 1 << 31 } else { 0 } + | if cfg!(g17p_mcache_aperture_probe) { 1 << 30 } else { 0 }; + +const SAMPLER_SIZE: u64 = 8; + +const MAX_SAMPLERS: u32 = 1024; + +const PAGE_SIZE: u64 = 0x4000; + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum UapiTranslateError { + HeaderTruncated, + PayloadTruncated, + PayloadTail, + CommandType, + AttachmentPayloadSize, + AttachmentCount, + AttachmentFields, + AttachmentBarrier, + HardwareCommandCount, + BarrierFuture, + QueueUscAlignment, + QueueUscRange, + AddressRange, + AddressAlignment, + FlagsUnknownBits, + FlagsUnsupported, + Dimensions, + Layers, + UtileDimensions, + Samples, + TilebufferSize, + SamplerCount, + SamplerPair, + HelperProgram, + Add3ProofAttachments, + ProgramOffset, + ZlsFields, + RenderBuild(RenderBuildError), +} + +impl From for UapiTranslateError { + fn from(value: RenderBuildError) -> Self { + Self::RenderBuild(value) + } +} + +impl UapiTranslateError { +} + +fn get_u16(raw: &[u8], offset: usize) -> u16 { + u16::from_le_bytes(raw[offset..offset + 2].try_into().unwrap()) +} + +fn get_u32(raw: &[u8], offset: usize) -> u32 { + u32::from_le_bytes(raw[offset..offset + 4].try_into().unwrap()) +} + +fn get_u64(raw: &[u8], offset: usize) -> u64 { + u64::from_le_bytes(raw[offset..offset + 8].try_into().unwrap()) +} + +fn padded_payload(raw: &[u8]) -> Result<[u8; N], UapiTranslateError> { + if raw.len() > N && raw[N..].iter().any(|byte| *byte != 0) { + return Err(UapiTranslateError::PayloadTail); + } + let mut out = [0u8; N]; + let count = core::cmp::min(raw.len(), N); + out[..count].copy_from_slice(&raw[..count]); + Ok(out) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiCommandHeader { + pub(crate) command_type: u16, + pub(crate) size: u16, + pub(crate) render_barrier: u16, + pub(crate) compute_barrier: u16, +} + +impl UapiCommandHeader { + fn parse(raw: &[u8]) -> Result { + if raw.len() < UAPI_COMMAND_HEADER_SIZE { + return Err(UapiTranslateError::HeaderTruncated); + } + Ok(Self { + command_type: get_u16(raw, 0), + size: get_u16(raw, 2), + render_barrier: get_u16(raw, 4), + compute_barrier: get_u16(raw, 6), + }) + } +} + +#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)] +pub(crate) struct UapiAttachment { + pub(crate) address: u64, + pub(crate) size: u64, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiAttachmentList { + pub(crate) entries: [UapiAttachment; UAPI_MAX_ATTACHMENTS], + pub(crate) count: u8, +} + +impl UapiAttachmentList { + pub(crate) const EMPTY: Self = Self { + entries: [UapiAttachment { + address: 0, + size: 0, + }; UAPI_MAX_ATTACHMENTS], + count: 0, + }; + + pub(crate) fn as_slice(&self) -> &[UapiAttachment] { + &self.entries[..self.count as usize] + } + + fn parse(raw: &[u8]) -> Result { + if raw.len() % UAPI_ATTACHMENT_SIZE != 0 { + return Err(UapiTranslateError::AttachmentPayloadSize); + } + let count = raw.len() / UAPI_ATTACHMENT_SIZE; + if count > UAPI_MAX_ATTACHMENTS { + return Err(UapiTranslateError::AttachmentCount); + } + let mut out = Self::EMPTY; + for index in 0..count { + let offset = index * UAPI_ATTACHMENT_SIZE; + if get_u32(raw, offset + 0x10) != 0 || get_u32(raw, offset + 0x14) != 0 { + return Err(UapiTranslateError::AttachmentFields); + } + out.entries[index] = UapiAttachment { + address: get_u64(raw, offset), + size: get_u64(raw, offset + 8), + }; + } + out.count = count as u8; + Ok(out) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiHelperProgram { + pub(crate) binary: u32, + pub(crate) config: u32, + pub(crate) data: u64, +} + +fn helper(raw: &[u8], offset: usize) -> UapiHelperProgram { + UapiHelperProgram { + binary: get_u32(raw, offset), + config: get_u32(raw, offset + 4), + data: get_u64(raw, offset + 8), + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiProgram { + pub(crate) usc: u32, + pub(crate) resource_spec: u64, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiTimestamp { + pub(crate) handle: u32, + pub(crate) offset: u32, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiTimestamps { + pub(crate) start: UapiTimestamp, + pub(crate) end: UapiTimestamp, +} + +fn timestamps(raw: &[u8], offset: usize) -> UapiTimestamps { + UapiTimestamps { + start: UapiTimestamp { + handle: get_u32(raw, offset), + offset: get_u32(raw, offset + 4), + }, + end: UapiTimestamp { + handle: get_u32(raw, offset + 8), + offset: get_u32(raw, offset + 12), + }, + } +} + +fn program(raw: &[u8], offset: usize, high_offset: usize) -> UapiProgram { + UapiProgram { + usc: get_u32(raw, offset), + resource_spec: get_u32(raw, offset + 4) as u64 + | (get_u32(raw, high_offset) as u64) << 32, + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiZlsBuffer { + pub(crate) base: u64, + pub(crate) compression_base: u64, + pub(crate) stride: u32, + pub(crate) compression_stride: u32, +} + +fn zls(raw: &[u8], offset: usize) -> UapiZlsBuffer { + UapiZlsBuffer { + base: get_u64(raw, offset), + compression_base: get_u64(raw, offset + 8), + stride: get_u32(raw, offset + 0x10), + compression_stride: get_u32(raw, offset + 0x14), + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiRenderCommand { + pub(crate) flags: u32, + pub(crate) depth_dimensions: u32, + pub(crate) vdm_base: u64, + pub(crate) vertex_helper: UapiHelperProgram, + pub(crate) fragment_helper: UapiHelperProgram, + pub(crate) scissor_base: u64, + pub(crate) depth_bias_base: u64, + pub(crate) occlusion_query_base: u64, + pub(crate) depth: UapiZlsBuffer, + pub(crate) stencil: UapiZlsBuffer, + pub(crate) zls_control: u64, + pub(crate) multisample_control: u64, + pub(crate) sampler_heap: u64, + pub(crate) ppp_control: u32, + pub(crate) width: u16, + pub(crate) height: u16, + pub(crate) layers: u16, + pub(crate) sampler_count: u16, + pub(crate) utile_width: u8, + pub(crate) utile_height: u8, + pub(crate) samples: u8, + pub(crate) sample_size: u8, + pub(crate) merge_upper_x: u32, + pub(crate) merge_upper_y: u32, + pub(crate) background: UapiProgram, + pub(crate) end_of_tile: UapiProgram, + pub(crate) partial_background: UapiProgram, + pub(crate) partial_end_of_tile: UapiProgram, + pub(crate) depth_clear: u32, + pub(crate) stencil_clear: u32, + pub(crate) vertex_timestamps: UapiTimestamps, + pub(crate) fragment_timestamps: UapiTimestamps, + pub(crate) prior_vdm: u64, + pub(crate) prior_cdm: u64, + /// `drm_asahi_g18_render_resources` words; zero unless flagged. + pub(crate) g18_resources: [u32; 20], +} + +impl UapiRenderCommand { + fn parse(raw: &[u8]) -> Result { + // Legacy payloads are zero-extended exactly as before. A flagged G18 + // suffix must be complete; padding could hide a truncated field. + let has_resources = raw.len() >= 4 && get_u32(raw, 0) & RENDER_G18_RESOURCES != 0; + if has_resources && raw.len() < UAPI_G18_RENDER_SIZE { + return Err(UapiTranslateError::PayloadTruncated); + } + if !has_resources && raw.len() > UAPI_RENDER_SIZE + && raw[UAPI_RENDER_SIZE..].iter().any(|byte| *byte != 0) + { + return Err(UapiTranslateError::PayloadTail); + } + let raw = padded_payload::(raw)?; + let mut g18_resources = [0; 20]; + if has_resources { + for (i, word) in g18_resources.iter_mut().enumerate() { + *word = get_u32(&raw, UAPI_RENDER_SIZE + i * 4); + } + } + Ok(Self { + flags: get_u32(&raw, 0x00), + depth_dimensions: get_u32(&raw, 0x04), + vdm_base: get_u64(&raw, 0x08), + vertex_helper: helper(&raw, 0x10), + fragment_helper: helper(&raw, 0x20), + scissor_base: get_u64(&raw, 0x30), + depth_bias_base: get_u64(&raw, 0x38), + occlusion_query_base: get_u64(&raw, 0x40), + depth: zls(&raw, 0x48), + stencil: zls(&raw, 0x60), + zls_control: get_u64(&raw, 0x78), + multisample_control: get_u64(&raw, 0x80), + sampler_heap: get_u64(&raw, 0x88), + ppp_control: get_u32(&raw, 0x90), + width: get_u16(&raw, 0x94), + height: get_u16(&raw, 0x96), + layers: get_u16(&raw, 0x98), + sampler_count: get_u16(&raw, 0x9a), + utile_width: raw[0x9c], + utile_height: raw[0x9d], + samples: raw[0x9e], + sample_size: raw[0x9f], + merge_upper_x: get_u32(&raw, 0xa0), + merge_upper_y: get_u32(&raw, 0xa4), + background: program(&raw, 0xa8, 0xf8), + end_of_tile: program(&raw, 0xb0, 0xf0), + partial_background: program(&raw, 0xb8, 0xfc), + partial_end_of_tile: program(&raw, 0xc0, 0xf4), + depth_clear: get_u32(&raw, 0xc8), + stencil_clear: get_u32(&raw, 0xcc), + vertex_timestamps: timestamps(&raw, 0xd0), + fragment_timestamps: timestamps(&raw, 0xe0), + prior_vdm: get_u64(&raw, 0x100), + prior_cdm: get_u64(&raw, 0x108), + g18_resources, + }) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct UapiComputeCommand { + pub(crate) flags: u32, + pub(crate) sampler_count: u32, + pub(crate) control_stream_base: u64, + pub(crate) control_stream_end: u64, + pub(crate) sampler_heap: u64, + pub(crate) helper: UapiHelperProgram, + pub(crate) timestamps: UapiTimestamps, + pub(crate) scs_layout: u64, + pub(crate) g18_resources: [u32; 16], + pub(crate) prior_vdm: u64, + pub(crate) prior_cdm: u64, +} + +impl UapiComputeCommand { + fn parse(raw: &[u8]) -> Result { + // Legacy compute payloads are zero-extended as before. A flagged + // metadata payload must be complete; padding it could hide truncation + // of a valid zero-valued field or reserved word. + let has_resources = raw.len() >= 4 && get_u32(raw, 0) & COMPUTE_G18_RESOURCES != 0; + if has_resources && raw.len() < UAPI_G18_COMPUTE_SIZE { + return Err(UapiTranslateError::PayloadTruncated); + } + if !has_resources && raw.len() > UAPI_COMPUTE_SIZE + && raw[UAPI_COMPUTE_SIZE..].iter().any(|byte| *byte != 0) + { + return Err(UapiTranslateError::PayloadTail); + } + let raw = padded_payload::(raw)?; + let mut g18_resources = [0; 16]; + if has_resources { + for (i, word) in g18_resources.iter_mut().enumerate() { + *word = get_u32(&raw, 72 + i * 4); + } + } + Ok(Self { + flags: get_u32(&raw, 0), + sampler_count: get_u32(&raw, 4), + control_stream_base: get_u64(&raw, 8), + control_stream_end: get_u64(&raw, 0x10), + sampler_heap: get_u64(&raw, 0x18), + helper: helper(&raw, 0x20), + timestamps: timestamps(&raw, 0x30), + scs_layout: get_u64(&raw, 0x40), + g18_resources, + prior_vdm: if has_resources { 0 } else { get_u64(&raw, 0x48) }, + prior_cdm: if has_resources { 0 } else { get_u64(&raw, 0x50) }, + }) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum ParsedHardwareCommand { + Render { + index: u32, + header: UapiCommandHeader, + payload: UapiRenderCommand, + vertex_attachments: UapiAttachmentList, + fragment_attachments: UapiAttachmentList, + }, + Compute { + index: u32, + header: UapiCommandHeader, + payload: UapiComputeCommand, + attachments: UapiAttachmentList, + }, +} + +pub(crate) struct UapiCommandParser<'a> { + raw: &'a [u8], + offset: usize, + command_index: u32, + hardware_count: u32, + render_count: u16, + compute_count: u16, + vertex_attachments: UapiAttachmentList, + fragment_attachments: UapiAttachmentList, + compute_attachments: UapiAttachmentList, +} + +impl<'a> UapiCommandParser<'a> { + pub(crate) const fn new(raw: &'a [u8]) -> Self { + Self { + raw, + offset: 0, + command_index: 0, + hardware_count: 0, + render_count: 0, + compute_count: 0, + vertex_attachments: UapiAttachmentList::EMPTY, + fragment_attachments: UapiAttachmentList::EMPTY, + compute_attachments: UapiAttachmentList::EMPTY, + } + } + + pub(crate) fn finish(&self) -> Result { + if self.offset != self.raw.len() { + return Err(UapiTranslateError::PayloadTruncated); + } + if self.hardware_count == 0 || self.hardware_count > UAPI_MAX_HARDWARE_COMMANDS { + return Err(UapiTranslateError::HardwareCommandCount); + } + Ok(self.hardware_count) + } + + pub(crate) fn next_hardware( + &mut self, + ) -> Result, UapiTranslateError> { + loop { + if self.offset == self.raw.len() { + return Ok(None); + } + if self.raw.len() - self.offset < UAPI_COMMAND_HEADER_SIZE { + return Err(UapiTranslateError::HeaderTruncated); + } + let header = UapiCommandHeader::parse(&self.raw[self.offset..])?; + self.offset += UAPI_COMMAND_HEADER_SIZE; + let end = self + .offset + .checked_add(header.size as usize) + .ok_or(UapiTranslateError::PayloadTruncated)?; + if end > self.raw.len() { + return Err(UapiTranslateError::PayloadTruncated); + } + let payload = &self.raw[self.offset..end]; + self.offset = end; + self.command_index += 1; + + match header.command_type { + COMMAND_RENDER | COMMAND_COMPUTE => { + if header.render_barrier != UAPI_BARRIER_NONE + && header.render_barrier > self.render_count + { + return Err(UapiTranslateError::BarrierFuture); + } + if header.compute_barrier != UAPI_BARRIER_NONE + && header.compute_barrier > self.compute_count + { + return Err(UapiTranslateError::BarrierFuture); + } + self.hardware_count += 1; + if self.hardware_count > UAPI_MAX_HARDWARE_COMMANDS { + return Err(UapiTranslateError::HardwareCommandCount); + } + if header.command_type == COMMAND_RENDER { + self.render_count += 1; + return Ok(Some(ParsedHardwareCommand::Render { + index: self.command_index, + header, + payload: UapiRenderCommand::parse(payload)?, + vertex_attachments: self.vertex_attachments, + fragment_attachments: self.fragment_attachments, + })); + } + self.compute_count += 1; + return Ok(Some(ParsedHardwareCommand::Compute { + index: self.command_index, + header, + payload: UapiComputeCommand::parse(payload)?, + attachments: self.compute_attachments, + })); + } + SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { + if header.render_barrier != UAPI_BARRIER_NONE + || header.compute_barrier != UAPI_BARRIER_NONE + { + return Err(UapiTranslateError::AttachmentBarrier); + } + let attachments = UapiAttachmentList::parse(payload)?; + match header.command_type { + SET_VERTEX_ATTACHMENTS => self.vertex_attachments = attachments, + SET_FRAGMENT_ATTACHMENTS => self.fragment_attachments = attachments, + SET_COMPUTE_ATTACHMENTS => self.compute_attachments = attachments, + _ => unreachable!(), + } + } + _ => return Err(UapiTranslateError::CommandType), + } + } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum GpuAccess { + Read, + Write, + ReadWrite, +} + +pub(crate) trait GpuAddressSpace { + fn covers(&self, address: u64, size: u64, access: GpuAccess) -> bool; +} + +fn require_range( + address_space: &A, + address: u64, + size: u64, + access: GpuAccess, +) -> Result<(), UapiTranslateError> { + let end = address + .checked_add(size) + .ok_or(UapiTranslateError::AddressRange)?; + if size == 0 || end <= address || !address_space.covers(address, size, access) { + return Err(UapiTranslateError::AddressRange); + } + Ok(()) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct QueueUscWindow { + pub(crate) base: u64, + pub(crate) user_start: u64, + pub(crate) user_end: u64, +} + +impl QueueUscWindow { + pub(crate) fn validate(self) -> Result<(), UapiTranslateError> { + if self.base & (USC_WINDOW_SIZE - 1) != 0 { + return Err(UapiTranslateError::QueueUscAlignment); + } + let end = self + .base + .checked_add(USC_WINDOW_SIZE) + .ok_or(UapiTranslateError::QueueUscRange)?; + if self.base < self.user_start || end > self.user_end || end <= self.base { + return Err(UapiTranslateError::QueueUscRange); + } + Ok(()) + } + + fn full_program( + self, + address_space: &A, + tagged_offset: u32, + ) -> Result { + self.validate()?; + if tagged_offset == 0 { + return Err(UapiTranslateError::ProgramOffset); + } + let allocation = self + .base + .checked_add((tagged_offset & !7) as u64) + .ok_or(UapiTranslateError::ProgramOffset)?; + require_range(address_space, allocation, 4, GpuAccess::Read)?; + // Honeykrisp carries resource metadata in the low three UAPI bits, + // but G17P's native 3D command strips those bits before programming + // every BG/EOT/partial USC address. Preserving bit 2 launched four + // bytes into the instruction stream and contradicted all complete + // Metal register-list captures. + Ok(allocation) + } +} + +fn validate_sampler( + address_space: &A, + heap: u64, + count: u32, +) -> Result<(), UapiTranslateError> { + if count > MAX_SAMPLERS { + return Err(UapiTranslateError::SamplerCount); + } + if (heap == 0) != (count == 0) { + return Err(UapiTranslateError::SamplerPair); + } + if count != 0 { + if heap & (SAMPLER_SIZE - 1) != 0 { + return Err(UapiTranslateError::AddressAlignment); + } + require_range( + address_space, + heap, + count as u64 * SAMPLER_SIZE, + GpuAccess::Read, + )?; + } + Ok(()) +} + +fn validate_attachments( + address_space: &A, + attachments: &UapiAttachmentList, +) -> Result<(), UapiTranslateError> { + for attachment in attachments.as_slice() { + require_range( + address_space, + attachment.address, + attachment.size, + GpuAccess::Write, + )?; + } + Ok(()) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct RenderInternalState { + pub(crate) parameters: G17pRenderParameters, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct TranslatedRenderCommand { + /// Exact logical render prefix assigned by the DRM ioctl dispatcher. + pub(crate) render_order: submission::G17PRenderOrder, + /// Original UAPI render index, retained through admission. + pub(crate) render_barrier: u16, + /// Original UAPI compute index, retained through admission. + pub(crate) compute_barrier: u16, + /// Exact compute prefix resolved at ioctl admission. Later independent + /// compute commands must not become parents of this render. + pub(crate) compute_wait_through: Option, + pub(crate) flags: u32, + pub(crate) vdm_base: u64, + pub(crate) parameters: G17pRenderParameters, + pub(crate) vertex_attachments: UapiAttachmentList, + pub(crate) fragment_attachments: UapiAttachmentList, + pub(crate) vertex_timestamps: UapiTimestamps, + pub(crate) fragment_timestamps: UapiTimestamps, +} + +fn validate_zls( + address_space: &A, + value: UapiZlsBuffer, + layers: u16, + g18_subpage: bool, +) -> Result<(), UapiTranslateError> { + if value.base == 0 + && (value.compression_base != 0 || value.stride != 0 || value.compression_stride != 0) + { + return Err(UapiTranslateError::ZlsFields); + } + if value.compression_base == 0 && value.compression_stride != 0 { + return Err(UapiTranslateError::ZlsFields); + } + if !g18_subpage && layers > 1 && value.base != 0 && value.stride == 0 { + return Err(UapiTranslateError::ZlsFields); + } + if value.stride != 0 && value.stride & 0x3fff != 1 + && !(g18_subpage && value.stride & 0x3fff == 0) { + return Err(UapiTranslateError::ZlsFields); + } + if value.compression_stride & 0x3fff != 0 { + return Err(UapiTranslateError::ZlsFields); + } + if value.base != 0 { + let layer_stride = if g18_subpage && layers > 1 { + let unit = if value.stride & 1 != 0 { PAGE_SIZE } else { 0x80 }; + ((value.stride as u64 >> 14) + 1) * unit + } else if value.stride == 0 { + 0 + } else { + ((value.stride as u64 >> 14) + 1) * PAGE_SIZE + }; + let size = layer_stride + .checked_mul(layers.saturating_sub(1) as u64) + .and_then(|value| value.checked_add(1)) + .ok_or(UapiTranslateError::AddressRange)?; + require_range(address_space, value.base, size, GpuAccess::ReadWrite)?; + } + if value.compression_base != 0 { + let layer_stride = ((value.compression_stride as u64 >> 14) + 1) * 0x80; + let size = layer_stride + .checked_mul(layers.saturating_sub(1) as u64) + .and_then(|value| value.checked_add(1)) + .ok_or(UapiTranslateError::AddressRange)?; + require_range( + address_space, + value.compression_base, + size, + GpuAccess::ReadWrite, + )?; + } + Ok(()) +} + +/// Bounded M5 D32 clear/store envelope, alongside the original color-only +/// profile. Native 25G76 supplies ff00ff dimensions and 80044 with compression; +/// bits2/6 select compression, while bit19 stores the depth plane. Geometry, +/// stencil absence, and application programs are checked by the M5 caller. +pub(crate) fn validate_m5_reference_depth( + command: &UapiRenderCommand, + address_space: &A, +) -> Result<(), UapiTranslateError> { + let depth = command.depth; + if depth.base == 0 { + // No depth plane. The surface may still carry an inert stencil one, + // which contributes nothing but its compression pair and the shared + // pixel dimensions; a render that transfers it is refused with the + // rest of the stencil profile. + let stencil_only = command.stencil.base != 0 + && command.zls_control + == if command.stencil.compression_base != 0 { 0x110 } else { 0 } + && command.depth_dimensions + == ((u32::from(command.width) - 1) + | ((u32::from(command.height) - 1) << 16)); + return if depth.compression_base == 0 && depth.stride == 0 + && depth.compression_stride == 0 + && (stencil_only + || (command.zls_control == 0 && command.depth_dimensions == 0)) { + Ok(()) + } else { + Err(UapiTranslateError::ZlsFields) + }; + } + let compressed = depth.compression_base != 0; + // The control word's load and store bits are the only part a render + // chooses: bit15 loads the depth plane and bit19 stores it, and a render + // that neither tests nor writes depth sets neither, which is how a + // conformance surface with an unused depth buffer arrives. Everything + // else -- the compression pair in bits 2 and 6, the GPU tiling, the 32F + // format -- is the witnessed profile and stays exact. depth_flags reaches + // register 0x15319 unchanged either way, so the admitted envelope is the + // set of load/store combinations over that fixed remainder. + let compression_bits = if compressed { 0x44 } else { 0 }; + // Bits 25-26 select the depth format: 0 is 32-bit float, 2 is 16-bit + // unorm. The narrow plane was captured on 25G76 alongside the wide one + // and moves nothing else in the register program except the clear value + // and one ISP flag, both of which the caller derives. Its compression + // metadata has no witness, so a compressed 16-bit plane stays out. + let z16 = command.zls_control & (3 << 25) == (2 << 25); + if z16 && compressed { + return Err(UapiTranslateError::ZlsFields); + } + let format_bits = if z16 { 2 << 25 } else { 0 }; + // A stencil plane may be attached without being transferred: a surface + // with a depth-stencil buffer carries one for every render, whether or + // not the render uses it. Its compression pair in bits 4 and 8 describes + // the attached layout and is the only stencil state admitted here -- + // loading or storing the plane (bits 14 and 18) needs its own witnesses, + // as does the stencil unit in the graphics record. + let stencil_compression_bits = + if command.stencil.compression_base != 0 { 0x110 } else { 0 }; + let control_transfers = command.zls_control & 0x88000; + let expected_control = + compression_bits | stencil_compression_bits | format_bits | control_transfers; + let width = u32::from(command.width); + let height = u32::from(command.height); + if !(1..=M5_MAX_RENDER_DIMENSION).contains(&width) + || !(1..=M5_MAX_RENDER_DIMENSION).contains(&height) + || command.layers != 1 || (compressed && (width < 16 || height < 16)) { + return Err(UapiTranslateError::ZlsFields); + } + // AIL tiles are 16 KiB whatever the format: 64x64 at four bytes a pixel, + // 128x64 at two. While both axes fit one tile the level is a whole + // number of them; if either axis is smaller, the level uses a + // power-of-two miptail aligned to a 128-byte cacheline. Single-layer M5 + // surfaces are not page-padded. + let (tile_width, bytes_per_pixel) = if z16 { (128u32, 2u64) } else { (64u32, 4u64) }; + let data_bytes = if width >= tile_width && height >= 64 { + u64::from(width.div_ceil(tile_width)) * u64::from(height.div_ceil(64)) * 0x4000 + } else { + (u64::from(width.next_power_of_two()) + * u64::from(height.next_power_of_two()) * bytes_per_pixel) + .div_ceil(128) * 128 + }; + let metadata_bytes = (u64::from(width.next_power_of_two().div_ceil(16)) + * u64::from(height.next_power_of_two().div_ceil(16)) * 8).div_ceil(128) * 128; + let dimensions = (width - 1) | ((height - 1) << 16); + if command.depth_dimensions != dimensions + || command.zls_control != expected_control + // The clear value is whatever the application asked for; it reaches + // register 0x15301 verbatim and is only consumed when the render + // actually clears the plane. + || (command.depth_clear & 0x7fffffff) > 0x7f800000 + // Image suballocations and small miptails use cacheline alignment; + // the backing VM pages remain independently validated below. + || depth.base & 0x7f != 0 || depth.compression_base & 0x7f != 0 + // Both strides are array strides, and the M5 caller zeroes them + // because native single-layer ZLS does not encode one. Every render + // admitted here is single-layer -- layers != 1 is refused above -- so + // the value that arrives is whatever the userspace packer computed + // and the hardware never sees it: for a surface smaller than a page + // Mesa's (pages - 1) << 14 | 1 underflows to 0xffffc001. Comparing it + // would refuse a valid render over a field that is discarded. The + // backing store is still validated in full below, from the + // dimensions rather than from either stride. + || (!compressed && depth.compression_stride != 0) { + return Err(UapiTranslateError::ZlsFields); + } + // Validate the entire resized surface and metadata before the + // M5 caller removes the unused single-layer array stride fields. + require_range(address_space, depth.base, data_bytes, GpuAccess::ReadWrite)?; + if compressed { + require_range(address_space, depth.compression_base, metadata_bytes, + GpuAccess::ReadWrite)?; + } + Ok(()) +} + +pub(crate) fn translate_render_command( + command: UapiRenderCommand, + vertex_attachments: UapiAttachmentList, + fragment_attachments: UapiAttachmentList, + queue: QueueUscWindow, + address_space: &A, + internal: RenderInternalState, +) -> Result { + translate_render_command_with_capacity(command, vertex_attachments, + fragment_attachments, queue, address_space, internal, 32_768, false) +} + +fn translate_render_command_with_capacity( + command: UapiRenderCommand, + vertex_attachments: UapiAttachmentList, + fragment_attachments: UapiAttachmentList, + queue: QueueUscWindow, + address_space: &A, + internal: RenderInternalState, + tile_capacity: u64, + g18_subpage: bool, +) -> Result { + if command.flags & !RENDER_FLAGS != 0 { + return Err(UapiTranslateError::FlagsUnknownBits); + } + // Genuinely unimplemented on G17P rather than merely unvalidated: + // `G17pRenderParameters` carries no helper-program fields at all, so + // VERTEX_SCRATCH has nowhere to put the scratch binding, and there is no + // cluster-count control for NO_VERTEX_CLUSTERING. A clean EINVAL beats + // rendering with the request silently dropped. + if command.flags & (RENDER_VERTEX_SCRATCH | RENDER_NO_VERTEX_CLUSTERING) != 0 { + return Err(UapiTranslateError::FlagsUnsupported); + } + // RSRC_SPEC_HI is *declarative*, and honouring it must not mean rejecting. + // The UAPI defines it as "the appended resource-specifier high dwords are + // present", and states its purpose: "This flag lets old kernels report an + // unsupported render payload instead of silently truncating 64-bit G17 + // values." It exists for kernels that do NOT understand the dwords. + // + // This kernel does understand them -- `program()` ORs the high dword in + // unconditionally, with no reference to the flag -- so the flag cannot + // change what we do with a payload that sets it. The old check therefore + // refused payloads it would otherwise have handled identically, protecting + // nothing; it is the same bring-up leftover as the stencil-clear mask. + // + // Honour the documented meaning instead: when the flag is clear the high + // dwords are "not present", so mask them off rather than refuse the + // submission. A userspace built against the 240-byte upstream struct (whose + // payload `padded_payload` zero-fills) and one that clears the flag now + // behave identically, which is what "not present" has to mean. + let resource_spec_mask = if command.flags & RENDER_RSRC_SPEC_HI != 0 { + u64::MAX + } else { + u32::MAX as u64 + }; + if !(1..=16_384).contains(&command.width) || !(1..=16_384).contains(&command.height) { + return Err(UapiTranslateError::Dimensions); + } + if !(1..=2048).contains(&command.layers) { + return Err(UapiTranslateError::Layers); + } + if !matches!( + (command.utile_width, command.utile_height), + (32, 32) | (32, 16) | (16, 16) + ) { + return Err(UapiTranslateError::UtileDimensions); + } + let samples_log2 = match command.samples { + 1 => 0, + 2 => 1, + 4 => 2, + _ => return Err(UapiTranslateError::Samples), + }; + let utile_bytes = command.sample_size as u64 + * command.utile_width as u64 + * command.utile_height as u64 + * command.samples as u64; + if utile_bytes > tile_capacity { + return Err(UapiTranslateError::TilebufferSize); + } + let blocks_per_utile = utile_bytes.div_ceil(2048); + + if command.vdm_base == 0 || command.vdm_base & 3 != 0 { + return Err(UapiTranslateError::AddressAlignment); + } + require_range(address_space, command.vdm_base, 4, GpuAccess::Read)?; + + if command.scissor_base == 0 || command.scissor_base & 7 != 0 { + return Err(UapiTranslateError::AddressAlignment); + } + require_range(address_space, command.scissor_base, 8, GpuAccess::Read)?; + if command.depth_bias_base != 0 { + if command.depth_bias_base & 7 != 0 { + return Err(UapiTranslateError::AddressAlignment); + } + require_range(address_space, command.depth_bias_base, 8, GpuAccess::Read)?; + } + if command.occlusion_query_base != 0 { + if command.occlusion_query_base & 7 != 0 { + return Err(UapiTranslateError::AddressAlignment); + } + require_range( + address_space, + command.occlusion_query_base, + 8, + GpuAccess::Write, + )?; + } + validate_zls(address_space, command.depth, command.layers, g18_subpage)?; + validate_zls(address_space, command.stencil, command.layers, g18_subpage)?; + validate_sampler( + address_space, + command.sampler_heap, + command.sampler_count as u32, + )?; + if command.vertex_helper + != (UapiHelperProgram { + binary: 0, + config: 0, + data: 0, + }) + || command.fragment_helper + != (UapiHelperProgram { + binary: 0, + config: 0, + data: 0, + }) + { + return Err(UapiTranslateError::HelperProgram); + } + // `isp_bgobjvals` is the *whole* ISP_BGOBJVALS register value, not just + // the stencil clear: the UAPI documents "the bottom 8-bits contain the + // stencil buffer clear value", and every Mesa backend unconditionally + // seeds the upper bits with 0x300 before OR-ing the clear in + // (hk_cmd_draw.c `render->cr.isp_bgobjvals = 0x300;`, + // agx_pipe.c `c->isp_bgobjvals = 0x300;`, d12_queue.c `0x300 | stencil`). + // The legacy queue path passes the field straight through to the firmware + // (queue/render.rs `let load_bgobjvals = cmdbuf.isp_bgobjvals as u64`), so + // rejecting anything above 0xff refused every real render pass while the + // in-tree render selftest -- which leaves the field zero -- was accepted. + // Accept the register value; `build_*_descriptor` re-asserts the 0x300 + // bits with `stencil_clear_value | 0x300`, which is idempotent for the + // value userspace sends and still supplies 0x300 when it sends zero. + + let background = queue.full_program(address_space, command.background.usc)?; + let end_of_tile = queue.full_program(address_space, command.end_of_tile.usc)?; + let partial_background = queue.full_program(address_space, command.partial_background.usc)?; + let partial_end_of_tile = queue.full_program(address_space, command.partial_end_of_tile.usc)?; + validate_attachments(address_space, &vertex_attachments)?; + validate_attachments(address_space, &fragment_attachments)?; + + let utile_config = ((command.utile_width as u64 / 16) << 12) + | ((command.utile_height as u64 / 16) << 14) + | samples_log2; + let mut tile_config = 0x280; + if command.layers > 1 { + tile_config |= 1; + } + if command.flags & RENDER_PROCESS_EMPTY_TILES != 0 { + tile_config |= 0x1_0000; + } + + let mut parameters = internal.parameters; + parameters.width = command.width as u32; + parameters.height = command.height as u32; + parameters.encoder = command.vdm_base; + parameters.layers = command.layers; + parameters.utile_width = command.utile_width; + parameters.utile_height = command.utile_height; + parameters.utile_config = utile_config; + parameters.multisample_control = command.multisample_control; + parameters.ppp_control = command.ppp_control as u64; + parameters.tib_blocks = blocks_per_utile; + parameters.tile_config = tile_config; + parameters.depth_dimensions = command.depth_dimensions as u64; + parameters.depth_buffer = command.depth.base; + parameters.depth_aux_buffer = command.depth.compression_base; + parameters.depth_stride = command.depth.stride as u64; + parameters.depth_aux_stride = command.depth.compression_stride as u64; + parameters.stencil_buffer = command.stencil.base; + parameters.stencil_aux_buffer = command.stencil.compression_base; + parameters.stencil_stride = command.stencil.stride as u64; + parameters.stencil_aux_stride = command.stencil.compression_stride as u64; + parameters.depth_flags = command.zls_control; + // The firmware's internal partial-render phases preserve attached Z/S + // surfaces even when the render-pass boundary is store-only. Mesa already + // computes this distinction for its partial BG/EOT programs, but the + // current 256-byte render UAPI carries only the boundary ZLS word. Derive + // the exact uncompressed enable bits here until the append-only partial + // ZLS UAPI field is plumbed; tiling/compression/format bits remain those + // packed into the original word. + parameters.partial_depth_flags = command.zls_control + | if command.depth.base != 0 { (1 << 15) | (1 << 19) } else { 0 } + | if command.stencil.base != 0 { (1 << 14) | (1 << 18) } else { 0 }; + parameters.occlusion_query_base = command.occlusion_query_base; + parameters.scissor_array = command.scissor_base; + parameters.depth_bias_array = command.depth_bias_base; + parameters.sampler_array = command.sampler_heap; + parameters.sampler_count = command.sampler_count as u32; + parameters.process_empty_tiles = command.flags & RENDER_PROCESS_EMPTY_TILES != 0; + parameters.merge_upper_x_bits = command.merge_upper_x; + parameters.merge_upper_y_bits = command.merge_upper_y; + parameters.depth_clear_value_bits = command.depth_clear; + parameters.stencil_clear_value = command.stencil_clear; + parameters.load_pipeline_bind = g17p_bg_resource_spec( + command.background.resource_spec, + resource_spec_mask, + internal.parameters.bg_resource_prefix, + ); + parameters.load_pipeline = background; + parameters.store_pipeline_bind = command.end_of_tile.resource_spec & resource_spec_mask; + parameters.store_pipeline = end_of_tile; + // These high 17 bits are BG shader pass control, not an address class. + // Native derives main and partial masks from their respective shader + // outputs; they need not match. The default diagnostic prefix is zero, + // preserving both full RT0 output masks and no-output masks from userspace. + parameters.partial_load_pipeline_bind = g17p_bg_resource_spec( + command.partial_background.resource_spec, + resource_spec_mask, + internal.parameters.bg_resource_prefix, + ); + parameters.partial_load_pipeline = partial_background; + parameters.partial_store_pipeline_bind = + command.partial_end_of_tile.resource_spec & resource_spec_mask; + parameters.partial_store_pipeline = partial_end_of_tile; + + Ok(TranslatedRenderCommand { + render_order: submission::G17PRenderOrder::default(), + render_barrier: UAPI_BARRIER_NONE, + compute_barrier: UAPI_BARRIER_NONE, + compute_wait_through: None, + flags: command.flags, + vdm_base: command.vdm_base, + parameters, + vertex_attachments, + fragment_attachments, + vertex_timestamps: command.vertex_timestamps, + fragment_timestamps: command.fragment_timestamps, + }) +} + +fn g17p_bg_resource_spec(resource_spec: u64, present_mask: u64, diagnostic_prefix: u64) -> u64 { + diagnostic_prefix | (resource_spec & present_mask) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct TranslatedComputeCommand { + /// Monotonic logical index, independent of the hardware timestamp. + pub(crate) compute_sequence: u64, + /// Explicit same-engine prefix; only host-published timestamps need host waits. + pub(crate) compute_wait_through: Option, + pub(crate) render_wait_through: Option, + pub(crate) render_wait_last: Option, + pub(crate) usc_exec_base: u64, + pub(crate) control_stream_base: u64, + pub(crate) control_stream_end: u64, + pub(crate) control_stream_terminator: u64, + pub(crate) sampler_heap: u64, + pub(crate) sampler_count: u32, + pub(crate) attachments: UapiAttachmentList, + pub(crate) g17p_add3_buffers: Option<[u64; 3]>, + pub(crate) timestamps: UapiTimestamps, + pub(crate) scs_layout: u64, + /// G18 only: the command carried `DRM_ASAHI_COMPUTE_USES_TEXTURE_STATE`. + /// [`translate_compute_command`] refuses that bit like any other unknown + /// one and leaves this false; the G18 adapter admits the bit, strips it + /// before translation and sets this afterwards. + pub(crate) g18_texture_state: bool, + /// Validated native descriptor inputs; resource/launch integration is + /// separate, so this field does not by itself authorize scratch use. + pub(crate) g18_resource_descriptor: Option<[u32; 23]>, +} + +pub(crate) fn translate_compute_command( + command: UapiComputeCommand, + attachments: UapiAttachmentList, + queue: QueueUscWindow, + address_space: &A, +) -> Result { + queue.validate()?; + if command.flags & !COMPUTE_G17P_ADD3_PROOF != 0 { + return Err(UapiTranslateError::FlagsUnknownBits); + } + if command.g18_resources != [0; 16] { + return Err(UapiTranslateError::FlagsUnsupported); + } + if command.control_stream_base & 3 != 0 + || command.control_stream_end & 3 != 0 + || command.control_stream_end <= command.control_stream_base + { + return Err(UapiTranslateError::AddressAlignment); + } + require_range( + address_space, + command.control_stream_base, + command.control_stream_end - command.control_stream_base, + GpuAccess::Read, + )?; + validate_sampler(address_space, command.sampler_heap, command.sampler_count)?; + if command.helper + != (UapiHelperProgram { + binary: 0, + config: 0, + data: 0, + }) + { + return Err(UapiTranslateError::HelperProgram); + } + let g17p_add3_buffers = if command.flags & COMPUTE_G17P_ADD3_PROOF != 0 { + let entries = attachments.as_slice(); + if entries.len() != 3 + || entries + .iter() + .any(|entry| entry.size < G17P_ADD3_BUFFER_BYTES) + { + return Err(UapiTranslateError::Add3ProofAttachments); + } + require_range( + address_space, + entries[0].address, + G17P_ADD3_BUFFER_BYTES, + GpuAccess::Read, + )?; + require_range( + address_space, + entries[1].address, + G17P_ADD3_BUFFER_BYTES, + GpuAccess::Read, + )?; + require_range( + address_space, + entries[2].address, + G17P_ADD3_BUFFER_BYTES, + GpuAccess::Write, + )?; + Some([entries[0].address, entries[1].address, entries[2].address]) + } else { + validate_attachments(address_space, &attachments)?; + None + }; + Ok(TranslatedComputeCommand { + compute_sequence: 0, + compute_wait_through: None, + render_wait_through: None, + render_wait_last: None, + usc_exec_base: queue.base, + control_stream_base: command.control_stream_base, + control_stream_end: command.control_stream_end, + control_stream_terminator: command.control_stream_end - 4, + sampler_heap: command.sampler_heap, + sampler_count: command.sampler_count, + attachments, + g17p_add3_buffers, + timestamps: command.timestamps, + scs_layout: command.scs_layout, + g18_texture_state: false, + g18_resource_descriptor: None, + }) +} + +impl TranslatedComputeCommand { + +} diff --git a/drivers/gpu/drm/asahi/m5/completion.rs b/drivers/gpu/drm/asahi/m5/completion.rs new file mode 100644 index 0000000000000..b6b1e748df482 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/completion.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Completion ownership for the bounded M5 TA/fragment pair. +//! +//! 25G76 GFX 0x17544 compares scheduler.completed with *scheduler.submitted; +//! 0x1763c unlinks the completed scheduler. The submitted total is host-owned, +//! not a firmware-decremented pending count. 0x17a68/0x17ae0 then write the +//! first stamp pointer and 0x17b98 publishes the corresponding event mask. + +// The 32-bit completion value reserves its low byte. Stop before it wraps; +// storage-ring wrap is independent of this monotonically increasing stamp. +pub(crate) const MAX_GRAPHICS_GENERATION: u32 = 0x00ff_ffff; +pub(crate) const GRAPHICS_POINTER_COUNT: u32 = 0x500; + +pub(crate) const fn graphics_pointer_head(generation: u32) -> u32 { + (1 + generation * 3) % GRAPHICS_POINTER_COUNT +} + +#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)] +pub(crate) struct M5GraphicsCompletion { + pub(crate) submitted: u32, + pub(crate) completed: u32, + pub(crate) linked: u32, + pub(crate) list: [u64; 2], + pub(crate) stamps: [u32; 2], + pub(crate) signalled: u128, +} + +/// The same native scheduler retirement contract for one compute record. +#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)] +pub(crate) struct M5ComputeCompletion { + pub(crate) submitted: u32, + pub(crate) completed: u32, + pub(crate) linked: u32, + pub(crate) list: [u64; 2], + pub(crate) stamp: u32, + pub(crate) signalled: u128, +} + +impl M5ComputeCompletion { + pub(crate) fn complete_at(self, list_address: u64, queue_id: u8, stamp: u32) -> bool { + list_address != 0 && queue_id < 128 && stamp != 0 && stamp & 0xff == 0 + && self.submitted == 1 && self.completed == 1 && self.linked == 0 + && self.list == [0, list_address] && self.stamp == stamp + && self.signalled & (1u128 << queue_id) != 0 + } +} + +impl M5GraphicsCompletion { + + pub(crate) fn pair_complete_at(self, list_address: u64, stamp: u32) -> bool { + list_address != 0 + && stamp != 0 && stamp & 0xff == 0 + && self.submitted == 2 + && self.completed == self.submitted + && self.linked == 0 + && self.list == [0, list_address] + && self.stamps == [stamp; 2] + && self.signalled & 0xc00 == 0xc00 + } +} + diff --git a/drivers/gpu/drm/asahi/m5/compute.rs b/drivers/gpu/drm/asahi/m5/compute.rs new file mode 100644 index 0000000000000..71e1384b070bc --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/compute.rs @@ -0,0 +1,246 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +#![cfg_attr(not(test), allow(dead_code))] + +//! T8142/G17G C0 J813 compute register program for the 25G76 native profile. +//! +//! The native SKSM payload has selector 3 and its register array begins at +//! +0x40. The 40-write program below is separately captured on M5; it is not +//! the G17P program with a new chip ID. Queue registration, descriptor-owned +//! pointers, shader/CDM construction and completion still belong to the M5 +//! runtime. Encoding these registers does not admit a Linux GPU job. + +pub(crate) const M5_COMPUTE_REGISTER_COUNT: usize = 40; +pub(crate) const M5_COMPUTE_REGISTER_BYTES: usize = 12 * M5_COMPUTE_REGISTER_COUNT; +/// Measured descriptor prefix, not a claim about the host allocation size. +pub(crate) const M5_COMPUTE_DESCRIPTOR_BYTES: usize = 0x1000; + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum M5ComputeError { + AddressOverflow, + BufferTooSmall, + CdmTerminatorBeforeStream, +} + +/// Retained objects and per-command state for the measured simple CL path. +/// Samplers, user timestamps, indirect dispatch and extra spill modes are not +/// part of this profile. Pointer ownership belongs to the runtime caller. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5ComputeDescriptor { + pub(crate) registers: M5ComputeParameters, + pub(crate) submit_sequence: u64, + /// Host descriptor +0x188, copied to native command +0x10. + pub(crate) scheduler_record: u64, + pub(crate) descriptor_low_alias: u64, + pub(crate) cdm_terminator: u64, + pub(crate) dispatch_stamps: [u64; 2], + pub(crate) event_machine_stamp: u32, + pub(crate) queue_id: u32, + pub(crate) queue_ordinal: u32, + pub(crate) has_event: bool, + pub(crate) submission_index: u32, + pub(crate) status: [u64; 2], + pub(crate) shared_control: u64, + pub(crate) shared_control_enabled: bool, + /// Sixteen bytes copied by the native host from the event machine's + /// +0x70 record. Their bit meanings are not all qualified; keep opaque. + pub(crate) event_metadata: [u8; 16], + pub(crate) zero_page: u64, + /// Host descriptor +0x148; not a fixed target constant. + pub(crate) owner_id: u8, + /// Full host descriptor +0x140. Register context packing uses only its + /// low byte; the descriptor copy at +0xf70 must retain all 32 bits. + pub(crate) descriptor_work_ordinal: u32, +} + +/// Encode all 4096 bytes of the native simple-compute descriptor prefix. +/// The register arrays and their aliases are generated from owned inputs. +/// This function performs no allocation, cache operation or publication. +pub(crate) fn encode_m5_compute_descriptor( + p: M5ComputeDescriptor, + raw: &mut [u8], +) -> Result<(), M5ComputeError> { + if raw.len() < M5_COMPUTE_DESCRIPTOR_BYTES { + return Err(M5ComputeError::BufferTooSmall); + } + if p.cdm_terminator < p.registers.cdm_base { + return Err(M5ComputeError::CdmTerminatorBeforeStream); + } + let registers = build_m5_compute_registers(p.registers)?; + let primary_alias = add(p.descriptor_low_alias, 0x40)?; + let secondary_alias = add(p.descriptor_low_alias, 0x760)?; + let secondary = [ + (0x10099u32, add(p.registers.operand_state_base, 5)?), + (0x10091, add(p.registers.operand_state_base, 0xf000)?), + (0x0a5c1, add(p.registers.operand_state_base, 0xf405)?), + (0x0a5c9, add(p.registers.operand_state_base, 0x1e400)?), + ]; + let raw = &mut raw[..M5_COMPUTE_DESCRIPTOR_BYTES]; + raw.fill(0); + for (offset, value) in [ + (0x00, 3u32), (0x0c, u32::from(p.registers.context_id)), + (0x748, 0x01e0_0028), (0xe68, 0x0030_0004), + (0xf20, (p.registers.dispatch_identity >> 32) as u32), + (0xf28, u32::MAX), (0xf50, p.event_machine_stamp), + (0xf54, p.queue_id), (0xf58, p.queue_ordinal), + (0xf5c, u32::from(p.has_event)), (0xf60, p.submission_index), + (0xf70, p.descriptor_work_ordinal), + ] { + raw[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + for (offset, value) in [ + (4, p.submit_sequence), (0x10, p.scheduler_record), + (0x740, primary_alias), (0xe60, secondary_alias), + (0xed8, p.registers.preempt_base), (0xee0, p.cdm_terminator), + (0xf08, 0x0000_0001_5402_4201), + (0xf40, p.dispatch_stamps[0]), (0xf48, p.dispatch_stamps[1]), + (0xf68, p.registers.dispatch_identity & 0xffff_ffff), + (0xf7c, p.status[0]), (0xf84, p.status[1]), + (0xfb2, p.shared_control), (0xfcb, p.zero_page), + ] { + raw[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); + } + for (index, count) in [37u16, 39, 39, 40].into_iter().enumerate() { + raw[0x18 + index * 2..0x1a + index * 2].copy_from_slice(&count.to_le_bytes()); + } + for (index, register) in registers.into_iter().enumerate() { + let offset = 0x40 + index * 12; + raw[offset..offset + 4].copy_from_slice(®ister.number.to_le_bytes()); + raw[offset + 4..offset + 12].copy_from_slice(®ister.value.to_le_bytes()); + } + for (index, (number, value)) in secondary.into_iter().enumerate() { + let offset = 0x760 + index * 12; + raw[offset..offset + 4].copy_from_slice(&number.to_le_bytes()); + raw[offset + 4..offset + 12].copy_from_slice(&value.to_le_bytes()); + } + raw[0xfba] = u8::from(p.shared_control_enabled); + raw[0xfbb..0xfcb].copy_from_slice(&p.event_metadata); + raw[0xfd3] = p.owner_id; + Ok(()) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5ComputeRegister { + pub(crate) number: u32, + pub(crate) value: u64, +} + +impl M5ComputeRegister { + const fn new(number: u32, value: u64) -> Self { + Self { number, value } + } +} + +/// Command-owned addresses and identities; the runtime must retain their +/// backing and validate its mappings before publishing the complete command. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5ComputeParameters { + pub(crate) preempt_base: u64, + pub(crate) cdm_base: u64, + pub(crate) dispatch_identity: u64, + pub(crate) context_id: u8, + pub(crate) work_ordinal: u8, + pub(crate) robustness: u64, + pub(crate) operand_state_base: u64, + /// Owned UMA pool slot, copied from native host descriptor +0x788 by + /// 25G76 generateRegisterList at 0x89e38dc..0x89e391c. This must match + /// shared-control +8 and the populated hardware UMA descriptor slot. + pub(crate) private_pool_hw_id: u64, + /// Native command descriptor +0x530, copied to register 0xd4a1. + pub(crate) descriptor_control_530: u64, + /// Descriptor +0x538; zero selects the native 0x60 default. The native + /// encoder shifts the selected value left 32 bits, discarding high bits. + pub(crate) descriptor_control_538: u64, + /// Native descriptor +0x60a/+0x60b bit 0. Their broader semantics are + /// still under investigation; neither is a fixed M5 device property. + pub(crate) descriptor_flag_60a: bool, + pub(crate) descriptor_flag_60b: bool, +} + +fn add(base: u64, offset: u64) -> Result { + base.checked_add(offset) + .ok_or(M5ComputeError::AddressOverflow) +} + +/// Encode the measured J813 profile, including its M5 control words and +/// enlarged operand-state offsets. Other G17G configurations are not implied. +pub(crate) fn build_m5_compute_registers( + p: M5ComputeParameters, +) -> Result<[M5ComputeRegister; M5_COMPUTE_REGISTER_COUNT], M5ComputeError> { + let context = ((p.context_id as u64) << 8) | p.work_ordinal as u64; + // 25G76 generateRegisterList +0x5d4..0x670. The final 0xa599 write + // restores 0x60 irrespective of the command-specific initial value. + let control_538 = if p.descriptor_control_538 == 0 { + 0x60 + } else { + p.descriptor_control_538 + }; + // 25G76 +0x644..0x66c; additional device-dependent bits used by other + // profiles are outside this measured J813 configuration. + let mode = if p.descriptor_flag_60a { + 0x14c0_8a60 + } else { + 0x10c0_8860 + } | if p.descriptor_flag_60b { 0x80 } else { 0 }; + Ok([ + M5ComputeRegister::new(0x1a510, p.preempt_base), + M5ComputeRegister::new(0x1a420, p.cdm_base), + M5ComputeRegister::new(0x1a4d0, add(p.preempt_base, 0x1480)?), + M5ComputeRegister::new(0x1a4d8, add(p.preempt_base, 0x1488)?), + M5ComputeRegister::new(0x1a4e0, add(p.preempt_base, 0x1490)?), + M5ComputeRegister::new(0x1a4e8, add(p.preempt_base, 0x1498)?), + M5ComputeRegister::new(0x1a440, 0x0000_0001_5402_4201), + M5ComputeRegister::new(0x0d4a1, p.descriptor_control_530), + M5ComputeRegister::new(0x0d411, 0x0000_0002_0000_0001), + M5ComputeRegister::new(0x0a599, (control_538 << 32) | 0x0040_0020), + M5ComputeRegister::new(0x1a458, mode), + M5ComputeRegister::new(0x101d9, 0x1c), + M5ComputeRegister::new(0x1a089, 0), + M5ComputeRegister::new(0x1a091, 0), + M5ComputeRegister::new(0x1a059, 0), + M5ComputeRegister::new(0x1a061, 0), + M5ComputeRegister::new(0x1a0b9, 0), + M5ComputeRegister::new(0x1a0c1, 0), + M5ComputeRegister::new(0x101d1, 0), + M5ComputeRegister::new(0x0d479, 0), + M5ComputeRegister::new(0x1a0e9, 8), + M5ComputeRegister::new(0x1a141, 0), + M5ComputeRegister::new(0x107a1, 0xff_0000), + M5ComputeRegister::new(0x1a540, p.dispatch_identity), + M5ComputeRegister::new(0x014a9, p.dispatch_identity), + M5ComputeRegister::new(0x0a351, p.dispatch_identity), + M5ComputeRegister::new(0x0a731, 0), + M5ComputeRegister::new(0x10201, context), + M5ComputeRegister::new(0x10428, context), + M5ComputeRegister::new(0x14028, p.private_pool_hw_id), + M5ComputeRegister::new(0x14070, p.robustness | 1), + M5ComputeRegister::new(0x10229, add(p.operand_state_base, 0x1e800)?), + M5ComputeRegister::new(0x140a8, add(p.operand_state_base, 0x1f000)?), + M5ComputeRegister::new(0x10099, add(p.operand_state_base, 0x0f405)?), + M5ComputeRegister::new(0x10091, add(p.operand_state_base, 0x1e400)?), + M5ComputeRegister::new(0x0a5c1, add(p.operand_state_base, 0x00005)?), + M5ComputeRegister::new(0x0a5c9, add(p.operand_state_base, 0x0f000)?), + M5ComputeRegister::new(0x0a731, 0), + M5ComputeRegister::new(0x1a440, 0x0000_0001_5402_4209), + M5ComputeRegister::new(0x0a599, 0x0000_0060_0040_0020), + ]) +} + +/// Write only the register array. No descriptor header or publication state +/// is manufactured here, and an invalid request leaves the destination alone. +pub(crate) fn encode_m5_compute_registers( + p: M5ComputeParameters, + bytes: &mut [u8], +) -> Result<(), M5ComputeError> { + if bytes.len() < M5_COMPUTE_REGISTER_BYTES { + return Err(M5ComputeError::BufferTooSmall); + } + let registers = build_m5_compute_registers(p)?; + for (index, register) in registers.iter().enumerate() { + let offset = index * 12; + bytes[offset..offset + 4].copy_from_slice(®ister.number.to_le_bytes()); + bytes[offset + 4..offset + 12].copy_from_slice(®ister.value.to_le_bytes()); + } + Ok(()) +} + diff --git a/drivers/gpu/drm/asahi/m5/drm.rs b/drivers/gpu/drm/asahi/m5/drm.rs new file mode 100644 index 0000000000000..a2a7b9d2679ac --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/drm.rs @@ -0,0 +1,386 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Experimental M5 DRM adapter using the retained M5 firmware session. +//! First-job admission is deliberately separate from general Mesa support. + +use core::{any::Any, ops::Range}; +use kernel::{bindings, c_str, device, macros::vtable, new_mutex, prelude::*, static_lock_class, + dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, + sync::{Arc, Mutex}, uapi, xarray}; +use crate::{alloc, driver::AsahiRegData, file, m5::live_boot::M5Runtime, + m5::resources::M5FirmwareMemory, m5::command, gem, gpu, hw, m5::vm_layout, mmu, queue}; + +pub(crate) type SharedM5Runtime = Arc>; +const USER_END: u64 = (1 << 42) - 2 * mmu::UAT_PGSZ as u64; + +/// Bytes of CDM control stream the witnessed M5 compute profile covers. The +/// captured stream (compute_program::STREAM) is twelve words: one dispatch +/// and the terminator at +44. Nothing longer has native evidence, and a +/// longer one is what a geometry-shader prepass submits. +const M5_COMPUTE_STREAM_BYTES: u64 = 48; +static QUEUE_NAME: &CStr = c_str!("m5_queue"); +static QUEUE_CLASS_KEY: Pin<&'static kernel::sync::LockClassKey> = static_lock_class!(); + +#[cfg(CONFIG_APPLE_CLPC)] +extern "C" { + fn apple_clpc_gpu_get(dev: *mut core::ffi::c_void, out: *mut *mut core::ffi::c_void) + -> core::ffi::c_int; + fn apple_clpc_gpu_set_active(gpu: *mut core::ffi::c_void, active: bool); + fn apple_clpc_gpu_put(gpu: *mut core::ffi::c_void); +} + +/// The CLPC's GPU input (`apple,clpc` on the GPU node). While the PMP runs, +/// its vote leaves the DRAM controller and the fabric at their lowest states; +/// the CLPC holds them at the top of its maps while M5 work is in flight, +/// and releases them its hold time after the last of it retires. Without a +/// CLPC the GPU runs as before, only slower under the PMP. +#[pin_data(PinnedDrop)] +pub(crate) struct M5ClpcInput { + gpu: *mut core::ffi::c_void, + /// Submissions in flight; the input is active while it is not zero. + #[pin] + in_flight: Mutex, +} + +// SAFETY: the CLPC serializes its input under its own lock, and the counter +// is only changed under `in_flight`. +unsafe impl Send for M5ClpcInput {} +// SAFETY: as above; shared use never changes the reference itself. +unsafe impl Sync for M5ClpcInput {} + +impl M5ClpcInput { + /// Takes the input before the firmware session starts, so that a CLPC + /// which has not probed yet defers the GPU without stranding a session. + pub(crate) fn new(dev: &device::Device) -> Result> { + #[allow(unused_mut)] + let mut gpu: *mut core::ffi::c_void = core::ptr::null_mut(); + #[cfg(CONFIG_APPLE_CLPC)] + { + // SAFETY: a live device and a writable result; C returns a + // reference, or NULL when the node names no CLPC. + let ret = unsafe { apple_clpc_gpu_get(dev.as_raw().cast(), &mut gpu) }; + if ret == EPROBE_DEFER.to_errno() { + return Err(EPROBE_DEFER); + } + if ret < 0 { + dev_warn!(dev, "no CLPC input ({}): GPU work gets no memory floor\n", ret); + gpu = core::ptr::null_mut(); + } + } + #[cfg(not(CONFIG_APPLE_CLPC))] + let _ = dev; + Arc::pin_init(pin_init!(Self { gpu, in_flight <- new_mutex!(0) }), GFP_KERNEL) + } + + fn set_active(&self, _active: bool) { + #[cfg(CONFIG_APPLE_CLPC)] + // SAFETY: NULL is accepted; a non-NULL reference is held until drop. + unsafe { apple_clpc_gpu_set_active(self.gpu, _active) }; + } + + /// Marks one submission in flight until the returned guard drops. + fn busy(&self) -> M5ClpcBusy<'_> { + let mut count = self.in_flight.lock(); + *count += 1; + if *count == 1 { + self.set_active(true); + } + M5ClpcBusy(self) + } +} + +#[pinned_drop] +impl PinnedDrop for M5ClpcInput { + fn drop(self: Pin<&mut Self>) { + #[cfg(CONFIG_APPLE_CLPC)] + // SAFETY: releases exactly the reference taken in new(), clearing the + // input first; NULL is accepted. + unsafe { apple_clpc_gpu_put(self.gpu) }; + } +} + +struct M5ClpcBusy<'a>(&'a M5ClpcInput); + +impl Drop for M5ClpcBusy<'_> { + fn drop(&mut self) { + let mut count = self.0.in_flight.lock(); + *count -= 1; + if *count == 0 { + self.0.set_active(false); + } + } +} + +pub(crate) struct M5DrmGpu { + // A strong reference prevents open DRM files from outliving the session. + runtime: SharedM5Runtime, + id: crate::regs::G17Id, + ids: gpu::SequenceIDs, + clpc: Arc, +} + +impl M5DrmGpu { + pub(crate) fn new(runtime: SharedM5Runtime, id: crate::regs::G17Id, + clpc: Arc) -> Self { + Self { runtime, id, ids: Default::default(), clpc } + } +} + +impl gpu::Gpu for M5DrmGpu { + fn stats_snapshot(&self) -> Option> { None } + fn as_any(&self) -> &dyn 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.is_crashed() { Err(ENODEV) } else { Ok(()) } + } + fn ids(&self) -> &gpu::SequenceIDs { &self.ids } + fn is_crashed(&self) -> bool { self.runtime.lock().is_crashed() } + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { + params.gpu_generation = hw::GpuGen::G17 as u32; + params.gpu_variant = hw::GpuVariant::G as u32; + params.gpu_revision = self.id.gpu_rev as u32; + params.chip_id = 0x8142; + params.num_dies = self.id.num_dies; + params.num_clusters_total = self.id.num_clusters; + params.num_cores_per_cluster = self.id.num_cores; + for (i, mask) in self.id.core_masks.iter().enumerate() { + *params.core_masks.get_mut(i).ok_or(EIO)? = (*mask).into(); + } + // Dynamic M5 clock policy is not implemented. + params.max_frequency_khz = 0; + params.usc_generation = 3; + params.gpu_hal_generation = 300; + // One hardware command per submission. + params.max_commands_per_submission = 1; + Ok(()) + } + fn supports_vm_status(&self) -> bool { true } + /// VM_BIND defers unmaps while accepted work runs, and a submission installs its fence + /// in every output sync, also on failure. + fn tracked_submission(&self) -> bool { true } + fn user_range(&self) -> Range { mmu::UAT_PGSZ as u64..USER_END } + fn base_clock_hz(&self) -> u32 { 24_000_000 } + fn uat_geometry(&self) -> mmu::UatGeometry { mmu::UatGeometry { ias: 42, oas: 42 } } + fn new_vm(&self, kernel_range: Range) -> Result { + self.runtime.lock().new_user_vm(self.ids.vm.next(), kernel_range) + } + fn new_queue(&self, vm: mmu::Vm, + _ualloc: Arc>, + _ualloc_priv: Arc>, + priority: u32, usc_exec_base: u64) -> Result> { + if priority > 3 { return Err(EINVAL); } + let window = command::QueueUscWindow { + base: usc_exec_base, user_start: vm_layout::DRIVER_BASE, user_end: USER_END, + }; + window.validate().map_err(|_| EINVAL)?; + let queue = M5Queue { + runtime: self.runtime.clone(), vm, window, + fences: FenceContexts::new(1, QUEUE_NAME, QUEUE_CLASS_KEY)?, + clpc: self.clpc.clone(), + }; + Ok(KBox::new(queue, GFP_KERNEL)?) + } + fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) + -> Result { Err(ENOTSUPP) } +} + +struct M5SubmissionFence; +#[vtable] +impl FenceOps for M5SubmissionFence { + fn get_driver_name<'a>(self: &'a FenceObject) -> &'a CStr { c_str!("asahi") } + fn get_timeline_name<'a>(self: &'a FenceObject) -> &'a CStr { c_str!("m5-submit") } +} + +/// Keep the original sync vector: creating a second output list would add an +/// allocation failure after userspace has already supplied its wait targets. +struct OutputPublication { + fence: UserFence, + syncs: KVec, + input_count: usize, + result: Result, +} + +impl Drop for OutputPublication { + fn drop(&mut self) { + if let Err(error) = self.result { self.fence.set_error(error); } + let fence = Fence::from_fence(&self.fence); + for mut sync in self.syncs.drain(self.input_count..) { + if let Some(chain) = sync.chain_fence.take() { + sync.syncobj.add_point(chain, &fence, sync.timeline_value); + } else { sync.syncobj.replace_fence(Some(&fence)); } + } + self.fence.signal(); + } +} + +struct UserAddressSpace<'a> { vm: &'a mmu::Vm } +impl command::GpuAddressSpace for UserAddressSpace<'_> { + fn covers(&self, address: u64, size: u64, access: command::GpuAccess) -> bool { + let (read, write) = match access { + command::GpuAccess::Read => (true, false), + command::GpuAccess::Write => (false, true), + command::GpuAccess::ReadWrite => (true, true), + }; + vm_layout::user_range_contains(&self.vm.kernel_range(), address, size, USER_END) + && self.vm.covers_range(address, size, read, write) + } +} + +struct M5Queue { + runtime: SharedM5Runtime, + vm: mmu::Vm, + window: command::QueueUscWindow, + fences: FenceContexts, + clpc: Arc, +} + +impl queue::Queue for M5Queue { + fn submit(&mut self, _reg_data: &AsahiRegData<'_>, _submission_id: u64, + syncs: KVec, + in_sync_count: usize, cmdbuf_raw: &[u8], + _objects: Pin<&xarray::XArray>>) -> Result { + if in_sync_count > syncs.len() { return Err(EINVAL); } + let fence = self.fences.new_fence(0, M5SubmissionFence)?.into(); + let mut publication = OutputPublication { + fence, syncs, input_count: in_sync_count, result: Err(ECANCELED), + }; + let result = (|| { + if self.vm.status().is_some_and(|status| status.get() != 0) { return Err(EIO); } + // Wait outside the runtime lock; another client may own the job + // whose fence satisfies this submission's dependency. + for sync in &publication.syncs[..in_sync_count] { + if let Some(fence) = &sync.fence { + // SAFETY: both calls borrow the strongly held input fence. + let waited = unsafe { bindings::dma_fence_wait_timeout( + fence.raw(), true, kernel::task::MAX_SCHEDULE_TIMEOUT) }; + if waited < 0 { return Err(Error::from_errno(waited as i32)); } + if waited == 0 { return Err(ETIMEDOUT); } + let status = unsafe { bindings::dma_fence_get_status(fence.raw()) }; + if status < 0 { return Err(Error::from_errno(status)); } + } + } + let _vm_job = self.vm.retain_job()?; + let address_space = UserAddressSpace { vm: &self.vm }; + let mut parser = command::UapiCommandParser::new(cmdbuf_raw); + let command = parser.next_hardware().map_err(|_| EINVAL)?.ok_or(EINVAL)?; + if parser.next_hardware().map_err(|_| EINVAL)?.is_some() { + pr_err!("M5 submit admission rejected: more than one hardware command\n"); + return Err(ENOTSUPP); + } + parser.finish().map_err(|_| EINVAL)?; + if let command::ParsedHardwareCommand::Compute { payload, attachments, .. } = command { + let timestamps = [payload.timestamps.start, payload.timestamps.end]; + if payload.flags != 0 || payload.sampler_heap != 0 || payload.sampler_count != 0 + || timestamps.iter().any(|t| t.handle != 0 || t.offset != 0) { + pr_err!("M5 compute admission rejected flags={:#x} sampler_heap={:#x} samplers={} timestamps={}\n", + payload.flags, payload.sampler_heap, payload.sampler_count, + timestamps.iter().any(|t| t.handle != 0 || t.offset != 0)); + return Err(ENOTSUPP); + } + // The witnessed M5 compute profile is one dispatch: the + // captured control stream is twelve words, a single dispatch + // followed by the terminator at +44, and the descriptor + // carries exactly one dispatch identity, one submission index + // and one pair of dispatch stamps. A longer stream -- every + // geometry-shader and transform-feedback prepass emits four or + // five dispatches -- is accepted by firmware, linked into the + // job list and never retired, so the submitting ioctl times + // out after forty seconds and quarantines the VM. Refuse it + // here instead: the client drops the batch and the session + // survives, exactly as it does for an out-of-profile render. + let stream_bytes = payload.control_stream_end + .saturating_sub(payload.control_stream_base); + if stream_bytes > M5_COMPUTE_STREAM_BYTES { + pr_err!("M5 compute admission rejected stream_bytes={} (profile admits one dispatch, {})\n", + stream_bytes, M5_COMPUTE_STREAM_BYTES); + return Err(ENOTSUPP); + } + let translated = command::translate_compute_command(payload, attachments, + self.window, &address_space).map_err(|_| EINVAL)?; + let _busy = self.clpc.busy(); + return self.runtime.lock().submit_application_compute(&self.vm, &translated); + } + let command::ParsedHardwareCommand::Render { + payload, vertex_attachments, fragment_attachments, .. + } = command else { + pr_err!("M5 submit admission rejected: neither a render nor a compute command\n"); + return Err(ENOTSUPP); + }; + admit_reference_render(&payload).map_err(|error| { + pr_err!("M5 render admission rejected size={}x{} layers={} utiles={}x{} samples={}\n", + payload.width, payload.height, payload.layers, + payload.utile_width, payload.utile_height, payload.samples); + error + })?; + // An attached stencil plane is admitted only while it is inert: + // its buffers are range-checked with the depth ones and its + // registers are written from the same parameter block, but a + // render that loads or stores it, or that runs the stencil unit, + // is outside the witnessed profile. + if payload.zls_control & 0x44000 != 0 { + pr_err!("M5 render admission rejected stencil transfer control={:#x}\n", + payload.zls_control); + return Err(ENOTSUPP); + } + command::validate_m5_reference_depth(&payload, &address_space) + .map_err(|error| { + pr_err!("M5 depth admission rejected {:?}: size={}x{} dimensions={:#x} control={:#x} stride={:#x} meta_stride={:#x} base={:#x} meta={:#x} clear={:#x}\n", + error, payload.width, payload.height, payload.depth_dimensions, + payload.zls_control, payload.depth.stride, payload.depth.compression_stride, + payload.depth.base, payload.depth.compression_base, payload.depth_clear); + ENOTSUPP + })?; + let (parameters, mut controls) = M5FirmwareMemory::reference_render_profile(); + let mut translated = command::translate_render_command(payload, + vertex_attachments, fragment_attachments, self.window, &address_space, + command::RenderInternalState { parameters }).map_err(|_| EINVAL)?; + // Native single-layer M5 ZLS does not encode an array stride. + // The full data/metadata ranges were validated above. + translated.parameters.depth_stride = 0; + translated.parameters.depth_aux_stride = 0; + // Native 25G76 indexed draws use 15021=0x10c000. The reference + // triangle's low bit causes fragment recovery with larger + // indexed overdraw, even after the tiling stage completes. + // Bit18 selects the narrow depth plane: the same controlled + // render against a Depth16Unorm attachment publishes 0x14c001 + // where the 32-bit one publishes 0x10c001, and that bit is the + // only difference in the whole register program beyond the ZLS + // format field and the integer clear value. + let z16 = payload.zls_control & (3 << 25) == (2 << 25); + translated.parameters.aux_fb_flags = + if z16 { 0x14c000 } else { 0x10c000 }; + // M5's second store-program pair refers to the same EOT program + // in the admitted native profile, with caller-owned program VAs. + controls.store_pipeline_2 = translated.parameters.store_pipeline; + controls.store_pipeline_2_bind = translated.parameters.store_pipeline_bind; + controls.partial_store_pipeline_2 = translated.parameters.partial_store_pipeline; + controls.partial_store_pipeline_2_bind = translated.parameters.partial_store_pipeline_bind; + let _busy = self.clpc.busy(); + self.runtime.lock().submit_application(&self.vm, translated.parameters, + controls, 1, [0x7d4000, 0x934000])?; + Ok(()) + })(); + // The runtime records and quarantines a failed published VM before + // this output fence is installed/signalled by the publication guard. + publication.result = result; + result + } +} + +/// Until the M5 controls are derived for other render modes, admit only the +/// reference render-state envelope. This is an experimental first-job ABI +/// path, not an assertion that arbitrary Vulkan programs are supported. +fn admit_reference_render(command: &command::UapiRenderCommand) -> Result { + let timestamps = [command.vertex_timestamps.start, command.vertex_timestamps.end, + command.fragment_timestamps.start, command.fragment_timestamps.end]; + if !(1..=command::M5_MAX_RENDER_DIMENSION).contains(&u32::from(command.width)) + || !(1..=command::M5_MAX_RENDER_DIMENSION).contains(&u32::from(command.height)) + || command.layers != 1 + || command.utile_width != 32 || command.utile_height != 32 || command.samples != 1 + || command.sampler_heap != 0 || command.sampler_count != 0 + || command.occlusion_query_base != 0 + || timestamps.iter().any(|timestamp| timestamp.handle != 0 || timestamp.offset != 0) { + return Err(ENOTSUPP); + } + Ok(()) +} diff --git a/drivers/gpu/drm/asahi/m5/fw_msg.rs b/drivers/gpu/drm/asahi/m5/fw_msg.rs new file mode 100644 index 0000000000000..368ed4cc36f34 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/fw_msg.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +const INITDATA_TAG: u64 = 0x0081_0000_0000_0000; + +const INITDATA_ADDRESS_MASK: u64 = 0x0000_0fff_ffff_ffff; + +const INITDATA_ADDRESS_PREFIX: u64 = 0xffff_f000_0000_0000; + +/// `AGXArmFirmware::powerTransitionEnd(AGFIFirmwareRole, bool)` closes the GPU +/// power-on transition by sending this note to EACH firmware role. +/// +/// KEXT_PROVEN, 25G83 @0xfffffe00088936a4. Both send sites are identical: +/// +/// ldr x0, [x19, #6616] / [x19, #6672] ; the two role objects +/// ldr x8, [obj + 0x8a8] ; sendAsyncNoteToFirmware +/// mov x1, #0x89000000000000 ; tag 0x89, payload 0 +/// mov w2, #0x1 ; gated=true +/// blraa x8, x16 +/// +/// MEASURED on hardware (m1n1 hv capture 20260904-001852Z): it is the LAST +/// EP-0x21 message of bring-up, sent once per role right after the initdata +/// handshake completes and 11.4 seconds before the first work doorbell: +/// +/// 57.95ms role0 -> ep=0x21 0x0089000000000000 +/// 59.31ms role1 -> ep=0x21 0x0089000000000000 +/// ... +/// 11425.12ms role0 -> ep=0x21 0x0083000000000000 <- first doorbell +/// +/// This driver has never sent it. Its EP-0x21 vocabulary was 0x81 initdata, +/// 0x83 doorbell, 0x84 device control and 0x86 recovery inspection only. +const POWER_TRANSITION_END_TAG: u64 = 0x0089_0000_0000_0000; + +/// Encode the role's power-transition-end note. The payload is zero in every +/// captured instance and the kext materialises the bare tag with a single +/// `movz x1, #0x89, lsl #48`. +pub(crate) const fn encode_power_transition_end() -> u64 { + POWER_TRANSITION_END_TAG +} + +/// Refusals made by the evidence-backed codec. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum WireError { + AddressOutOfRange, +} + +/// Encode the G17 init-data handoff exactly as the recovered host does. +/// +/// The host instruction truncates to 44 bits. Linux instead rejects an +/// address unless it is already in low-44-bit or firmware-canonical form. +pub(crate) const fn encode_initdata_doorbell(firmware_va: u64) -> Result { + let high = firmware_va & !INITDATA_ADDRESS_MASK; + if high != 0 && high != INITDATA_ADDRESS_PREFIX { + return Err(WireError::AddressOutOfRange); + } + + Ok(INITDATA_TAG | (firmware_va & INITDATA_ADDRESS_MASK)) +} diff --git a/drivers/gpu/drm/asahi/m5/initdata.rs b/drivers/gpu/drm/asahi/m5/initdata.rs new file mode 100644 index 0000000000000..f2ad6afea017f --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/initdata.rs @@ -0,0 +1,1630 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +use core::result::Result; + +/// Root size for the primary (`gfx-asc`) instance. +pub(crate) const ROOT_SIZE_PRIMARY: usize = 0x0b8; + +/// Root size for the secondary (`gfx1-asc`) instance; the extra 0x10 bytes are +/// the two secondary-only pointers at `+0xb8`/`+0xc0`. +pub(crate) const ROOT_SIZE_SECONDARY: usize = 0x0c8; + +pub(crate) const MAIN_CONFIG_SIZE: usize = 0x600; + +pub(crate) const REGION_A_SIZE: usize = 0x4000; + +pub(crate) const REGION_C_SIZE: usize = 0x1000; + +pub(crate) const STATUS_BLOCK_SIZE: usize = 0x80; + +pub(crate) const HW_DATA_BUNDLE_MIN_ALLOC: usize = 0x10000; + +/// The native placement additionally hosts the twelve work rings and both main +/// configuration objects inside the same cluster, which then spans this much +/// (see [`WORK_RING_BUNDLE_OFFSETS`], [`NATIVE_PRIMARY_MAIN_BUNDLE_OFFSET`]). +pub(crate) const NATIVE_SHARED_CLUSTER_SIZE: usize = 0x28000; + +/// The same tuple as the little-endian u64 the firmware compares in one go. +pub(crate) const INITDATA_VERSION_WORD: u64 = 0x0c8a_a322_0396_04c0; + +/// Target/build-specific root encoding. This is a serialization choice, not +/// permission to start firmware or reuse the other target's hardware tables. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum RootProfile { + J700G17P, + /// J813 Mac17,3 / 25G76, RTKit-3255.160.4.release. Both roots were captured + /// before INBOX1 publication. Independently confirmed by the loaded GFX + /// version comparison at +0x1fa5c and GFX1 at +0x21140. + J813G17G25G76, + /// J873 Mac18,5 / T8152 / G18G / 26A428, RTKit_release-3514.0.15 + /// (armfw_g18g-b000 on GFX, armfw1_g18g-b010 on GFX1). No capture of a + /// native root exists; the encoding is source-constructed from the 26A428 + /// kext and firmware (see the "J873 / G18G" section below). Selecting it + /// changes nothing for the other two profiles. + J873G18G26A428, +} + +impl RootProfile { + pub(crate) const fn version_word(self) -> u64 { + match self { + Self::J700G17P => INITDATA_VERSION_WORD, + Self::J813G17G25G76 => 0x0c8a_a322_039e_04c0, + Self::J873G18G26A428 => G18G_26A428_INITDATA_VERSION_WORD, + } + } + + /// Bytes of the root object for `role`. J700/J813 keep the historical + /// 0xb8/0xc8 split. G18G sizes both roots to 0xc8 because both firmware + /// images copy 0xc8 bytes from each root (FW_PROVEN b000 0x21664-0x216a8). + pub(crate) const fn root_size(self, role: InstanceRole) -> usize { + match self { + Self::J873G18G26A428 => G18G_26A428_ROOT_SIZE, + Self::J700G17P | Self::J813G17G25G76 => root_size(role), + } + } + + /// Opcode of the one opening device-control record staged at main + /// `+0x4c0`. G18G renumbered the opening handler: 0x16 is now an + /// unrelated handler and 0x15 reaches the opening (FW_PROVEN jump table + /// 0xfffffc0000006c60, handler b000 0x3ed0). The secondary keeps 0x2a. + pub(crate) const fn control_opening_opcode(self, role: InstanceRole) -> u32 { + match (self, role) { + (Self::J873G18G26A428, InstanceRole::Primary) => { + G18G_26A428_CONTROL_OPENING_OPCODE_PRIMARY + } + (Self::J873G18G26A428, InstanceRole::Secondary) => { + G18G_26A428_CONTROL_OPENING_OPCODE_SECONDARY + } + (_, InstanceRole::Primary) => CONTROL_OPENING_OPCODE_PRIMARY, + (_, InstanceRole::Secondary) => CONTROL_OPENING_OPCODE_SECONDARY, + } + } + + /// Bundle offsets of the five views published at main `+0x254`. + pub(crate) const fn bundle_view_offsets(self) -> [usize; 5] { + match self { + Self::J873G18G26A428 => G18G_26A428_BUNDLE_VIEW_OFFSETS, + Self::J700G17P | Self::J813G17G25G76 => BUNDLE_VIEW_OFFSETS, + } + } + + /// Extents each view must fit inside the bundle allocation. + pub(crate) const fn bundle_view_extents(self) -> [usize; 5] { + match self { + Self::J873G18G26A428 => G18G_26A428_BUNDLE_VIEW_EXTENTS, + Self::J700G17P | Self::J813G17G25G76 => BUNDLE_VIEW_EXTENTS, + } + } + + /// Bundle offset named twice by main `+0x08`/`+0x10` (the empty BRN + /// table and the 0x88 block, which the allocator places together). + pub(crate) const fn repeated_region_bundle_offset(self) -> usize { + match self { + Self::J873G18G26A428 => G18G_26A428_SHARED_LAYOUT.block_88, + Self::J700G17P | Self::J813G17G25G76 => MAIN_REPEATED_REGION_BUNDLE_OFFSET, + } + } + +} + +const INITDATA_ADDR_MASK: u64 = 0x0000_0fff_ffff_ffff; + +const INITDATA_ADDR_PREFIX: u64 = 0xffff_f000_0000_0000; + +const ROOT_VERSION: usize = 0x00; + +const ROOT_REGION_A: usize = 0x08; + +const ROOT_MAIN_CONFIG: usize = 0x18; + +const ROOT_REGION_C: usize = 0x20; + +const ROOT_INSTANCE_KIND: usize = 0x28; + +const ROOT_CONSTANT_2C: usize = 0x2c; + +const ROOT_PAGE_SIZE: usize = 0x30; + +const ROOT_PAGE_BITS: usize = 0x32; + +const ROOT_LEVEL_COUNT: usize = 0x33; + +const ROOT_LEVELS: usize = 0x34; + +/// Root `+0xa8`: Status A pointer. (The M5-derived model misused this slot as +/// a role pointer.) +const ROOT_STATUS_A: usize = 0xa8; + +/// Root `+0xb0`: Status B pointer. Real for the primary, zero for the +/// secondary. (The M5-derived model misused it as a cross-role pointer.) +const ROOT_STATUS_B: usize = 0xb0; + +const ROOT_SECONDARY_EXTRA_0: usize = 0xb8; + +const ROOT_SECONDARY_EXTRA_1: usize = 0xc0; + +pub(crate) const UAT_PAGE_SIZE: u16 = 0x4000; + +pub(crate) const UAT_PAGE_BITS: u8 = 14; + +pub(crate) const UAT_LEVEL_COUNT: usize = 3; + +/// `(index_shift, entry_count)` for the three levels below the root, +/// confirmed against a live table walk. +pub(crate) const UAT_LEVELS: [(u8, u16); UAT_LEVEL_COUNT] = [(36, 64), (25, 2048), (14, 2048)]; + +pub(crate) const UAT_LEVEL_DESC_SIZE: usize = 0x20; + +/// Level descriptor `+0x10`: physical mask, identical in all three. +pub(crate) const UAT_LEVEL_PHYS_MASK: u64 = 0x0000_03ff_ffff_c000; + +const MAIN_HW_DATA: usize = 0x00; + +/// The same repeated-region address appears at `+0x08` and `+0x10`; it is the +/// bundle base plus [`MAIN_REPEATED_REGION_BUNDLE_OFFSET`], not the bundle +/// base itself. It reads zero at handoff (firmware writes into it), so the +/// host only has to provide it mapped. +const MAIN_REPEATED_0: usize = 0x08; + +const MAIN_REPEATED_1: usize = 0x10; + +pub(crate) const MAIN_REPEATED_REGION_BUNDLE_OFFSET: usize = 0xc500; + +const MAIN_CHANNEL_TABLE: usize = 0x20; + +/// Main `+0x254`: five unaligned u64 views into the hardware-data bundle. +const MAIN_BUNDLE_VIEWS: usize = 0x254; + +/// Main `+0x2d0`: six qwords of region views. +const MAIN_REGION_VIEWS: usize = 0x2d0; + +/// Main `+0x300`: u32 4, secondary only. +const MAIN_SECONDARY_KIND: usize = 0x300; + +const MAIN_SECONDARY_KIND_VALUE: u32 = 4; + +/// Main `+0x3e0`: u32 0xff, primary only. +const MAIN_PRIMARY_MASK: usize = 0x3e0; + +const MAIN_PRIMARY_MASK_VALUE: u32 = 0xff; + +const MAIN_PRIMARY_SCALAR_32C: usize = 0x32c; + +const MAIN_PRIMARY_SCALAR_344: usize = 0x344; + +/// Main `+0x471`: unaligned u64, secondary only, pointing *into* bundle view 2 +/// at [`SECONDARY_EXTRA_VIEW_OFFSET`] (not a fresh allocation — the M5-derived +/// model had this at `+0x481` backed by an invented 0x12688-byte buffer; both +/// were wrong). +const MAIN_SECONDARY_EXTRA_PTR: usize = 0x471; + +pub(crate) const SECONDARY_EXTRA_VIEW_INDEX: usize = 2; + +pub(crate) const SECONDARY_EXTRA_VIEW_OFFSET: usize = 0xe40; + +/// Main `+0x4c0` is both a scalar and a place: the leading u32 of the +/// device-control ring, which is embedded in the main configuration object at +/// exactly this offset on both instances. Writing the opening opcode here *is* +/// staging the opening device-control record (records are 0x40 bytes; fields +/// past the opcode are zero). The control channel's producer counter must then +/// be set to the role-specific value returned by +/// [`control_opening_producer`] before the descriptor is handed over. +const MAIN_CONTROL_RING: usize = 0x4c0; + +pub(crate) const CONTROL_OPENING_OPCODE_PRIMARY: u32 = 0x16; + +pub(crate) const CONTROL_OPENING_OPCODE_SECONDARY: u32 = 0x2a; + +/// Bundle offsets of the five views named at main `+0x254`. They are views of +/// the common bundle, not independent objects: view 0 overlaps the tail of +/// the hardware-data object, and views 3 and 4 overlap each other by all but +/// 0x80 bytes. +pub(crate) const BUNDLE_VIEW_OFFSETS: [usize; 5] = [0x2740, 0x3380, 0x4400, 0xbc80, 0xbd00]; + +/// Logical extents of the five views. +pub(crate) const BUNDLE_VIEW_EXTENTS: [usize; 5] = [0x18c0, 0x0c80, 0x3c00, 0x3380, 0x3300]; + +/// The context-0 mappings of the PB descriptor and UMA page-pool descriptor +/// tables published at main `+0x2d8` and `+0x2e8`, respectively. The matching +/// firmware-high mappings are published at `+0x2e0` and `+0x2f0`. +pub(crate) const REGION_VIEW_LOW_ADDRS: [u64; 2] = [0x70_0183_8000, 0x70_0184_0000]; + +pub(crate) const CHANNEL_TABLE_ENTRIES: usize = 17; + +pub(crate) const CHANNEL_ENTRY_SIZE: usize = 0x20; + +/// Channel entry layout: three *separate* 32-bit state-counter addresses at +/// `+0x00`/`+0x08`/`+0x10` (the counters themselves sit at 0x10 spacing in +/// their state block — do not collapse them into one state object), then the +/// ring base at `+0x18`. +pub(crate) const CHANNEL_ENTRY_STATE_COUNT: usize = 3; + +pub(crate) const CHANNEL_STATE_SPACING: usize = 0x10; + +/// Entries 0..11 are ordered TA_0, 3D_0, CL_0, TA_1, ... CL_3. +pub(crate) const WORK_CHANNEL_COUNT: usize = 12; + +/// Entry 12 is device control. It continues the compact control-state grid +/// ([`WORK_STATE_GRID_OFFSETS`] has 13 entries, one more than there are work +/// channels), and its ring is embedded at main `+0x4c0`. The M5-derived model +/// refused this index, claiming a "cursor pair at +0x1a0/+0x1a8"; that was a +/// misread — those offsets are exactly this entry's state-counter addresses 0 +/// and 1. +pub(crate) const CONTROL_CHANNEL_INDEX: usize = 12; + +/// Entries 13 and 14 are report channels with split state objects: their +/// state addresses alias off status A rather than the compact grid, and the +/// firmware peer of each host-owned counter is at `+0x20` within its object. +pub(crate) const REPORT_CHANNEL_INDICES: [usize; 2] = [13, 14]; + +/// Entry 15 is partial: only its first state address, no ring. Entry 16 is +/// empty. Filling them like the rest declares channels that do not exist. +pub(crate) const PARTIAL_CHANNEL_INDEX: usize = 15; + +/// Offsets of the channel state blocks (channels 0..=12) inside the compact +/// state grid. Native state is *not* in channel-table order: within each +/// workload group the work queues sit at descending offsets, and the control +/// channel's block follows at `+0x300`. Preserving these address identities is +/// part of the descriptor ABI. +pub(crate) const WORK_STATE_GRID_OFFSETS: [usize; 13] = [ + 0x0c0, 0x1c0, 0x2c0, // TA_0, 3D_0, CL_0 + 0x080, 0x180, 0x280, // TA_1, 3D_1, CL_1 + 0x040, 0x140, 0x240, // TA_2, 3D_2, CL_2 + 0x000, 0x100, 0x200, // TA_3, 3D_3, CL_3 + 0x300, // device control +]; + +/// The primary status-B object runs from there to status A: `0xeb00` bytes. +pub(crate) const PRIMARY_STATUS_B_OBJECT_SIZE: usize = 0xeb00; + +/// State-counter addresses of report channels 13/14, as offsets from status A. +pub(crate) const REPORT_STATE_STATUS_A_OFFSETS: [[usize; 3]; 2] = + [[0x00040, 0x002c0, 0x00080], [0x00240, 0xa6ac0, 0x00280]]; + +/// Ring bases of report channels 13/14, as offsets from status A. +pub(crate) const REPORT_RING_STATUS_A_OFFSETS: [usize; 2] = [0x04ac0, 0xafac0]; + +/// Entry 15's sole state address, as an offset from status A. +pub(crate) const PARTIAL_STATE_STATUS_A_OFFSET: usize = 0x2d2c0; + +/// Native bundle offsets of the twelve work rings (0x1800 each), in +/// channel-table order. These extend past [`HW_DATA_BUNDLE_MIN_ALLOC`]; a host +/// using this placement sizes the cluster [`NATIVE_SHARED_CLUSTER_SIZE`]. +pub(crate) const WORK_RING_BUNDLE_OFFSETS: [usize; 12] = [ + 0x10dc0, 0x16dc0, 0x1cdc0, 0x0f5c0, 0x155c0, 0x1b5c0, 0x0ddc0, 0x13dc0, 0x19dc0, 0x0c5c0, + 0x125c0, 0x185c0, +]; + +/// Native bundle offsets of the two main configuration objects. +pub(crate) const NATIVE_PRIMARY_MAIN_BUNDLE_OFFSET: usize = 0x1e5c0; + +pub(crate) const NATIVE_SECONDARY_MAIN_BUNDLE_OFFSET: usize = 0x22a80; + +pub(crate) const HW_REGISTER_MAP_ENTRY_SIZE: usize = 0x28; + +pub(crate) const HW_REGISTER_MAP_SLOTS: usize = 53; + +/// Two GPU mappings of one present completion-queue backing. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct G17PKsmCompletionAliases { + pub(crate) low: u64, + pub(crate) high: u64, +} + +pub(crate) const M5_25G76_COMPLETION_QUEUE_COUNT: usize = 4; + +pub(crate) const M5_25G76_COMPLETION_BACKING_SIZE: usize = 0x800 * 0x40; + +/// M5 publishes all four descriptors at hardware-data +0x2614, with ordinals +/// 0,1,2,3. Each names low/high mappings of its own retained 128-KiB backing. +/// The two native pre-handoff captures agree on every descriptor byte. +/// Construction only: this does not allocate, map, publish, or poll a queue. +pub(crate) fn encode_m5_25g76_completion_table( + aliases: [G17PKsmCompletionAliases; M5_25G76_COMPLETION_QUEUE_COUNT], + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != M5_25G76_COMPLETION_QUEUE_COUNT * 0x20 { + return Err(InitdataError::BufferSize); + } + let extent = M5_25G76_COMPLETION_BACKING_SIZE as u64; + // Validate every range before mutating the output. Different queues must + // not alias each other in either address space. + for (i, alias) in aliases.iter().enumerate() { + for address in [alias.low, alias.high] { + required_address(address)?; + let end = address.checked_add(extent).ok_or(InitdataError::AddressOutOfRange)?; + required_address(end - 1)?; + } + for prior in &aliases[..i] { + if (alias.low < prior.low + extent && prior.low < alias.low + extent) + || (alias.high < prior.high + extent && prior.high < alias.high + extent) + { + return Err(InitdataError::PairAliasedObject); + } + } + } + out.fill(0); + for (ordinal, alias) in aliases.iter().enumerate() { + let offset = ordinal * 0x20; + put_u64(out, offset, alias.low); + put_u64(out, offset + 8, alias.high); + put_u32(out, offset + 0x10, 0x800); + put_u32(out, offset + 0x14, 0x40); + put_u32(out, offset + 0x18, ordinal as u32); + } + Ok(()) +} + +/// Status block `+0x04` holds u32 1 pre-init. `+0x10`/`+0x14` are *post-ack +/// firmware state* and must be zero at handoff. +pub(crate) const STATUS_BLOCK_ONE_OFFSET: usize = 0x04; + +pub(crate) const PRIMARY_STATUS_B_FWCTL_STATE: usize = 0x48e0; + +pub(crate) const PRIMARY_STATUS_B_FWCTL_RING: usize = 0x48e8; + +pub(crate) const PRIMARY_STATUS_B_CONFIG_HEADER: usize = 0xe434; + +pub(crate) const PRIMARY_STATUS_B_CONFIG_OFFSET: usize = 0xe440; + +/// The secondary root sits exactly this far above the primary root; the +/// secondary's initialisation message carries the primary's address plus this +/// delta in the same field, so the pair is not placed freely. +pub(crate) const SECONDARY_ROOT_DELTA: u64 = 0x8000; + +/// Physical firmware instance encoded at root `+0x28`. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u32)] +pub(crate) enum InstanceRole { + /// `gfx-asc`: scheduler, device control, and all work channels. + Primary = 0, + /// `gfx1-asc`: control-only peer. Linux starts it after primary RTKit is ready. + Secondary = 1, +} + +pub(crate) const fn root_size(role: InstanceRole) -> usize { + match role { + InstanceRole::Primary => ROOT_SIZE_PRIMARY, + InstanceRole::Secondary => ROOT_SIZE_SECONDARY, + } +} + +/// GPU virtual addresses of the objects both instances share. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct SharedAddresses { + /// Shared 16 KiB region A (root `+0x08`). + pub(crate) region_a: u64, + /// Shared region C (root `+0x20`), 0x1000 bytes. + pub(crate) region_c: u64, + /// Base of the contiguous hardware-data bundle. The hardware-data object + /// sits at the base; the five main-config views, the repeated region, and + /// the secondary's `+0x471` pointer are all derived offsets into it. + pub(crate) hw_data_bundle: u64, + /// Size of that one allocation; must be at least + /// [`HW_DATA_BUNDLE_MIN_ALLOC`]. + pub(crate) hw_data_bundle_alloc: usize, +} + +/// GPU virtual addresses of one instance's private objects. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct InstanceAddresses { + /// This instance's root; its address rides the endpoint-0x20 doorbell. + pub(crate) root: u64, + pub(crate) main_config: u64, + pub(crate) status_a: u64, + /// Required for the primary; must be zero for the secondary (whose root + /// still has the field, written zero). + pub(crate) status_b: u64, + /// Root `+0xb8`/`+0xc0`. Required for the secondary; the primary root is + /// only 0xb8 bytes and cannot even hold them, so they must be zero there. + pub(crate) secondary_extras: [u64; 2], +} + +/// One channel-table entry: three state-counter addresses, then the ring base. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct ChannelEntry { + pub(crate) states: [u64; 3], + pub(crate) ring: u64, +} + +impl ChannelEntry { + pub(crate) const EMPTY: ChannelEntry = ChannelEntry { + states: [0; 3], + ring: 0, + }; +} + +/// The primary's global region views at main `+0x2d0`: a globally retained, +/// initially zero HWDSID accounting table (256 pairs of u32), followed by +/// the high halves of two low/high alias pairs (the low halves +/// are the fixed context-0 addresses in +/// [`REGION_VIEW_LOW_ADDRS`]). Each pair must map one physical page from both +/// address spaces — an invariant of the UAT mapping layer that cannot be +/// checked from the addresses alone. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct PrimaryRegionViews { + pub(crate) sentinel_high: u64, + pub(crate) alias_high: [u64; 2], +} + +/// M5 25G76 descriptor fields +0x10 and +0x14 are independent. In slot 39 +/// native publishes 0x10000 and 0x8000 respectively. The older RegisterWindow +/// encoder duplicates one size and must not serialize this target's table. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5RegisterWindow { + pub(crate) slot: usize, + pub(crate) phys: u64, + pub(crate) device_va: u64, + pub(crate) size_10: u32, + pub(crate) size_14: u32, + pub(crate) unk_18: u64, + pub(crate) flag: u32, +} + +impl M5RegisterWindow { + /// Actual M5 PTE walks cover size_10 rounded to 16 KiB, including the + /// four pages of slot 39. size_14 is independently serialized firmware + /// metadata and must not truncate that mapping to two pages. + pub(crate) fn mapped_pages(&self) -> Result<(u64, u64, u64), InitdataError> { + let mask = UAT_PAGE_SIZE as u64 - 1; + if self.size_10 == 0 || self.phys & mask != self.device_va & mask { + return Err(InitdataError::RegisterWindow); + } + let physical = self.phys & !mask; + let virtual_address = self.device_va & !mask; + let end = self.device_va.checked_add(self.size_10 as u64) + .and_then(|value| value.checked_add(mask)) + .ok_or(InitdataError::AddressOutOfRange)? & !mask; + let span = end.checked_sub(virtual_address).ok_or(InitdataError::AddressOutOfRange)?; + physical.checked_add(span).ok_or(InitdataError::AddressOutOfRange)?; + Ok((physical, virtual_address, span)) + } +} + +/// Source-constructed register descriptors from both identical pre-handoff +/// J813/25G76 captures. These are firmware virtual mappings, not a request to +/// access or power the devices. No runtime currently consumes this profile. +pub(crate) const M5_25G76_REGISTER_WINDOWS: [M5RegisterWindow; 22] = { + const fn w(slot: usize, phys: u64, va: u64, size_10: u32, size_14: u32, + unk_18: u64, flag: u32) -> M5RegisterWindow { + M5RegisterWindow { slot, phys, device_va: 0xffff_fc21_8000_0000 + va, + size_10, size_14, unk_18, flag } + } + [ + w(0, 0x381014000, 0x000000, 0x04000, 0x04000, 0, 2), + w(3, 0x220104000, 0x008000, 0x18000, 0x18000, 0, 2), + w(8, 0x3a1350000, 0x028000, 0x04000, 0x04000, 0, 2), + w(9, 0x3803d0000, 0x030000, 0x04000, 0x04000, 0, 2), + w(10, 0x3803c0000, 0x038000, 0x04000, 0x04000, 0, 0), + w(12, 0x42165c000, 0x040000, 0x04000, 0x04000, 0, 2), + w(14, 0x380280000, 0x048000, 0x08000, 0x08000, 0, 0), + w(15, 0x38c840000, 0x058000, 0x24000, 0x24000, 0, 2), + w(17, 0x580000000, 0x080000, 0x21400, 0x21400, 0, 2), + w(22, 0x581000000, 0x0a8000, 0x08000, 0x08000, 0, 2), + w(24, 0x580ec0000, 0x0b8000, 0x10000, 0x10000, 0, 2), + w(26, 0x580d04000, 0x0d0000, 0x08000, 0x08000, 0xd04000, 2), + w(27, 0x580d0d000, 0x0e1000, 0x01000, 0x01000, 0xd0d000, 2), + w(28, 0x580d50000, 0x0e8000, 0x10000, 0x10000, 0xd50000, 2), + w(29, 0x580d10000, 0x100000, 0x04000, 0x04000, 0xd10000, 2), + w(31, 0x580d40000, 0x108000, 0x04000, 0x04000, 0xd40000, 2), + w(32, 0x580d60000, 0x110000, 0x08000, 0x08000, 0xd60000, 2), + w(35, 0x580e00000, 0x120000, 0x04000, 0x04000, 0xe00000, 2), + w(39, 0x580e08000, 0x128000, 0x10000, 0x08000, 0, 2), + w(41, 0x580e33800, 0x143800, 0x04000, 0x04000, 0, 2), + w(42, 0x580e35000, 0x151000, 0x04000, 0x04000, 0, 2), + w(50, 0x580014400, 0x160400, 0x00400, 0x00400, 0x14400, 0), + ] +}; + +pub(crate) fn encode_m5_25g76_register_map(out: &mut [u8]) -> Result<(), InitdataError> { + if out.len() != HW_REGISTER_MAP_SLOTS * HW_REGISTER_MAP_ENTRY_SIZE { + return Err(InitdataError::BufferSize); + } + out.fill(0); + for window in M5_25G76_REGISTER_WINDOWS { + let base = window.slot * HW_REGISTER_MAP_ENTRY_SIZE; + put_u64(out, base, window.phys); + put_u64(out, base + 8, window.device_va); + put_u32(out, base + 0x10, window.size_10); + put_u32(out, base + 0x14, window.size_14); + put_u64(out, base + 0x18, window.unk_18); + put_u32(out, base + 0x20, window.flag); + } + for slot in [2, 5, 6, 7, 30, 33, 34, 37, 38, 40, 43, 46, 47, 48, 49, 52] { + put_u32(out, slot * HW_REGISTER_MAP_ENTRY_SIZE + 0x20, 2); + } + Ok(()) +} + +pub(crate) const M5_25G76_HW_DATA_SIZE: usize = 0x2708; + +pub(crate) const M5_25G76_SHARED_PREFIX_SIZE: usize = 0xc500; + +pub(crate) const M5_25G76_AON_PTD_SIZE: usize = 0xe4; + +/// J813/25G76 AON PTD backing, captured twice before each role's handoff and +/// unchanged after a passing Metal workload. The three recorded words are +/// scoped to this platform's telemetry description; they are not generic +/// M5 constants. The allocation and GPU binding must remain caller-owned. +pub(crate) fn encode_m5_25g76_aon_ptd(out: &mut [u8]) -> Result<(), InitdataError> { + if out.len() != M5_25G76_AON_PTD_SIZE { + return Err(InitdataError::BufferSize); + } + out.fill(0); + put_u32(out, 0, 0x6730_5452); + put_u32(out, 4, 0x001d_0001); + put_u32(out, 8, 0x0000_1401); + Ok(()) +} + +const M5_25G76_STATUS_CONFIG_WORDS: &[(usize, u32)] = &[ + (0x010, 0x0000001f), (0x014, 0x3e0a3d71), (0x018, 0x401ae148), + (0x01c, 0x00000028), (0x020, 0x00000001), (0x0c8, 0x00002af8), + (0x0cc, 0x00001f40), (0x0d8, 0x41980000), (0x0dc, 0x3d0f5c28), + (0x0f0, 0x000026ac), (0x0f4, 0x000000c8), (0x108, 0x42c80000), + (0x10c, 0x43c80000), (0x110, 0x000000c8), (0x128, 0x00000001), + (0x12c, 0x00005eb0), (0x130, 0x3e800000), (0x134, 0x3f99999a), + (0x158, 0x0000000e), (0x1c0, 0x00000001), (0x1c4, 0x00000001), + (0x1c8, 0x00000002), (0x1cc, 0x00000001), (0x1d0, 0x00000001), + (0x1d4, 0x00000001), (0x1d8, 0x00000001), (0x588, 0x00000001), + (0x58c, 0x0000000a), (0x590, 0x00000dac), (0x594, 0x000003e8), + (0x598, 0x00000bb8), (0x59c, 0x000002bc), (0x5cc, 0x00000001), + (0x5d0, 0x00000004), (0x5dc, 0x00001f40), (0x5e0, 0x000000c8), + (0x5e4, 0x00000fa0), (0x5e8, 0x0000012c), (0x5ec, 0x000007d0), + (0x5f0, 0x0000012c), (0x5f4, 0x000003e8), (0x5f8, 0x0000012c), + (0x600, 0x00000001), (0x604, 0x41700000), (0x608, 0x40a00000), + (0x60c, 0x00000020), (0x610, 0x000004b0), (0x620, 0x0000044c), +]; + +/// Build the primary status object before either firmware role is started. +/// Secondary root+0xb8 aliases status+0xe440. GFX1 copies that pointer to +/// firmware global 0x176248 at text+0x211d4 and later writes config+0x670, +/// +0x678 and +0x680 at text+0x1af94..0x1afc4. Those are firmware-owned +/// runtime state, not platform constants, and must start at zero even when +/// a primary pre-handoff capture (taken after secondary startup) has values. +pub(crate) fn encode_m5_25g76_primary_status_b( + fwctl_state: u64, + fwctl_ring: u64, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != PRIMARY_STATUS_B_OBJECT_SIZE { + return Err(InitdataError::BufferSize); + } + required_address(fwctl_state)?; + required_address(fwctl_ring)?; + out.fill(0); + encode_status_block(&mut out[..STATUS_BLOCK_SIZE])?; + put_u64(out, PRIMARY_STATUS_B_FWCTL_STATE, fwctl_state); + put_u64(out, PRIMARY_STATUS_B_FWCTL_RING, fwctl_ring); + put_u32(out, PRIMARY_STATUS_B_CONFIG_HEADER, 1); + for &(offset, value) in M5_25G76_STATUS_CONFIG_WORDS { + put_u32(out, PRIMARY_STATUS_B_CONFIG_OFFSET + offset, value); + } + Ok(()) +} + +/// Shared private arena observed before primary initialization on J813. +/// The status and secondary-grid pointers name overlapping views of this +/// one backing. This extent is a measured mapped arena, not a claim about +/// the sizes of the native host's individual suballocations. +pub(crate) const M5_25G76_PRIVATE_CLUSTER_SIZE: usize = 0x178000; + +pub(crate) fn encode_m5_25g76_private_cluster( + fwctl_state: u64, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != M5_25G76_PRIVATE_CLUSTER_SIZE { + return Err(InitdataError::BufferSize); + } + required_address(fwctl_state)?; + let fwctl_ring = fwctl_state.checked_add(0x40).ok_or(InitdataError::AddressOutOfRange)?; + required_address(fwctl_ring)?; + out.fill(0); + encode_m5_25g76_primary_status_b(fwctl_state, fwctl_ring, &mut out[0x340..0xee40])?; + for offset in [0xee40, 0xc3100] { + encode_status_block(&mut out[offset..offset + STATUS_BLOCK_SIZE])?; + } + encode_secondary_root_extra_1_for_profile(RootProfile::J813G17G25G76, + &mut out[0x177400..0x177480])?; + // The main-config encoders carry one measured opening record (0x16 / + // 0x2a). Publish exactly one producer entry for each control channel. + // All work-channel and report counters remain zero. + put_u32(out, 0x320, 1); + put_u32(out, 0x1773e0, 1); + Ok(()) +} + +/// Caller-owned bindings in the power/performance policy allocation. +/// The host stores mach_absolute_time() at policy+0x651c. Supply the live +/// platform counter in its native timebase, never a captured timestamp. +#[derive(Clone, Copy)] +pub(crate) struct M5PolicyBindings { + pub state: u64, + pub aon_ptd: u64, + pub boot_timestamp: u64, +} + +/// Pre-handoff J813/25G76 scalars, identical across two cold boots after +/// removing owned pointers and the native boot timestamp. The repeated +/// 512-entry u16 table is encoded separately. Calibration fields whose +/// meanings remain unknown are scoped to this measured ten-core target. +const M5_25G76_POLICY_WORDS: &[(usize, u32)] = &[ + (0x3d98, 0xffffffff), (0x3db0, 0xffffffff), (0x5244, 0x00030d40), + (0x5248, 0x00030d40), (0x5250, 0x00000004), (0x5254, 0x3f800000), + (0x526c, 0x00000001), (0x5270, 0x00000001), (0x5280, 0x00000064), + (0x5284, 0x00000001), (0x5288, 0x000004b0), (0x5290, 0x00000064), + (0x52a0, 0x00000004), (0x52a4, 0x3f800000), (0x52ac, 0x00000001), + (0x52b0, 0x00000001), (0x52c0, 0x00000064), (0x52c4, 0x00000001), + (0x52c8, 0x000004b0), (0x52d0, 0x00000064), (0x5300, 0x3f828f5c), + (0x5304, 0x3f828f5c), (0x5308, 0x3f828f5c), (0x530c, 0x3f828f5c), + (0x5310, 0x3f828f5c), (0x5314, 0x3f828f5c), (0x5318, 0x3f828f5c), + (0x531c, 0x3f828f5c), (0x5320, 0x3f828f5c), (0x5324, 0x3f828f5c), + (0x5328, 0x3f828f5c), (0x532c, 0x3f828f5c), (0x5330, 0x3f828f5c), + (0x5bf8, 0x00000271), (0x5c04, 0x3f7f2e9f), (0x5c0c, 0x3b516154), + (0x5c14, 0x3ca59586), (0x5c20, 0x46bd6000), (0x5c24, 0x40a90fe4), + (0x5c2c, 0xbd4ac5b4), (0x5c30, 0x00000028), (0x5c34, 0x000004b0), + (0x5c38, 0x000004b0), (0x5c44, 0x00005eb0), (0x5c78, 0x000004b0), + (0x5cb0, 0x00000008), (0x5cbc, 0x3f000000), (0x5cc4, 0x3f000000), + (0x5ccc, 0x3f99999a), (0x5cd8, 0x47800000), (0x5cdc, 0x3e800000), + (0x5ce8, 0x00000028), (0x5cec, 0x000004b0), (0x5cfc, 0x00005eb0), + (0x5d08, 0x00000010), (0x5d10, 0x0005dc00), (0x5d68, 0x0000004a), + (0x5d70, 0x0000005a), (0x5d74, 0x00000032), (0x5d78, 0x00000006), + (0x5d80, 0x00000006), (0x5d84, 0x00000001), (0x5d8c, 0x3f4ccccd), + (0x5d90, 0x3f7eb852), (0x5d94, 0x3e4ccccd), (0x5d98, 0x3ba3d70a), + (0x5d9c, 0x3f144b3c), (0x5da0, 0x3f144b3c), (0x5da8, 0x42be0000), + (0x5dac, 0x4029eb85), (0x5db0, 0x4029eb85), (0x5db4, 0x4139435e), + (0x5db8, 0x00000064), (0x5dbc, 0x000004b0), (0x5dc0, 0x00000064), + (0x5dcc, 0x0000004a), (0x5dd4, 0x00000001), (0x5e00, 0x00000064), + (0x5e20, 0x00000401), (0x5e24, 0x00006400), (0x5e2c, 0x001f4000), + (0x5e30, 0x0000c800), (0x5e34, 0x000fa000), (0x5e38, 0x00012c00), + (0x5e3c, 0x0007d000), (0x5e40, 0x00012c00), (0x5e44, 0x0003e800), + (0x5e48, 0x00012c00), (0x5e4c, 0x00000100), (0x5ea4, 0x00000001), + (0x5ed0, 0x00000001), (0x74d8, 0x47800000), (0x74dc, 0x42200000), + (0x74e0, 0x44960000), (0x74e4, 0x0000062a), (0x74f8, 0x00000028), + (0x7500, 0x42c80000), (0x7504, 0x000004b0), (0x750c, 0x3f4ccccd), + (0x7510, 0x3e4ccccd), (0x7550, 0xdcdcfbfa), (0x7558, 0x00001f40), + (0x7560, 0x00000004), (0x7574, 0x3f800000), (0x757c, 0x3d0f5c28), + (0x7588, 0x47800000), (0x758c, 0x41980000), (0x7598, 0x00000028), + (0x759c, 0x000004b0), (0x75a0, 0x000004b0), (0x75ac, 0x00002af8), + (0x75e0, 0x000004b0), (0x77f8, 0x00000002), (0x77fc, 0x42000006), + (0x7a10, 0xb8520000), (0x7a14, 0x00003f7e), (0x7a18, 0xd70a0000), + (0x7a1c, 0x00003ba3), (0x7a24, 0x000043c8), (0x7a30, 0x00004780), + (0x7a34, 0x000042c8), (0x7a3c, 0x0384bac8), (0x7a40, 0x03e80000), + (0x7a44, 0x03e80000), (0x7a4c, 0x80000000), (0x7a50, 0x26ac453b), + (0x7a84, 0x03e80000), (0x7aa0, 0x00c80000), (0x7b58, 0x000004b0), + (0x7b6c, 0x00000001), (0x7ba0, 0x00000101), (0x7ba4, 0x00000200), + (0x7bbc, 0x00023f00), (0x7bc0, 0x00000100), (0x7bc4, 0x00000100), + (0x7bdc, 0x00024000), (0x7be0, 0x00000100), (0x7be4, 0x00000100), + (0x7bfc, 0x00024100), (0x7c48, 0x00000001), (0x7c50, 0x00005eb0), + (0x7c54, 0x00005eb0), (0x7c58, 0x00005eb0), (0x7c68, 0x3f800000), + (0x7c6c, 0x00000004), (0x7c70, 0x00000008), (0x7c74, 0x0002ee00), + (0x7d44, 0x0000007c), (0x7d50, 0x3f77bdef), (0x7d58, 0x3d042108), + (0x7d60, 0x3e0a3d71), (0x7d6c, 0x47800000), (0x7d70, 0x401ae148), + (0x7d7c, 0x00000028), (0x7d80, 0x000004b0), (0x7d84, 0x000004b0), + (0x7d8c, 0x46bd6000), (0x7d90, 0x00005eb0), (0x7d9c, 0x000000f8), + (0x7da4, 0x005ad200), (0x7dc4, 0x000004b0), (0x7e04, 0x00000001), + (0x7ed4, 0x00000032), (0x7ed8, 0x00000001), (0x7ee0, 0x3f638e39), + (0x7ee4, 0x3f2aaaab), (0x7ee8, 0x3de38e39), (0x7eec, 0x3eaaaaab), + (0x7ef0, 0xbecccccd), (0x7ef4, 0xbf4ccccd), (0x7efc, 0x47800000), + (0x7f00, 0xc0a00000), (0x7f04, 0xc0a00000), (0x7f0c, 0x00000064), + (0x7f10, 0x000004b0), (0x7f14, 0x00000064), (0x7f1c, 0x45fa0000), + (0x7f20, 0x00000578), (0x7f28, 0x0000000e), (0x7f2c, 0x00000048), + (0x7f30, 0x00000018), (0x7f34, 0x001a5e00), (0x7f3c, 0x0008ca00), + (0x7f48, 0x47800000), (0x7f70, 0x00001f40), (0x7f74, 0x00000004), + (0x7f78, 0x000009c4), (0x7f7c, 0x00000258), (0x7f80, 0x00000002), + (0x7f84, 0x00000004), (0x7f88, 0x00000032), (0x7fb8, 0x47800000), + (0x7fc8, 0x00000028), (0x7fcc, 0x000004b0), (0x8098, 0x00000001), + (0x80ac, 0x0000000a), (0x80b8, 0x00000001), (0x8174, 0xac000000), + (0x8178, 0xe800000d), (0x817c, 0xb8000003), (0x8180, 0xb000000b), + (0x8184, 0xb0000004), (0x8188, 0xbc000004), (0x818c, 0x20000002), + (0x8198, 0x00000001), (0x81b4, 0x00000004), (0x81c0, 0x3f780000), + (0x81c8, 0x3d000000), (0x81d0, 0x40a00000), (0x81dc, 0x47800000), + (0x81e0, 0x41700000), (0x81ec, 0x0000044c), (0x81f0, 0x000004b0), + (0x81f4, 0x000004b0), (0x8200, 0x000004b0), (0x8234, 0x000004b0), + (0x827c, 0x00000064), (0x8290, 0xdcdcfbfa), (0x8298, 0x0000007d), + (0x829c, 0x00000001), (0x8ee0, 0xdcdcfbfb), (0x8ee8, 0x00000001), + (0xaeec, 0x41c80000), (0xaef0, 0x41c80000), (0xb6a8, 0x67305452), + (0xb6e8, 0x00000001), (0xb728, 0x5243464c), (0xb72c, 0x4758464c), + (0xb738, 0x47584c50), (0xb748, 0x00000001), (0xb7a8, 0x00000001), + (0xb7b4, 0x42b73333), (0xb7f4, 0x449b8000), (0xb834, 0x42bc0000), + (0xb8e0, 0x0000186a), +]; + +/// Initialize the six allocations following M5 hardware-data. Preserve the +/// hardware block and subsequent channel resources. No firmware is started. +pub(crate) fn encode_m5_25g76_bundle_policy( + bindings: M5PolicyBindings, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() < M5_25G76_SHARED_PREFIX_SIZE { + return Err(InitdataError::BufferSize); + } + required_address(bindings.state)?; + required_address(bindings.aon_ptd)?; + let state_end = bindings.state.checked_add(STATUS_BLOCK_SIZE as u64) + .ok_or(InitdataError::AddressOutOfRange)?; + let aon_end = bindings.aon_ptd.checked_add(M5_25G76_AON_PTD_SIZE as u64) + .ok_or(InitdataError::AddressOutOfRange)?; + required_address(state_end - 1)?; + required_address(aon_end - 1)?; + if bindings.state < aon_end && bindings.aon_ptd < state_end { + return Err(InitdataError::PairAliasedObject); + } + out[0x2740..M5_25G76_SHARED_PREFIX_SIZE].fill(0); + for &(offset, value) in M5_25G76_POLICY_WORDS { + put_u32(out, offset, value); + } + for index in 0..512 { + put_u16(out, 0x6ed7 + index * 2, 0x7fff); + } + put_u64(out, 0x8ed8, bindings.state); + put_u64(out, 0xb6a0, bindings.aon_ptd); + put_u64(out, 0xb75c, bindings.boot_timestamp); + Ok(()) +} + +/// Recorded platform words outside the explicit register, performance and +/// owned-pointer fields. Meanings not yet derived are deliberately kept as +/// target-scoped measured values. Never insert runtime completion counters +/// or captured allocation addresses here. Reference hardware-data SHA-256: +/// 6f9ac0c4664f898a0ddb4e5df9ad160a23c1b52d3fd750750779cbdebe446be9. +const M5_25G76_HW_PLATFORM_WORDS: &[(usize, u32)] = &[ + (0x0004, 0x0000006f), (0x0008, 0xffc00000), (0x0014, 0x00000010), + (0x001c, 0x00000010), (0x0020, 0xffff8000), (0x0024, 0x000002ff), + (0x0028, 0x81400000), (0x002c, 0xfffffc21), (0x00e0, 0x00002008), + (0x00e8, 0x20080000), (0x00f4, 0x00002008), (0x00f8, 0x000024cb), + (0x00fc, 0xc98a2cfa), (0x0100, 0xf4f624cb), (0x0104, 0x1877e917), + (0x0108, 0x38d924cb), (0x010c, 0xbdab0000), (0x02d8, 0xfff82000), + (0x02dc, 0xd32d2cdb), (0x02e0, 0xf5002000), (0x02e4, 0x21dae926), + (0x02e8, 0x38b62000), (0x02ec, 0xc7420008), (0x03e0, 0x00007fe0), + (0x03e8, 0x7fe00000), (0x03f4, 0x00007fe0), (0x03f8, 0x00008000), + (0x0400, 0x80000000), (0x040c, 0x00008000), (0x05d8, 0x4b232645), + (0x05dc, 0x00000e98), (0x05e0, 0xd5a2ea5f), (0x05e4, 0x40003fff), + (0x05e8, 0xca5e4000), (0x05ec, 0x4000f5a2), (0x0e90, 0x00008142), + (0x0e94, 0x00000002), (0x0ea0, 0x00000001), (0x0ea4, 0x00000001), + (0x0eb8, 0x00000001), (0x0ec0, 0x00000001), (0x0ec8, 0x00000001), + (0x0ed0, 0x00005dc0), (0x0ed4, 0x00000001), (0x0ed8, 0x00000008), + (0x0ee0, 0x00000001), (0x0ee4, 0x00000001), (0x0ee8, 0x00000001), + (0x0f04, 0x0000001f), (0x0f24, 0x07800004), (0x0f28, 0x00000006), + (0x0f34, 0x00000001), (0x0f38, 0x00000001), (0x0f4c, 0x00000031), + (0x0f6c, 0x00000001), (0x0f88, 0x0000000a), (0x0f8c, 0x00000001), + (0x0fac, 0x00000001), (0x0fb8, 0x00000020), (0x0fbc, 0x00000005), + (0x0fc0, 0x0000000a), (0x0fc4, 0x0000000c), (0x2544, 0x00000004), + (0x2548, 0x00000006), (0x254c, 0x00000003), (0x2550, 0x00000007), + (0x2554, 0x00000007), (0x2568, 0x0000000a), (0x2570, 0x00000001), + (0x258c, 0x00180000), (0x2594, 0x00000001), (0x2598, 0x00000001), + (0x259c, 0x00000001), (0x25a4, 0x00000001), (0x25a8, 0x00000001), + (0x25ac, 0x00000001), (0x25b4, 0xffffffff), (0x25b8, 0xffffffff), + (0x25bc, 0xffffffff), (0x25c0, 0xffffffff), (0x25c4, 0xffffffff), + (0x25c8, 0xffffffff), (0x25cc, 0xffffffff), (0x25d0, 0xffffffff), + (0x25d4, 0xffffffff), (0x25d8, 0xffffffff), (0x25dc, 0xffffffff), + (0x25e0, 0xffffffff), (0x25f4, 0x00000001), (0x2600, 0x00000001), + (0x2608, 0x00000001), (0x2610, 0x00000100), (0x26b4, 0x00000001), + (0x26b8, 0x00000001), (0x26e0, 0x000003e8), (0x26e8, 0x00000001), +]; + +/// Reconstruct the M5 reference hardware-data block with caller-owned queue +/// and QoS bindings. Performance values are measured on the ten-core J813 +/// reference, not derived from ADT and not a generic M5 power configuration. +/// Both pre-handoff firmware roles supplied identical reference bytes. +/// This encoder grants no runtime admission and performs no MMIO accesses. +pub(crate) fn encode_m5_25g76_hw_data( + aliases: [G17PKsmCompletionAliases; M5_25G76_COMPLETION_QUEUE_COUNT], + qos_high: u64, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != M5_25G76_HW_DATA_SIZE { + return Err(InitdataError::BufferSize); + } + required_address(qos_high)?; + let qos_end = qos_high.checked_add(0xe40).ok_or(InitdataError::AddressOutOfRange)?; + required_address(qos_end - 1)?; + let mut completion = [0; 0x80]; + encode_m5_25g76_completion_table(aliases, &mut completion)?; + for alias in aliases { + if qos_high < alias.high + M5_25G76_COMPLETION_BACKING_SIZE as u64 + && alias.high < qos_end { + return Err(InitdataError::PairAliasedObject); + } + } + + out.fill(0); + for &(offset, value) in M5_25G76_HW_PLATFORM_WORDS { + put_u32(out, offset, value); + } + encode_m5_25g76_register_map(&mut out[0x640..0xe88])?; + out[0x2614..0x2694].copy_from_slice(&completion); + put_u64(out, 0x26ac, qos_high); + + // Native includes index zero plus twelve operating points. Each voltage + // occupies all sixteen lanes of its 0x40-byte state row. + const FREQUENCY: [u32; 13] = [0, 338, 486, 636, 796, 888, 988, 1084, 1182, 1278, 1374, 1470, 1578]; + const CORE_VOLTAGE: [u32; 13] = [125, 615, 630, 660, 705, 735, 755, 800, 830, 865, 905, 945, 1010]; + const MEMORY_VOLTAGE: [u32; 13] = [770, 770, 770, 770, 770, 770, 770, 800, 830, 865, 905, 945, 1010]; + const RELATIVE_A: [u32; 13] = [0, 17, 23, 30, 42, 50, 58, 71, 82, 85, 89, 93, 100]; + const RELATIVE_B: [u32; 13] = [0, 0, 11, 24, 36, 44, 52, 60, 68, 75, 83, 91, 100]; + for index in 0..13 { + put_u32(out, 0xfc8 + index * 4, FREQUENCY[index]); + put_u32(out, 0x1848 + index * 4, 0x3f828f5c); + put_u32(out, 0x18c8 + index * 4, RELATIVE_A[index]); + put_u32(out, 0x1908 + index * 4, RELATIVE_B[index]); + for lane in 0..16 { + put_u32(out, 0x1008 + index * 0x40 + lane * 4, CORE_VOLTAGE[index]); + put_u32(out, 0x1408 + index * 0x40 + lane * 4, MEMORY_VOLTAGE[index]); + } + } + for index in 0..16 { + put_u32(out, 0x19c8 + index * 4, index as u32); + } + Ok(()) +} + +/// Fail-closed validation errors for the grounded layout. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum InitdataError { + BufferSize, + AddressOutOfRange, + NullRequiredAddress, + RoleSpecificAddress, + BundleAllocationTooSmall, + ChannelTableShape, + RegisterWindow, + PairAliasedObject, +} + +fn address_representable(address: u64) -> bool { + let high = address & !INITDATA_ADDR_MASK; + high == 0 || high == INITDATA_ADDR_PREFIX +} + +fn required_address(address: u64) -> Result<(), InitdataError> { + if address == 0 { + Err(InitdataError::NullRequiredAddress) + } else if !address_representable(address) { + Err(InitdataError::AddressOutOfRange) + } else { + Ok(()) + } +} + +fn put_u16(bytes: &mut [u8], offset: usize, value: u16) { + bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u32(bytes: &mut [u8], offset: usize, value: u32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +fn write_runs(bytes: &mut [u8], runs: &[(usize, &[u8])]) { + for (offset, data) in runs { + bytes[*offset..*offset + data.len()].copy_from_slice(data); + } +} + +fn validate_shared(shared: &SharedAddresses) -> Result<(), InitdataError> { + required_address(shared.region_a)?; + required_address(shared.region_c)?; + required_address(shared.hw_data_bundle)?; + if shared.hw_data_bundle_alloc < HW_DATA_BUNDLE_MIN_ALLOC { + return Err(InitdataError::BundleAllocationTooSmall); + } + Ok(()) +} + +fn validate_instance(role: InstanceRole, inst: &InstanceAddresses) -> Result<(), InitdataError> { + required_address(inst.root)?; + required_address(inst.main_config)?; + required_address(inst.status_a)?; + match role { + InstanceRole::Primary => { + // The primary root has no +0xb8/+0xc0 fields at all; carrying + // secondary extras there is a role-confusion bug at the caller. + if inst.secondary_extras != [0, 0] { + return Err(InitdataError::RoleSpecificAddress); + } + required_address(inst.status_b)?; + } + InstanceRole::Secondary => { + // Every hardware-booting host hands the secondary a zero status-B; + // a nonzero value there is ungrounded, so fail closed on it. + if inst.status_b != 0 { + return Err(InitdataError::RoleSpecificAddress); + } + for extra in inst.secondary_extras { + required_address(extra)?; + } + } + } + Ok(()) +} + +/// Encode one 0x20-byte UAT level descriptor. Every field is derivable from +/// the level's index shift and entry count; the index mask +/// `(entries - 1) << shift` reproduces all three captured masks exactly. +fn encode_uat_level_descriptor(bytes: &mut [u8], offset: usize, shift: u8, entries: u16) { + bytes[offset] = 8; + bytes[offset + 1] = UAT_PAGE_BITS; + bytes[offset + 2] = UAT_PAGE_BITS; + bytes[offset + 3] = shift; + put_u16(bytes, offset + 0x04, entries); + put_u16(bytes, offset + 0x06, UAT_PAGE_SIZE); + put_u64(bytes, offset + 0x08, 1); + put_u64(bytes, offset + 0x10, UAT_LEVEL_PHYS_MASK); + put_u64(bytes, offset + 0x18, (entries as u64 - 1) << shift); +} + +/// Encode the common root layout with an explicitly selected firmware build. +/// The existing runtime continues to call the J700-only wrapper above. +pub(crate) fn encode_root_for_profile( + profile: RootProfile, + role: InstanceRole, + shared: &SharedAddresses, + inst: &InstanceAddresses, + out: &mut [u8], +) -> Result<(), InitdataError> { + // Profile-sized: identical to root_size(role) for J700/J813. + if out.len() != profile.root_size(role) { + return Err(InitdataError::BufferSize); + } + validate_shared(shared)?; + validate_instance(role, inst)?; + + out.fill(0); + put_u64(out, ROOT_VERSION, profile.version_word()); + put_u64(out, ROOT_REGION_A, shared.region_a); + // ROOT_ZERO_10 deliberately left zero. + put_u64(out, ROOT_MAIN_CONFIG, inst.main_config); + put_u64(out, ROOT_REGION_C, shared.region_c); + put_u32(out, ROOT_INSTANCE_KIND, role as u32); + put_u32(out, ROOT_CONSTANT_2C, 1); + put_u16(out, ROOT_PAGE_SIZE, UAT_PAGE_SIZE); + out[ROOT_PAGE_BITS] = UAT_PAGE_BITS; + out[ROOT_LEVEL_COUNT] = UAT_LEVEL_COUNT as u8; + for (index, (shift, entries)) in UAT_LEVELS.iter().enumerate() { + encode_uat_level_descriptor( + out, + ROOT_LEVELS + index * UAT_LEVEL_DESC_SIZE, + *shift, + *entries, + ); + } + put_u64(out, ROOT_STATUS_A, inst.status_a); + put_u64(out, ROOT_STATUS_B, inst.status_b); + if role == InstanceRole::Secondary { + put_u64(out, ROOT_SECONDARY_EXTRA_0, inst.secondary_extras[0]); + put_u64(out, ROOT_SECONDARY_EXTRA_1, inst.secondary_extras[1]); + } + Ok(()) +} + +/// Derive the native channel table for one instance. +/// +/// `state_grid` is this instance's compact channel-state block (0x40-stride, +/// permuted per [`WORK_STATE_GRID_OFFSETS`]); `status_a` anchors the trailing +/// report/partial channels; the ring for entry 12 is `main_config + 0x4c0`; +/// work rings for the primary sit in the bundle at +/// [`WORK_RING_BUNDLE_OFFSETS`] (which requires the +/// [`NATIVE_SHARED_CLUSTER_SIZE`] cluster). The secondary leaves entries +/// 0..11 empty: it is a control-only peer with no work channels. +pub(crate) fn derive_channel_table( + role: InstanceRole, + state_grid: u64, + status_a: u64, + main_config: u64, + bundle: u64, +) -> [ChannelEntry; CHANNEL_TABLE_ENTRIES] { + let mut table = [ChannelEntry::EMPTY; CHANNEL_TABLE_ENTRIES]; + let grid_states = |index: usize| { + let base = state_grid + WORK_STATE_GRID_OFFSETS[index] as u64; + [ + base, + base + CHANNEL_STATE_SPACING as u64, + base + 2 * CHANNEL_STATE_SPACING as u64, + ] + }; + if role == InstanceRole::Primary { + for index in 0..WORK_CHANNEL_COUNT { + table[index] = ChannelEntry { + states: grid_states(index), + ring: bundle + WORK_RING_BUNDLE_OFFSETS[index] as u64, + }; + } + } + table[CONTROL_CHANNEL_INDEX] = ChannelEntry { + states: grid_states(CONTROL_CHANNEL_INDEX), + ring: main_config + MAIN_CONTROL_RING as u64, + }; + for (slot, index) in REPORT_CHANNEL_INDICES.iter().enumerate() { + let mut states = [0u64; 3]; + for (word, offset) in states.iter_mut().zip(REPORT_STATE_STATUS_A_OFFSETS[slot]) { + *word = status_a + offset as u64; + } + table[*index] = ChannelEntry { + states, + ring: status_a + REPORT_RING_STATUS_A_OFFSETS[slot] as u64, + }; + } + table[PARTIAL_CHANNEL_INDEX] = ChannelEntry { + states: [status_a + PARTIAL_STATE_STATUS_A_OFFSET as u64, 0, 0], + ring: 0, + }; + table +} + +fn validate_populated_entry(entry: &ChannelEntry) -> Result<(), InitdataError> { + // A populated channel needs all three state-counter addresses — a null + // producer (state 2) on a populated entry makes firmware fault on address + // zero — and a real ring. + for state in entry.states { + if state == 0 { + return Err(InitdataError::ChannelTableShape); + } + if !address_representable(state) { + return Err(InitdataError::AddressOutOfRange); + } + } + required_address(entry.ring) +} + +fn validate_channel_table( + role: InstanceRole, + main_config: u64, + channels: &[ChannelEntry; CHANNEL_TABLE_ENTRIES], +) -> Result<(), InitdataError> { + for (index, entry) in channels.iter().enumerate() { + match index { + 0..=11 => match role { + InstanceRole::Primary => validate_populated_entry(entry)?, + // The secondary has no work channels at all. + InstanceRole::Secondary => { + if *entry != ChannelEntry::EMPTY { + return Err(InitdataError::ChannelTableShape); + } + } + }, + 12 => { + validate_populated_entry(entry)?; + // Device control is embedded in the main object, at exactly + // main + 0x4c0 on both instances. + if entry.ring != main_config + MAIN_CONTROL_RING as u64 { + return Err(InitdataError::ChannelTableShape); + } + } + 13 | 14 => validate_populated_entry(entry)?, + 15 => { + // Partial: a first state address and nothing else. + required_address(entry.states[0])?; + if entry.states[1] != 0 || entry.states[2] != 0 || entry.ring != 0 { + return Err(InitdataError::ChannelTableShape); + } + } + _ => { + if *entry != ChannelEntry::EMPTY { + return Err(InitdataError::ChannelTableShape); + } + } + } + } + Ok(()) +} + +/// The two complete M5/25G76 pre-handoff main configurations match the common +/// layout except primary +0x32c/+0x344 and secondary +0x300. Keep these +/// measured scalars build-specific; their meanings are not inferred here. +pub(crate) fn encode_main_config_for_profile( + profile: RootProfile, + role: InstanceRole, + shared: &SharedAddresses, + inst: &InstanceAddresses, + channels: &[ChannelEntry; CHANNEL_TABLE_ENTRIES], + region_views: Option<&PrimaryRegionViews>, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != MAIN_CONFIG_SIZE { + return Err(InitdataError::BufferSize); + } + validate_shared(shared)?; + validate_instance(role, inst)?; + validate_channel_table(role, inst.main_config, channels)?; + match (role, region_views) { + (InstanceRole::Primary, Some(views)) => { + required_address(views.sentinel_high)?; + for high in views.alias_high { + required_address(high)?; + } + } + (InstanceRole::Secondary, None) => {} + _ => return Err(InitdataError::RoleSpecificAddress), + } + // Every view must fit inside the one bundle allocation. (The last two end + // exactly at 0xf000, inside the 0x10000 minimum.) The view table is the + // profile's: J700/J813 keep BUNDLE_VIEW_OFFSETS/EXTENTS unchanged. + let view_offsets = profile.bundle_view_offsets(); + for (offset, extent) in view_offsets.iter().zip(profile.bundle_view_extents()) { + if offset + extent > shared.hw_data_bundle_alloc { + return Err(InitdataError::BundleAllocationTooSmall); + } + } + + out.fill(0); + // Firmware log enable. The emitter at A000 0xfffffc0000021fa0 reads this + // word and returns immediately when it is zero; every buffer the facility + // needs is already allocated and pointed at by the addresses below. The + // records are plain ASCII. Shipping macOS provisions the whole facility + // and then throws the messages away (drainFirmwareLogRing is `bti c; ret`), + // which is why the captured value is zero. It stays zero here. + let bundle = shared.hw_data_bundle; + put_u64(out, MAIN_HW_DATA, bundle); + let repeated = bundle + profile.repeated_region_bundle_offset() as u64; + put_u64(out, MAIN_REPEATED_0, repeated); + put_u64(out, MAIN_REPEATED_1, repeated); + + for (index, entry) in channels.iter().enumerate() { + let base = MAIN_CHANNEL_TABLE + index * CHANNEL_ENTRY_SIZE; + for (word, state) in entry.states.iter().enumerate() { + put_u64(out, base + word * 8, *state); + } + put_u64(out, base + CHANNEL_ENTRY_STATE_COUNT * 8, entry.ring); + } + + match (role, region_views) { + (InstanceRole::Primary, Some(views)) => { + // The five bare pointers are views into the one bundle + // allocation, at fixed offsets. Unaligned stores at +0x254. + for (index, offset) in view_offsets.iter().enumerate() { + put_u64(out, MAIN_BUNDLE_VIEWS + index * 8, bundle + *offset as u64); + } + // High-only sentinel followed by two low/high region-view pairs. + put_u64(out, MAIN_REGION_VIEWS, views.sentinel_high); + put_u64(out, MAIN_REGION_VIEWS + 0x08, REGION_VIEW_LOW_ADDRS[0]); + put_u64(out, MAIN_REGION_VIEWS + 0x10, views.alias_high[0]); + put_u64(out, MAIN_REGION_VIEWS + 0x18, REGION_VIEW_LOW_ADDRS[1]); + put_u64(out, MAIN_REGION_VIEWS + 0x20, views.alias_high[1]); + if profile == RootProfile::J700G17P { + put_u32(out, MAIN_PRIMARY_SCALAR_32C, 1); + put_u32(out, MAIN_PRIMARY_SCALAR_344, 0xabcd_abcd); + } + // KEXT_PROVEN for G18G too (0xfffffe0008c31780: main+0x3e0=0xff). + put_u32(out, MAIN_PRIMARY_MASK, MAIN_PRIMARY_MASK_VALUE); + put_u32(out, MAIN_CONTROL_RING, profile.control_opening_opcode(role)); + } + (InstanceRole::Secondary, _) => { + // The secondary keeps the two low context-0 values but carries no + // view or region addresses; the values are therefore not + // properties of any region the host allocates. + put_u64(out, MAIN_REGION_VIEWS + 0x08, REGION_VIEW_LOW_ADDRS[0]); + put_u64(out, MAIN_REGION_VIEWS + 0x18, REGION_VIEW_LOW_ADDRS[1]); + put_u32(out, MAIN_SECONDARY_KIND, match profile { + RootProfile::J700G17P => MAIN_SECONDARY_KIND_VALUE, + RootProfile::J813G17G25G76 => 0xc, + // INFERRED: 26A428 stores accel+0x10a74 here (25G76: + // accel+0xed30, measured 0xc on J813). Value not read on J873. + RootProfile::J873G18G26A428 => G18G_26A428_MAIN_SECONDARY_KIND, + }); + if profile == RootProfile::J873G18G26A428 { + // KEXT_PROVEN (26A428 initFirmwareSharedData, g18g_key.c:4464): + // role 1 main+0x481 = FW VA of the perf/policy allocation. + // 25G76 stored it at +0x471 and also wrote an accelerator + // pair at +0x479/+0x481, which 26A428 no longer writes. + put_u64(out, G18G_26A428_MAIN_SECONDARY_POLICY_PTR, + bundle + G18G_26A428_SHARED_LAYOUT.policy as u64); + } else { + // One additional unaligned pointer *into* primary view 2, landing + // five bytes before that view's first populated run. + let extra = bundle + + BUNDLE_VIEW_OFFSETS[SECONDARY_EXTRA_VIEW_INDEX] as u64 + + SECONDARY_EXTRA_VIEW_OFFSET as u64; + put_u64(out, MAIN_SECONDARY_EXTRA_PTR, extra); + } + put_u32(out, MAIN_CONTROL_RING, profile.control_opening_opcode(role)); + } + _ => unreachable!(), + } + Ok(()) +} + +/// Encode target-specific pre-handoff platform policy. M5's native policy is +/// kept separate from the experimental T8140 watchdog and idle overrides. +pub(crate) fn encode_region_c_for_profile( + profile: RootProfile, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != REGION_C_SIZE { + return Err(InitdataError::BufferSize); + } + if profile == RootProfile::J873G18G26A428 { + // Derived from the J813 bytes below through the proven +4 shift. + return encode_g18g_26a428_region_c(out); + } + out.fill(0); + write_runs(out, REGION_C_RUNS); + if profile == RootProfile::J813G17G25G76 { + // Scalars measured before each ASC received its root on two cold + // J813 / 25G76 boots. These are a scoped reference configuration, + // not generic M5 calibration or a power-management qualification. + // The final pair moved by 0x20; leaving the T8140 pair in place would + // initialize unrelated M5 fields. + for (offset, value) in [ + (0x084, 0x0000_5eb0), + (0x088, 0x0000_04b0), + (0x08c, 0x0000_04b0), + (0x098, 0x0000_04b0), + (0x7c4, 0x0000_04e2), + (0x7e0, 0x3f33_3333), + (0x9a8, 0x0000_0333), + (0xe38, 0), + (0xe3c, 0), + (0xe58, 0x0000_0300), + (0xe5c, 0x0000_0100), + ] { + put_u32(out, offset, value); + } + return Ok(()); + } + // regionC+0x9cc is the KSM progress-watchdog threshold for data master 2 + // (compute); the firmware copies it to 0x1778d0 and its handler starts + // `cbz w20 -> ret`, so 0 disables the watchdog. We ship 0x32 (50) here and + // leave the other data master's slot at 0 -- i.e. we arm the watchdog on + // exactly the queue we submit to. When work cannot progress for any other + // reason this turns a stall into a self-sustaining recovery loop. + for (offset, value) in [ + (0x7c, 1), + (0x80, 1), + (0x9c, 0x3000_001d), + (0xa0, 0x3100_0002), + ] { + put_u32(out, offset, value); + } + Ok(()) +} + +/// Encode one 0x80-byte status block in its pre-init state: u32 1 at `+0x04`, +/// everything else zero. `+0x10`/`+0x14` are post-acknowledgement firmware +/// state and must be zero at handoff. +pub(crate) fn encode_status_block(out: &mut [u8]) -> Result<(), InitdataError> { + if out.len() != STATUS_BLOCK_SIZE { + return Err(InitdataError::BufferSize); + } + out.fill(0); + put_u32(out, STATUS_BLOCK_ONE_OFFSET, 1); + Ok(()) +} + +pub(crate) fn encode_secondary_root_extra_1_for_profile( + profile: RootProfile, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != STATUS_BLOCK_SIZE { + return Err(InitdataError::BufferSize); + } + out.fill(0); + write_runs(out, SECONDARY_ROOT_EXTRA_1_RUNS); + // G18G: KEXT_PROVEN identical store geometry for this 0x60 object + // (26A428 vs 25G76 R_60 stores, all at the same offsets); the J813 values + // are carried unchanged (INFERRED, listed in G18G_26A428_UNPROVEN). + if matches!(profile, RootProfile::J813G17G25G76 | RootProfile::J873G18G26A428) { + put_u32(out, 0x10, 2); + } + Ok(()) +} + +/// Recorded T8140 region-C platform tuning constants (values known, meanings +/// not; generated from the hardware-validated `g17p_initdata.py` +/// `REGION_C_CONSTANTS`). 12 sparse runs, 180 bytes total. The final run +/// initializes the byte preceding the host power-assert counter and the +/// counter itself to their native cold value of zero. +pub(crate) const REGION_C_RUNS: &[(usize, &[u8])] = &[ + (0x0024, &[0xb8, 0x0b, 0x00, 0x00]), + ( + 0x0030, + &[ + 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, + 0x00, 0x00, + ], + ), + ( + 0x0054, + &[ + 0xff, 0xff, 0x28, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, + ], + ), + (0x0078, &[0x01, 0x00, 0x00, 0x00]), + ( + 0x0084, + &[ + 0x4e, 0x25, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, + ], + ), + (0x0098, &[0xe8, 0x03, 0x00, 0x00]), + ( + 0x07c4, + &[ + 0xd0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0xcd, 0xcc, 0x4c, 0x3f, 0xcd, 0xcc, + 0x4c, 0x3e, 0x66, 0x66, 0x66, 0x3f, 0xcd, 0xcc, 0xcc, 0x3d, 0x00, 0x00, 0x80, 0x3e, + 0x9a, 0x99, 0x19, 0x3f, 0x66, 0x66, 0x66, 0x3f, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, + ], + ), + ( + 0x0998, + &[ + 0x28, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, + ], + ), + ( + 0x09b8, + &[ + 0x02, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + ], + ), + (0x0e1c, &[0x00, 0x01, 0x00, 0x00]), + (0x0e38, &[0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]), + (0x0e50, &[0x00, 0x00, 0x00, 0x00]), +]; + +pub(crate) const SECONDARY_ROOT_EXTRA_1_RUNS: &[(usize, &[u8])] = &[ + (0x14, &[0x01]), + (0x2c, &[0x01]), + (0x30, &[0x01]), + (0x40, &[0x01]), + (0x4c, &[0x01]), + (0x50, &[0x6a, 0x18]), +]; + +/// Root `+0x00`: u16 {0x04c0, 0x83a0, 0x4339, 0x0c8b}. FW_PROVEN: b000 +/// 0x2164c-0x21660 and b010 0x294f0-0x29504 compare root+0 with this word and +/// abort with "Host and FW Interface is mismatched" otherwise. KEXT_PROVEN: +/// AGXArmFirmware::initFirmwareData (0xfffffe0008c31f6c) writes it to both +/// roots. +pub(crate) const G18G_26A428_INITDATA_VERSION_WORD: u64 = 0x0c8b_4339_83a0_04c0; + +/// Both roots are 0xc8 bytes. FW_PROVEN: each image copies 0xc8 bytes of its +/// root (b000 0x21664-0x216a8) and requires root+0x2c != 0 (b000 0x216ac). +/// Root field offsets are unchanged from 25G76 (KEXT_PROVEN g18g_key.c:3748). +pub(crate) const G18G_26A428_ROOT_SIZE: usize = 0xc8; + +/// `AGXFirmware::allocFirmwareData` allocation-size table, 24 u64. +/// KEXT_PROVEN: 25G76 __const 0xfffffe0007139820. Index names are the +/// `KX_*` constants below. +pub(crate) const KEXT_ALLOCATION_SIZES_25G76: [usize; 24] = [ + 0x2708, 0x0c18, 0x1048, 0x0e10, 0x6a30, 0x0068, 0x0800, 0x0088, 0x1800, 0x04c0, 0x4000, 0x0030, + 0xe440, 0x06a8, 0x0020, 0x01b0, 0x4800, 0x28800, 0x79800, 0x9000, 0x0060, 0x0008, 0x0e78, 0x00e4, +]; + +/// KEXT_PROVEN: 26A428 __const 0xfffffe000714f0d8. Only entries 0 (hw_data), +/// 4 (perf/policy), 12 (status B), 13 (status config) and 22 (region C) +/// differ from 25G76. +pub(crate) const KEXT_ALLOCATION_SIZES_26A428: [usize; 24] = [ + 0x2848, 0x0c18, 0x1048, 0x0e10, 0x7800, 0x0068, 0x0800, 0x0088, 0x1800, 0x04c0, 0x4000, 0x0030, + 0xe730, 0x06d0, 0x0020, 0x01b0, 0x4800, 0x28800, 0x79800, 0x9000, 0x0060, 0x0008, 0x0e80, 0x00e4, +]; + +pub(crate) const KX_HW_DATA: usize = 0; + +pub(crate) const KX_BLOCK_C18: usize = 1; + +pub(crate) const KX_BLOCK_1048: usize = 2; + +pub(crate) const KX_BLOCK_E10: usize = 3; + +pub(crate) const KX_POLICY: usize = 4; + +pub(crate) const KX_BLOCK_68: usize = 5; + +pub(crate) const KX_BLOCK_800: usize = 6; + +pub(crate) const KX_BLOCK_88: usize = 7; + +pub(crate) const KX_DM_RING: usize = 8; + +pub(crate) const KX_MAIN_CONFIG: usize = 9; + +pub(crate) const KX_CONTROL_RING: usize = 10; + +pub(crate) const KX_REGION_C: usize = 22; + +/// `getSizeOfFWBRNTable` returns 0 in both kexts (KEXT_PROVEN +/// 0xfffffe00089ee74c / 0xfffffe0008c507e4). +pub(crate) const KEXT_BRN_TABLE_SIZE: usize = 0; + +/// Both shared allocations are rounded to one 16 KiB page (allocateSharedData). +pub(crate) const KEXT_ALLOCATION_PAGE: usize = 0x4000; + +pub(crate) const SHARED_ALLOCATION_ENTRIES: usize = 25; + +const fn round_up_usize(value: usize, alignment: usize) -> usize { + (value + alignment - 1) & !(alignment - 1) +} + +/// The allocateSharedData packing rule (KEXT_PROVEN 0xfffffe0008c038d8): +/// each next entry starts at `(previous offset + previous size + 0x3f) & !0x3f`. +pub(crate) const fn next_packed_allocation(offset: usize, size: usize) -> usize { + round_up_usize(offset + size, 0x40) +} + +/// Offsets of `sizes` packed by [`next_packed_allocation`], the first at 0. +pub(crate) const fn packed_allocation_offsets(sizes: &[usize; N]) -> [usize; N] { + let mut out = [0usize; N]; + let mut index = 1; + while index < N { + out[index] = next_packed_allocation(out[index - 1], sizes[index - 1]); + index += 1; + } + out +} + +/// The 25 entries of shared allocation #1 in allocation order: hw_data, the +/// 0xc18/0x1048/0xe10 blocks, perf/policy, the 0x68/0x800 blocks, the BRN +/// table, the 0x88 block, twelve data-master rings, then main config and +/// device-control ring for role 0 and for role 1 (KEXT_PROVEN descriptor +/// build, 25G76 g17g_key.c:1224-1310 / 26A428 g18g_key.c:1236-1320). +pub(crate) const fn shared_allocation_sizes(table: &[usize; 24]) -> [usize; SHARED_ALLOCATION_ENTRIES] { + let mut sizes = [0usize; SHARED_ALLOCATION_ENTRIES]; + sizes[0] = table[KX_HW_DATA]; + sizes[1] = table[KX_BLOCK_C18]; + sizes[2] = table[KX_BLOCK_1048]; + sizes[3] = table[KX_BLOCK_E10]; + sizes[4] = table[KX_POLICY]; + sizes[5] = table[KX_BLOCK_68]; + sizes[6] = table[KX_BLOCK_800]; + sizes[7] = KEXT_BRN_TABLE_SIZE; + sizes[8] = table[KX_BLOCK_88]; + let mut ring = 0; + while ring < WORK_CHANNEL_COUNT { + sizes[9 + ring] = table[KX_DM_RING]; + ring += 1; + } + sizes[21] = table[KX_MAIN_CONFIG]; + sizes[22] = table[KX_CONTROL_RING]; + sizes[23] = table[KX_MAIN_CONFIG]; + sizes[24] = table[KX_CONTROL_RING]; + sizes +} + +/// Offsets (from the start of the shared allocation #1 backing) of every +/// object in it. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct SharedClusterLayout { + pub(crate) hw_data: usize, + pub(crate) block_c18: usize, + pub(crate) block_1048: usize, + pub(crate) block_e10: usize, + pub(crate) policy: usize, + pub(crate) block_68: usize, + pub(crate) block_800: usize, + pub(crate) brn_table: usize, + pub(crate) block_88: usize, + /// Data-master rings in allocation order (see [`WORK_CHANNEL_DM_INDEX`]). + pub(crate) dm_rings: [usize; WORK_CHANNEL_COUNT], + pub(crate) main_config: [usize; 2], + pub(crate) control_ring: [usize; 2], + pub(crate) end: usize, + pub(crate) total: usize, +} + +pub(crate) const fn shared_cluster_layout(table: &[usize; 24]) -> SharedClusterLayout { + let sizes = shared_allocation_sizes(table); + let offsets = packed_allocation_offsets(&sizes); + let mut dm_rings = [0usize; WORK_CHANNEL_COUNT]; + let mut ring = 0; + while ring < WORK_CHANNEL_COUNT { + dm_rings[ring] = offsets[9 + ring]; + ring += 1; + } + let end = offsets[24] + sizes[24]; + SharedClusterLayout { + hw_data: offsets[0], + block_c18: offsets[1], + block_1048: offsets[2], + block_e10: offsets[3], + policy: offsets[4], + block_68: offsets[5], + block_800: offsets[6], + brn_table: offsets[7], + block_88: offsets[8], + dm_rings, + main_config: [offsets[21], offsets[23]], + control_ring: [offsets[22], offsets[24]], + end, + total: round_up_usize(end, KEXT_ALLOCATION_PAGE), + } +} + +/// The 26A428 layouts: hw_data 0x2848 at 0, blocks at 0x2880/0x34c0/0x4540, +/// perf/policy 0x7800 at 0x5380, 0x68/0x800 at 0xcb80/0xcc00, BRN and 0x88 at +/// 0xd400, rings from 0xd4c0, main r0 0x1f4c0, control r0 0x1f980, main r1 +/// 0x23980, control r1 0x23e40; status B 0x340, status config 0xea80, status +/// A 0xf180/0xc3440, tail 0x177700/0x177740/0x1777c0. Totals 0x28000 and +/// 0x178000, as in 25G76. +pub(crate) const G18G_26A428_SHARED_LAYOUT: SharedClusterLayout = + shared_cluster_layout(&KEXT_ALLOCATION_SIZES_26A428); + +/// Main `+0x254` views (KEXT_PROVEN 26A428 initFirmwareSharedData: the FW VAs +/// of the 0xc18, 0x1048, 0xe10, 0x68 and 0x800 blocks, this+0x310..0x338). +pub(crate) const G18G_26A428_BUNDLE_VIEW_OFFSETS: [usize; 5] = [ + G18G_26A428_SHARED_LAYOUT.block_c18, + G18G_26A428_SHARED_LAYOUT.block_1048, + G18G_26A428_SHARED_LAYOUT.block_e10, + G18G_26A428_SHARED_LAYOUT.block_68, + G18G_26A428_SHARED_LAYOUT.block_800, +]; + +pub(crate) const G18G_26A428_BUNDLE_VIEW_EXTENTS: [usize; 5] = [ + KEXT_ALLOCATION_SIZES_26A428[KX_BLOCK_C18], + KEXT_ALLOCATION_SIZES_26A428[KX_BLOCK_1048], + KEXT_ALLOCATION_SIZES_26A428[KX_BLOCK_E10], + KEXT_ALLOCATION_SIZES_26A428[KX_BLOCK_68], + KEXT_ALLOCATION_SIZES_26A428[KX_BLOCK_800], +]; + +/// Role-1 main `+0x481`: FW VA of the perf/policy allocation (KEXT_PROVEN). +pub(crate) const G18G_26A428_MAIN_SECONDARY_POLICY_PTR: usize = 0x481; + +/// Role-1 main `+0x300`. INFERRED: the J813 value (26A428 source accel+0x10a74). +pub(crate) const G18G_26A428_MAIN_SECONDARY_KIND: u32 = 0xc; + +/// J873 ADT gpu-num-perf-states. ADT_PROVEN. +pub(crate) const J873_GPU_NUM_PERF_STATES: u32 = 13; + +/// Region-C ADT tunables. KEXT_PROVEN: +0x7c8 = accel+0x106b0 +/// (gpu-idleoff-standby-timer; J813 +0x7c4 carried its ADT 1250) and +0x7e4 = +/// accel+0x106cc (gpu-idleoff-min_conf); ADT_PROVEN values 1500 and 0.8f. +/// +0x9c = this+0xf14 * 100 (25G76 +0x98 = this+0xf40 * 100 = 1200 on J813): +/// INFERRED to be the perf-state count again. +pub(crate) const G18G_26A428_REGION_C_ADT_WORDS: [(usize, u32); 3] = [ + (0x7c8, 1500), + (0x7e4, 0x3f4c_cccd), + (0x09c, J873_GPU_NUM_PERF_STATES * 100), +]; + +/// Stable region-C inputs from the same eight initialization snapshots. +/// +0x38 is the new 26A428 feature bit, no longer a guessed zero. +pub(crate) const G18G_26A428_REGION_C_CAPTURED_WORDS: [(usize, u32); 7] = [ + (0x0038, 1), (0x0088, 0x00008f16), (0x008c, 0x00000514), + (0x0090, 0x00000514), (0x09b0, 0x00000200), + (0x09dc, 0x00000032), (0x0e0c, 0x000000fa), +]; + +/// Encode the G18G region C: the J813 bytes, the 25G76 fields from +0x38 on +/// moved up by 4 (FW_PROVEN), the J873 ADT tunables and stable native J873 +/// inputs. The new +0x38 feature bit (accel+0x6b9 bit 2) is captured as one. +pub(crate) fn encode_g18g_26a428_region_c(out: &mut [u8]) -> Result<(), InitdataError> { + if out.len() != REGION_C_SIZE { + return Err(InitdataError::BufferSize); + } + encode_region_c_for_profile(RootProfile::J813G17G25G76, out)?; + // The J813 object never reaches its 0xe78 end; shifting in place keeps the + // tail zero and needs no second 4 KiB buffer on the kernel stack. + let shifted = KEXT_ALLOCATION_SIZES_25G76[KX_REGION_C]; + if out[shifted..].iter().any(|byte| *byte != 0) { + return Err(InitdataError::BufferSize); + } + out.copy_within(0x38..shifted, 0x3c); + out[0x38..0x3c].fill(0); + for (offset, value) in G18G_26A428_REGION_C_ADT_WORDS { + put_u32(out, offset, value); + } + for (offset, value) in G18G_26A428_REGION_C_CAPTURED_WORDS { + put_u32(out, offset, value); + } + // Idle power-off policy word (Region C +0x30). The firmware loads + // it on every cold wake, which undoes the IdlePowerOff(0) sent once at boot. + // 0 keeps the scheduler idle event from powering the cores down between + // jobs. Measured on the M6: 8.6 percent less time per op. + put_u32(out, 0x30, 0); + Ok(()) +} + +/// FW_PROVEN (jump table 0xfffffc0000006c60, 56 entries from opcode 4): the +/// opening/region-C reload handler (b000 0x3ed0) is reached by 0x15, 0x2a +/// and 0x30. +pub(crate) const G18G_26A428_CONTROL_OPENING_OPCODE_PRIMARY: u32 = 0x15; + +pub(crate) const G18G_26A428_CONTROL_OPENING_OPCODE_SECONDARY: u32 = 0x2a; diff --git a/drivers/gpu/drm/asahi/m5/live_boot.rs b/drivers/gpu/drm/asahi/m5/live_boot.rs new file mode 100644 index 0000000000000..89bf0b08c7124 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/live_boot.rs @@ -0,0 +1,527 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! M5-specific initialization and retained application submission session. +//! DRM admission remains in the device adapter; no G17P manager is selected. + +use super::provider::{validate_provider, ExpectedProvider, G17PAscwrapV6Role, + G17PMailboxProvider, G17PNoRtkitBuffer}; +use crate::{driver::AsahiDrmDevice, m5::resources::M5FirmwareMemory, + m5::fw_msg, mmu, regs}; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use crate::m5::completion::{graphics_pointer_head, MAX_GRAPHICS_GENERATION}; + +/// Application jobs are polled for retirement. A 1 ms step put up to a +/// millisecond of idle GPU after every job, several per video frame. +/// (The first render job keeps 1 ms steps; see submit_application.) +const APPLICATION_POLL_US: i64 = 50; +const APPLICATION_POLLS_PER_MS: u32 = 1000 / APPLICATION_POLL_US as u32; +use kernel::{device::Core, macros::vtable, platform, prelude::*, + soc::apple::rtkit, sync::{aref::ARef, Arc}, time::{delay::fsleep, Delta}}; + +struct M5RoleState { + dev: ARef, + role: usize, + acked: AtomicBool, + crashed: AtomicBool, + events: AtomicU32, +} + +struct M5RtkitOps; + +#[vtable] +impl rtkit::Operations for M5RtkitOps { + type Data = Arc; + type Buffer = G17PNoRtkitBuffer; + + fn recv_message_early( + data: ::Borrowed<'_>, + endpoint: u8, + message: u64, + ) -> bool { + // Both native M5 roles reply with exactly 0x0009000000000000. + if endpoint == 0x20 && message == 0x0009_0000_0000_0000 { + data.acked.store(true, Ordering::Release); + true + } else { + false + } + } + + fn recv_message( + data: ::Borrowed<'_>, + endpoint: u8, + message: u64, + ) { + let ordinal = data.events.fetch_add(1, Ordering::Relaxed); + if ordinal < 8 { + dev_dbg!(data.dev.as_ref(), "M5 message role={} ep={:#x} payload={:#x}\n", + data.role, endpoint, message); + } + } + + fn crashed( + data: ::Borrowed<'_>, + _crashlog: Option<&[u8]>, + ) { + data.crashed.store(true, Ordering::Release); + dev_err!(data.dev.as_ref(), "M5 firmware crashed role={}\n", data.role); + } +} + +struct M5Role { + provider: G17PMailboxProvider, + rtkit: rtkit::RtKit, + state: Arc, + started: bool, +} + +struct M5Session { + roles: [M5Role; 2], + memory: Option>, + uat: Arc, + /// The GPU mappings of both firmware crash log buffers. + _crash_views: [mmu::KernelMapping; 2], + registers: regs::G17Resources, + dev: ARef, +} + +impl M5Session { + fn stop_cpus(&mut self) -> Result { + let mut failure = None; + // Reverse the measured M5 GFX1/GFX start order. + for index in [0, 1] { + if self.roles[index].started { + match self.roles[index].provider.stop_cpu() { + Ok(()) => self.roles[index].started = false, + Err(error) => failure = Some(error), + } + } + } + failure.map_or(Ok(()), Err) + } + + fn initialize(&mut self) -> Result { + self.registers.m5_match_pmgr_boot_control()?; + for index in [1, 0] { + let role = &mut self.roles[index]; + role.provider.start_cpu()?; + role.started = true; + Pin::new(&mut role.rtkit).boot()?; + dev_dbg!(self.dev.as_ref(), "M5_INIT role={} rtkit-ready\n", index); + } + // These helpers operate only on the proven shared dual-root layout; + // the Neo-specific contexts, metrics and manager remain unselected. + let roots = self.uat.adopt_firmware_root_entries()?; + let timestamp: u64; + // SAFETY: Read-only architectural counter, available on this target. + unsafe { core::arch::asm!("mrs {value}, cntvct_el0", value = out(reg) timestamp, + options(nomem, nostack, preserves_flags)); } + self.memory = Some(M5FirmwareMemory::new_with_uat( + &self.dev, self.uat.clone(), timestamp)?); + self.uat.confirm_firmware_root_entries(roots)?; + self.uat.mirror_secondary_root()?; + dev_dbg!(self.dev.as_ref(), "M5_INIT retained memory graph mapped\n"); + self.registers.enable_g17_gating()?; + + // M5's own trace publishes and ACKs GFX1 first (133/137), then GFX + // (160/164). The Neo's opposite ordering is not used here. + for index in [1, 0] { + let address = self.memory.as_ref().ok_or(EIO)?.root(index == 1); + let message = fw_msg::encode_initdata_doorbell(address).map_err(|_| EINVAL)?; + let role = &mut self.roles[index]; + Pin::new(&mut role.rtkit).start_endpoint(0x20)?; + Pin::new(&mut role.rtkit).start_endpoint(0x21)?; + Pin::new(&mut role.rtkit).send_message(0x20, message)?; + dev_dbg!(self.dev.as_ref(), "M5_INIT role={} published root={:#x}\n", index, address); + for _ in 0..200 { + if self.memory.as_mut().ok_or(EIO)?.drain_reports(&self.dev)? { + return Err(EIO); + } + if role.state.crashed.load(Ordering::Acquire) { + return Err(EIO); + } + if role.state.acked.load(Ordering::Acquire) { + break; + } + fsleep(Delta::from_millis(10)); + } + if !role.state.acked.load(Ordering::Acquire) { + return Err(ETIMEDOUT); + } + dev_dbg!(self.dev.as_ref(), "M5_INIT role={} initdata-ack\n", index); + } + if self.roles.iter().any(|role| role.state.crashed.load(Ordering::Acquire)) { + return Err(EIO); + } + self.retire_openings() + } + + fn install_graphics_queues(&mut self) -> Result { + let memory = self.memory.as_mut().ok_or(EIO)?; + dev_dbg!(self.dev.as_ref(), "M5_GRAPHICS install before counters={:x?} registration={:x?}\n", + memory.graphics_status()?, memory.graphics_installation_status()?); + memory.publish_graphics_install()?; + Pin::new(&mut self.roles[0].rtkit).send_message(0x21, 0x0083_0000_0000_000a)?; + for poll in 0..1000 { + if memory.drain_reports(&self.dev)? { return Err(EIO); } + if self.roles.iter().any(|role| role.state.crashed.load(Ordering::Acquire)) { + return Err(EIO); + } + let (outer, inner, _) = memory.graphics_status()?; + if outer == [2; 3] && inner == [[1; 3]; 2] + && memory.graphics_queues_installed()? { + dev_dbg!(self.dev.as_ref(), "M5_GRAPHICS installed TA/fragment queues; registration={:x?}; no draws published\n", + memory.graphics_installation_status()?); + return Ok(()); + } + if [0, 100].contains(&poll) { + dev_dbg!(self.dev.as_ref(), "M5_GRAPHICS install poll={} counters={:x?} registration={:x?}\n", + poll, memory.graphics_status()?, memory.graphics_installation_status()?); + } + fsleep(Delta::from_millis(1)); + } + dev_err!(self.dev.as_ref(), "M5_GRAPHICS install timeout counters={:x?} registration={:x?}\n", + memory.graphics_status()?, memory.graphics_installation_status()?); + Err(ETIMEDOUT) + } + + fn retire_idle_policy(&mut self) -> Result { + let memory = self.memory.as_mut().ok_or(EIO)?; + // Retire the idle-policy request. + memory.publish_idle_wake()?; + Pin::new(&mut self.roles[0].rtkit).send_message(0x21, 0x0084_0000_0000_0011)?; + for _ in 0..1000 { + if memory.drain_reports(&self.dev)? { return Err(EIO); } + if self.roles.iter().any(|role| role.state.crashed.load(Ordering::Acquire)) { + dev_err!(self.dev.as_ref(), "M5: firmware crashed retiring the idle policy\n"); + return Err(EIO); + } + if memory.control_counters()? == [[2; 3], [1; 3]] { + return Ok(()); + } + fsleep(Delta::from_millis(1)); + } + dev_err!(self.dev.as_ref(), "M5: idle policy not retired, counters={:?}\n", + memory.control_counters()?); + Err(ETIMEDOUT) + } + + fn retire_openings(&mut self) -> Result { + let mut counters = self.memory.as_mut().ok_or(EIO)?.control_counters()?; + dev_dbg!(self.dev.as_ref(), "M5_OPEN before power-transition-end {:?}\n", counters); + // M5's own cold trace sends one 0x89 to GFX, then GFX1 (events + // 167/171), immediately after the two initdata ACKs. No other control + // record or work item is published in this bounded experiment. + for index in [0, 1] { + Pin::new(&mut self.roles[index].rtkit) + .send_message(0x21, fw_msg::encode_power_transition_end())?; + } + for _ in 0..1000 { + if self.memory.as_mut().ok_or(EIO)?.drain_reports(&self.dev)? { + return Err(EIO); + } + if self.roles.iter().any(|role| role.state.crashed.load(Ordering::Acquire)) { + return Err(EIO); + } + counters = self.memory.as_mut().ok_or(EIO)?.control_counters()?; + if counters == [[1; 3]; 2] { + dev_dbg!(self.dev.as_ref(), "M5_OPEN both native control openings retired {:?}\n", counters); + return Ok(()); + } + fsleep(Delta::from_millis(1)); + } + dev_err!(self.dev.as_ref(), "M5_OPEN control openings did not retire {:?}\n", counters); + Err(ETIMEDOUT) + } + +} + +/// Sizes of the GFX and GFX1 `__DATA` segments the 25G76 firmware runs with. +const DATA_SIZES: [u64; 2] = [0x134000, 0x130000]; +/// The firmware's crash log buffer, at this offset of each `__DATA` segment. +const CRASH_LOG_OFFSET: u64 = 0xa0000; +const CRASH_LOG_SIZE: usize = 0x8000; + +/// Creates the UAT both firmware instances share, as the A18 Pro's: each instance publishes +/// its own kernel root, the secondary one 0x40000 into `pagetables`. Each instance asks for +/// its crash log at the GPU address of `__DATA` + 0xa0000 truncated to 40 bits, which is +/// mapped here, before either instance starts. +fn new_uat(dev: &AsahiDrmDevice) -> Result<(Arc, [mmu::KernelMapping; 2])> { + let node = dev.as_ref().as_ref().of_node().ok_or(EINVAL)?; + let mut crash_logs = [0u64; 2]; + for (index, name) in [c"gfx-data", c"gfx1-data"].into_iter().enumerate() { + let region = node.reserved_mem_region_to_resource_byname(name)?; + if region.size() != DATA_SIZES[index] || region.start() & (mmu::UAT_PGSZ as u64 - 1) != 0 + { + return Err(EINVAL); + } + crash_logs[index] = region.start() + CRASH_LOG_OFFSET; + } + let uat = Arc::new( + mmu::Uat::new( + dev.into(), + mmu::UatGeometry { ias: 42, oas: 42 }, + false, + mmu::UatFirmware::PublishedRoots { secondary_root_offset: Some(0x40000) }, + mmu::UatQuirks::DEFAULT, + )?, + GFP_KERNEL, + )?; + let map = |pa: u64| { + uat.kernel_lower_vm().map_io( + dev.as_ref().as_ref(), + pa & ((1u64 << 40) - 1), + pa.try_into()?, + CRASH_LOG_SIZE, + mmu::PROT_FW_SHARED_RW, + ) + }; + let views = [map(crash_logs[0])?, map(crash_logs[1])?]; + Ok((uat, views)) +} + +pub(crate) struct M5Runtime { + session: Option>, + application: bool, + faulted: bool, + application_generation: u32, + application_compute_generation: u32, +} + +impl M5Runtime { + fn prepare( + pdev: &platform::Device>, + dev: ARef, + registers: regs::G17Resources, + ) -> Result { + let gfx = G17PMailboxProvider::get(pdev.as_ref(), 0)?; + let gfx1 = G17PMailboxProvider::get(pdev.as_ref(), 1)?; + for (provider, expected) in [ + (&gfx, ExpectedProvider { role: G17PAscwrapV6Role::Gfx, + wrapper: (0x582600000, 0x88000), iop_vbar: (0x582050000, 8) }), + (&gfx1, ExpectedProvider { role: G17PAscwrapV6Role::Gfx1, + wrapper: (0x582e00000, 0x88000), iop_vbar: (0x582850000, 8) }), + ] { + validate_provider(provider, expected)?; + provider.require_safe_cpu_lifecycle()?; + } + let (uat, crash_views) = new_uat(&dev)?; + let make_role = |index, provider| -> Result { + let state = Arc::new(M5RoleState { dev: dev.clone(), role: index, + acked: AtomicBool::new(false), crashed: AtomicBool::new(false), + events: AtomicU32::new(0) }, GFP_KERNEL)?; + let rtkit = rtkit::RtKit::::new_with_firmware_crashlog( + dev.as_ref().as_ref(), None, index, state.clone())?; + Ok(M5Role { provider, rtkit, state, started: false }) + }; + let session = KBox::new(M5Session { + roles: [make_role(0, gfx)?, make_role(1, gfx1)?], + memory: None, uat, _crash_views: crash_views, registers, dev, + }, GFP_KERNEL)?; + // From this point every path returns the retained platform owner, + // even when firmware rejects the graph. Failed probe unwinding must + // never release UAT or transports beneath a running firmware CPU. + // Keep callback code resident even if a failed stop retains owners. + // This explicit RAM-boot experiment is released by reboot only. + unsafe { kernel::bindings::__module_get((*kernel::module::this_module::()).as_ptr()); } + Ok(Self { session: Some(session), application: false, faulted: false, + application_generation: 0, application_compute_generation: 0 }) + } + + /// Boot without a native program or job graph and leave both processors + /// running for explicit application submissions. This does not register + /// a render node or claim that Mesa command translation is complete. + pub(crate) fn start_application( + pdev: &platform::Device>, dev: ARef, registers: regs::G17Resources, + ) -> Result { + // Periodic power/submission traces need continuous draining while + // the session idles. Recovery bit 9 emits only on a fault, which the + // synchronous submit loop drains before retaining a failed graph. + if crate::module_parameters::m5_fw_trace.value() & !0x200 != 0 { + return Err(EINVAL); + } + let mut owner = Self::prepare(pdev, dev, registers)?; + owner.application = true; + let result = (|| { + let session = owner.session.as_mut().ok_or(EIO)?; + session.initialize()?; + session.retire_idle_policy()?; + Ok(()) + })(); + if let Err(error) = result { + owner.faulted = true; + return Err(error); + } + dev_info!(pdev.as_ref(), "M5: GPU firmware 25G76 running\n"); + Ok(owner) + } + + pub(crate) fn new_user_vm(&self, id: u64, kernel_range: core::ops::Range) -> Result { + if !self.application || self.is_crashed() { return Err(ENODEV); } + crate::m5::vm_layout::compact_range(&kernel_range).ok_or(EINVAL)?; + self.session.as_ref().ok_or(EIO)?.uat.new_vm(id, kernel_range)?.with_status() + } + + pub(crate) fn is_crashed(&self) -> bool { + self.faulted || self.session.as_ref().is_none_or(|session| + session.roles.iter().any(|role| role.state.crashed.load(Ordering::Acquire))) + } + + /// The adapter serializes this call and validates the translated command + /// plus every user mapping before entry. Return success only after paired + /// queue retirement, scheduler unlink, stamps and firmware notifications. + /// A failed published job retains and quarantines its VM until reboot. + #[allow(clippy::too_many_arguments)] + pub(crate) fn submit_application( + &mut self, vm: &mmu::Vm, parameters: crate::m5::render_desc::G17pRenderParameters, + controls: crate::m5::render::M5RenderControls, clusters: u32, + usc_required: [u64; 2], + ) -> Result { + if !self.application || self.is_crashed() { return Err(ENODEV); } + // Reuse retired ring storage while keeping completion stamps unique. + if self.application_generation >= MAX_GRAPHICS_GENERATION { return Err(EBUSY); } + let generation = self.application_generation + 1; + let session = self.session.as_deref_mut().ok_or(EIO)?; + if generation == 1 { + session.memory.as_mut().ok_or(EIO)?.initialize_application_graphics( + &session.dev, vm, parameters, controls, clusters, usc_required)?; + } + // From installation onward, even a failed mailbox send can have made + // memory visible to firmware. Never unwind or recycle the job graph. + self.application_generation = generation; + let result = (|| { + if generation == 1 { session.install_graphics_queues()?; } + let memory = session.memory.as_mut().ok_or(EIO)?; + if generation == 1 { + memory.publish_graphics_job()?; + } else { + memory.publish_next_application_job(&session.dev, vm, parameters, controls, + clusters, usc_required, generation)?; + } + Pin::new(&mut session.roles[0].rtkit).send_message(0x21, 0x0083_0000_0000_000a)?; + for _ in 0..10000 * APPLICATION_POLLS_PER_MS { + if memory.drain_reports(&session.dev)? + || session.roles.iter().any(|role| role.state.crashed.load(Ordering::Acquire)) { + return Err(EIO); + } + let (outer, inner, _) = memory.graphics_status()?; + let completion = memory.graphics_completion()?; + if outer == [memory.application_outer_head(); 3] + && inner == [[graphics_pointer_head(generation); 3]; 2] + && M5FirmwareMemory::graphics_pair_complete(completion, generation) { + dev_dbg!(session.dev.as_ref(), + "M5_APPLICATION generation={} completed; both queues retired\n", + generation); + return Ok(completion); + } + // The first job also installs the queues; polling it this + // often met a firmware recovery on its fragment queue. + fsleep(Delta::from_micros(if generation == 1 { 1000 } else { APPLICATION_POLL_US })); + } + Err(ETIMEDOUT) + })(); + if let Err(error) = result { + if let Some(memory) = session.memory.as_mut() { + for _ in 0..4 { let _ = memory.drain_reports(&session.dev); } + dev_err!(session.dev.as_ref(), + "M5_APPLICATION failed graph counters={:x?} completion={:x?}\n", + memory.graphics_status(), memory.graphics_completion()); + } + self.faulted = true; + if let Some(status) = vm.status() { status.record(error); } + if let Some(memory) = &session.memory { memory.quarantine_graphics(); } + // A successful stop request alone does not prove a halt. Keep + // the full session even after this best-effort stop succeeds. + let stopped = session.stop_cpus(); + dev_err!(session.dev.as_ref(), + "M5_APPLICATION submission failed {:?}; stop={:?}; VM and firmware owners retained\n", + error, stopped); + } + result + } + + /// Execute a compute command in the already retained application VM. + /// Installation, dispatch and retirement are separate firmware transitions. + /// The first submission installs queue 12 and dispatches generation 1; + /// every later one reuses that owner and dispatches the next generation, + /// as submit_application() does for the graphics pair. + pub(crate) fn submit_application_compute(&mut self, vm: &mmu::Vm, + command: &crate::m5::command::TranslatedComputeCommand) -> Result { + if !self.application || self.is_crashed() || self.application_generation == 0 { + return Err(ENOTSUPP); + } + if self.application_compute_generation >= MAX_GRAPHICS_GENERATION { + return Err(EBUSY); + } + let generation = self.application_compute_generation + 1; + let session = self.session.as_deref_mut().ok_or(EIO)?; + if generation == 1 { + session.memory.as_mut().ok_or(EIO)?.initialize_application_compute( + &session.dev, vm, command, self.application_generation)?; + } else { + session.memory.as_mut().ok_or(EIO)?.prepare_next_application_compute( + &session.dev, vm, command, generation)?; + } + // The owner is retained from installation onward. Even a failed mailbox + // send can follow firmware seeing the new producer, so never unwind. + self.application_compute_generation = generation; + let result = (|| { + let memory = session.memory.as_mut().ok_or(EIO)?; + // Installation is published once; the dispatch record every time. + let stages: &[bool] = if generation == 1 { &[false, true] } else { &[true] }; + for &dispatch in stages { + memory.publish_application_compute(dispatch, generation)?; + Pin::new(&mut session.roles[0].rtkit) + .send_message(0x21, 0x0083_0000_0000_000a)?; + let mut retired = false; + for _ in 0..if dispatch { 10000 } else { 1000 } * APPLICATION_POLLS_PER_MS { + if memory.drain_reports(&session.dev)? + || session.roles.iter().any(|role| role.state.crashed.load(Ordering::Acquire)) { + return Err(EIO); + } + let (outer, _, _) = memory.graphics_status()?; + if outer == [memory.application_outer_head(); 3] + && if dispatch { memory.application_compute_complete(generation)? } + else { memory.application_compute_installed()? } { + retired = true; + break; + } + fsleep(Delta::from_micros(APPLICATION_POLL_US)); + } + if !retired { return Err(ETIMEDOUT); } + dev_dbg!(session.dev.as_ref(), + "M5_APPLICATION_COMPUTE {} generation={} queue=12 outer={} status={:x?}\n", + if dispatch { "completed" } else { "installed" }, generation, + memory.application_outer_head(), memory.application_compute_status()); + } + Ok(()) + })(); + if let Err(error) = result { + self.faulted = true; + if let Some(status) = vm.status() { status.record(error); } + if let Some(memory) = session.memory.as_mut() { + for _ in 0..4 { let _ = memory.drain_reports(&session.dev); } + memory.quarantine_graphics(); + dev_err!(session.dev.as_ref(), + "M5_APPLICATION_COMPUTE failed {:?}; outer/graphics={:x?} compute={:x?}\n", + error, memory.graphics_status(), memory.application_compute_status()); + } + let stopped = session.stop_cpus(); + dev_err!(session.dev.as_ref(), + "M5_APPLICATION_COMPUTE stop={:?}; VM and owners retained until reboot\n", stopped); + } + result + } +} + +impl Drop for M5Runtime { + fn drop(&mut self) { + if let Some(mut session) = self.session.take() { + if let Some(memory) = &session.memory { memory.quarantine_graphics(); } + let stopped = session.stop_cpus(); + dev_dbg!(session.dev.as_ref(), + "M5 session release requested; stop={:?}; halt unqualified, owners retained until reboot\n", + stopped); + core::mem::forget(session); + } + } +} diff --git a/drivers/gpu/drm/asahi/m5/mapped.rs b/drivers/gpu/drm/asahi/m5/mapped.rs new file mode 100644 index 0000000000000..2ccc37b82531b --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/mapped.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Kernel-owned, write-combined GEM objects mapped at one GPU address. + +use core::ops::Range; +use kernel::prelude::*; + +use crate::{driver::AsahiDrmDevice, gem, mmu}; + +/// A zeroed, write-combined kernel object and its owning GPU mapping. +pub(crate) struct MappedObject { + _mapping: mmu::KernelMapping, + object: gem::ObjectRef, + iova: u64, + /// Size of the object in bytes, as requested. + pub(crate) logical_size: usize, + /// The VM of the owning mapping. + home: u64, +} + +impl MappedObject { + fn new_object(dev: &AsahiDrmDevice, size: usize) -> Result { + let mut object = gem::new_kernel_object_wc(dev, size)?; + let len = object.size(); + let vmap = object.vmap()?; + // SAFETY: the vmap covers the whole page-rounded allocation. + unsafe { core::ptr::write_bytes(vmap.addr.cast::(), 0, len) }; + Ok(object) + } + + fn from_mapping( + object: gem::ObjectRef, vm: &mmu::Vm, mapping: mmu::KernelMapping, size: usize, + ) -> Self { + let iova = mapping.iova(); + Self { _mapping: mapping, object, iova, logical_size: size, home: vm.id() } + } + + /// Maps a new object of `size` bytes at `address`. + pub(crate) fn new_wc_at( + dev: &AsahiDrmDevice, vm: &mmu::Vm, address: u64, size: usize, prot: mmu::Prot, + ) -> Result { + let mut object = Self::new_object(dev, size)?; + let mapping = object.map_at(vm, address, prot, false)?; + Ok(Self::from_mapping(object, vm, mapping, size)) + } + + /// Maps a new object of `size` bytes at a free address in `range`. + pub(crate) fn new_wc_in_range( + dev: &AsahiDrmDevice, vm: &mmu::Vm, range: Range, size: usize, alignment: u64, + prot: mmu::Prot, + ) -> Result { + let mut object = Self::new_object(dev, size)?; + let mapping = object.map_into_range(vm, range, alignment, prot, true)?; + Ok(Self::from_mapping(object, vm, mapping, size)) + } + + /// As [`Self::new_wc_in_range`], followed by `guard_pages` unmapped pages. + pub(crate) fn new_wc_in_range_with_guards( + dev: &AsahiDrmDevice, vm: &mmu::Vm, range: Range, size: usize, alignment: u64, + prot: mmu::Prot, guard_pages: usize, + ) -> Result { + let object = Self::new_object(dev, size)?; + let guard = guard_pages.checked_mul(mmu::UAT_PGSZ).ok_or(EOVERFLOW)?; + let mapping = vm.map_in_range_with_guard_size( + &object.gem, 0..object.size(), alignment, range, prot, guard, + )?; + Ok(Self::from_mapping(object, vm, mapping, size)) + } + + /// Maps this object again at `address` of `vm`. + pub(crate) fn map_alias_at( + &mut self, vm: &mmu::Vm, address: u64, prot: mmu::Prot, + ) -> Result { + self.object.map_at(vm, address, prot, false) + } + + /// Maps this object at its own address in another client VM, followed by `guard_pages` + /// unmapped pages. In the VM of the owning mapping, where the object already is at that + /// address, there is nothing to map. + pub(crate) fn map_alias_at_with_guards( + &mut self, vm: &mmu::Vm, address: u64, prot: mmu::Prot, guard_pages: usize, + ) -> Result> { + if vm.id() == self.home { + return if address == self.iova { Ok(None) } else { Err(EINVAL) }; + } + let guard = guard_pages.checked_mul(mmu::UAT_PGSZ).ok_or(EOVERFLOW)?; + vm.map_at_with_guard_size(address, self.object.size(), &self.object.gem, prot, guard) + .map(Some) + } + + /// GPU address of the object. + pub(crate) fn iova(&self) -> u64 { + self.iova + } + + /// Runs `f` on the CPU view of the object's `size` bytes. + pub(crate) fn with_bytes_mut(&mut self, f: impl FnOnce(&mut [u8]) -> Result) -> Result { + let size = self.logical_size; + let vmap = self.object.vmap()?; + // SAFETY: the vmap covers the whole allocation, which is at least `size` bytes, and + // `&mut self` excludes other CPU views made through this object. + let bytes = unsafe { core::slice::from_raw_parts_mut(vmap.addr.cast::(), size) }; + f(bytes) + } + + fn offset(&self, address: u64, width: usize) -> Result { + let offset: usize = address.checked_sub(self.iova).ok_or(EINVAL)?.try_into()?; + let end = offset.checked_add(width).ok_or(EINVAL)?; + if end > self.logical_size { + return Err(EINVAL); + } + Ok(offset) + } + + /// Reads the little-endian word at GPU address `address` (any alignment). + pub(crate) fn read_u32(&mut self, address: u64) -> Result { + let offset = self.offset(address, 4)?; + self.with_bytes_mut(|bytes| { + Ok(u32::from_le_bytes(bytes[offset..offset + 4].try_into().map_err(|_| EINVAL)?)) + }) + } + + /// Reads the little-endian double word at GPU address `address` (any alignment). + pub(crate) fn read_u64(&mut self, address: u64) -> Result { + let offset = self.offset(address, 8)?; + self.with_bytes_mut(|bytes| { + Ok(u64::from_le_bytes(bytes[offset..offset + 8].try_into().map_err(|_| EINVAL)?)) + }) + } + + /// Writes the naturally aligned little-endian word at GPU address `address` with one store. + pub(crate) fn write_u32(&mut self, address: u64, value: u32) -> Result { + let offset = self.offset(address, 4)?; + if offset % 4 != 0 { + return Err(EINVAL); + } + self.with_bytes_mut(|bytes| { + // SAFETY: checked bounds and natural alignment. + unsafe { + core::ptr::write_volatile(bytes.as_mut_ptr().add(offset).cast::(), value.to_le()) + }; + Ok(()) + }) + } +} diff --git a/drivers/gpu/drm/asahi/m5/mod.rs b/drivers/gpu/drm/asahi/m5/mod.rs new file mode 100644 index 0000000000000..96beaac4391f4 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/mod.rs @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Apple M5 (T8142, G17G) GPU support for the 25G76 firmware (RTKit-3255.160.4). +//! +//! The M5 has two GPU coprocessors, GFX and GFX1, as the A18 Pro does. The boot loader (aura) +//! loads their firmware, checks both loaded TEXT images against the 25G76 build and says so +//! in `/chosen/aurora,m5-gpu-firmware-profile`. The firmware interface is HAL300 and differs +//! from the 26A428 and 25G83 builds the shared G17 code runs, so this backend builds its own +//! initialization graph ([`initdata`], [`resources`]) and talks to the firmware over its own +//! channels ([`channel`], [`sksm`], [`completion`]). +//! +//! # Plugging into the shared driver +//! +//! - `ProbeConfig::M5` (`apple,agx-t8142`) calls [`probe`], which starts both coprocessors +//! ([`live_boot`]) and returns a [`Gpu`] implementing [`crate::gpu::Gpu`]. +//! - The UAT is the shared [`crate::mmu::Uat`] with published roots, as on the A18 Pro, plus +//! [`crate::mmu::M5ExecutionContext`] for application contexts. User VMs carry a status and +//! a job lifetime, and the backend uses the tracked submission model of `file.rs`. +//! - The UAPI is the shared one. The backend reports `VM_STATUS` (with its mirror) and +//! `SOFT_FAULTS`, and one hardware command per submission. +//! +//! # Submission +//! +//! One render pair (TA and fragment queues) and one compute queue serve every client: the +//! queues are installed by the first render and handed from client VM to client VM, with +//! the driver's pools aliased at the same addresses in each. A submission is published, +//! then polled to retirement before the ioctl returns, so there is one job in flight. +//! Renders and compute are admitted only within the state the firmware programs have been +//! verified with ([`render`], [`compute`]); anything else is refused with `ENOTSUPP` +//! before it reaches the firmware. +//! +//! # Failures +//! +//! There is no recovery yet. A job that fails or does not retire marks its VM, stops both +//! coprocessors and retains every firmware-visible object until reboot; the device is lost +//! for all clients. The module stays loaded for the same reason. + +mod channel; +mod command; +mod completion; +mod compute; +mod drm; +mod fw_msg; +mod initdata; +mod live_boot; +mod mapped; +mod provider; +mod render; +mod render_desc; +mod render_target; +mod resources; +mod sksm; +mod submission; +mod vm_layout; + +use kernel::{device::Core, of, platform, prelude::*, sync::Arc}; + +use crate::{driver::AsahiDrmDevice, regs}; + +pub(crate) use drm::M5DrmGpu as Gpu; + +/// The firmware profile aura publishes in `/chosen/aurora,m5-gpu-firmware-profile` after it +/// checked both loaded TEXT images against the exact 25G76 build. +const FIRMWARE_PROFILE: &[u8] = b"M5-RTKit-3255.160.4.release\0"; + +/// Starts both firmware instances and returns the GPU, ready for DRM registration. +pub(crate) fn probe( + pdev: &platform::Device>, + dev: &AsahiDrmDevice, + res: regs::G17Resources, +) -> Result> { + let chosen = of::chosen().ok_or(ENODEV)?; + let profile: KVec = chosen.get_property(c"aurora,m5-gpu-firmware-profile")?; + if profile.as_slice() != FIRMWARE_PROFILE { + dev_err!(pdev.as_ref(), "M5: GPU firmware profile not published or not 25G76\n"); + return Err(ENODEV); + } + let id = res.get_g17_id()?; + let cores: u32 = id.core_masks.iter().map(|mask| mask.count_ones()).sum(); + // M5 GPUs have 10 cores, or 8 with two fused off (MacBook Air). + if id.family != 0xb || id.num_dies != 1 || !matches!(cores, 8 | 10) { + dev_err!(pdev.as_ref(), "M5: unexpected GPU family {:#x}, {} dies, {} cores\n", + id.family, id.num_dies, cores); + return Err(ENODEV); + } + // Before the session: a CLPC that has not probed yet defers the GPU. + let clpc = drm::M5ClpcInput::new(pdev.as_ref())?; + let runtime = live_boot::M5Runtime::start_application(pdev, dev.into(), res)?; + let runtime = Arc::pin_init(kernel::new_mutex!(runtime), GFP_KERNEL)?; + Ok(Arc::new(Gpu::new(runtime, id, clpc), GFP_KERNEL)?) +} diff --git a/drivers/gpu/drm/asahi/m5/provider.rs b/drivers/gpu/drm/asahi/m5/provider.rs new file mode 100644 index 0000000000000..d54a591f85448 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/provider.rs @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The GFX and GFX1 ASCWrap v6 mailbox providers, as seen by the M5 firmware session. + +use core::mem::MaybeUninit; + +use kernel::{ + bindings, + error::{from_err_ptr, to_result}, + io::{IoSysMap, Region}, + prelude::*, + soc::apple::rtkit, +}; + +use crate::mmu; + +const G17P_CRASHLOG_MAX_BYTES: usize = 256 * 1024; + +const G17P_RTKIT_UAT_DVA_MASK: u64 = (1u64 << 40) - 1; + +/// Module-local, read-only view of one existing ASCWrap mailbox provider. +/// +/// The C provider owns the mapping and all lifecycle transitions. This view +/// neither maps an alias nor changes callback ownership; it only borrows the +/// provider's established mailbox-register pointer for two control reads. +pub(super) struct G17PMailboxProvider { + mbox: *mut bindings::apple_mbox, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(super) enum G17PAscwrapV6Role { + Gfx, + Gfx1, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(super) struct G17PAscwrapV6Lifecycle { + role: G17PAscwrapV6Role, + wrapper: (u64, u64), + iop_vbar: (u64, u64), + missing: u32, +} + +impl G17PMailboxProvider { + + pub(super) fn get(dev: &kernel::device::Device, index: usize) -> Result { + // SAFETY: `dev` is live and apple_mbox_get() establishes a device link + // to keep the resolved provider alive for this consumer. + let mbox = unsafe { + from_err_ptr(bindings::apple_mbox_get( + dev.as_raw(), + index.try_into()?, + ))? + }; + Ok(Self { mbox }) + } + + pub(super) fn lifecycle(&self) -> Result { + let mut raw = MaybeUninit::::uninit(); + // SAFETY: `self.mbox` is the live provider returned by + // apple_mbox_get() and `raw` points to writable storage. + to_result(unsafe { + bindings::apple_mbox_ascwrap_v6_get_lifecycle(self.mbox, raw.as_mut_ptr()) + })?; + // SAFETY: the successful C call initialized every field. + let raw = unsafe { raw.assume_init() }; + let role = match raw.role as u32 { + 1 => G17PAscwrapV6Role::Gfx, + 2 => G17PAscwrapV6Role::Gfx1, + _ => return Err(EINVAL), + }; + Ok(G17PAscwrapV6Lifecycle { + role, + wrapper: (raw.wrapper_start, raw.wrapper_size), + iop_vbar: (raw.iop_vbar_start, raw.iop_vbar_size), + missing: raw.missing, + }) + } + + pub(super) fn require_safe_cpu_lifecycle(&self) -> Result { + // SAFETY: this is a capability check on the live provider pointer. + to_result(unsafe { + bindings::apple_mbox_ascwrap_v6_require_safe_cpu_lifecycle(self.mbox) + }) + } + + pub(super) fn start_cpu(&self) -> Result { + // SAFETY: lifecycle serialization and MMIO ownership remain in C. + to_result(unsafe { bindings::apple_mbox_ascwrap_v6_start_cpu(self.mbox) }) + } + + pub(super) fn stop_cpu(&self) -> Result { + // SAFETY: lifecycle serialization and MMIO ownership remain in C. + to_result(unsafe { bindings::apple_mbox_ascwrap_v6_stop_cpu(self.mbox) }) + } + +} + +unsafe impl Send for G17PMailboxProvider {} + +unsafe impl Sync for G17PMailboxProvider {} + +pub(super) const fn g17p_rtkit_uat_address(dva: u64) -> u64 { + dva & G17P_RTKIT_UAT_DVA_MASK +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u32)] +pub(super) enum G17PProcessor { + Gfx = 0, + Gfx1 = 1, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(super) struct G17PFirmwareCrashBuffer { + dva: u64, + size: usize, +} + +impl G17PProcessor { + + pub(super) const fn firmware_crash_buffer(self) -> G17PFirmwareCrashBuffer { + // Both endpoint-1 buffer requests are stable across the retained + // G17P captures. Message 0x0010810001e1c000 decodes to the primary + // DVA below and size 0x8000; GFX1 advertises the second DVA with the + // same size. + match self { + Self::Gfx => G17PFirmwareCrashBuffer { + dva: 0x100_01e1_c000, + size: 0x8000, + }, + Self::Gfx1 => G17PFirmwareCrashBuffer { + dva: 0x100_01f5_0000, + size: 0x8000, + }, + } + } +} + +pub(super) const fn bounded_crashlog_size(size: usize) -> usize { + if size < G17P_CRASHLOG_MAX_BYTES { + size + } else { + G17P_CRASHLOG_MAX_BYTES + } +} + +const _: () = { + assert!(bounded_crashlog_size(0) == 0); + assert!(bounded_crashlog_size(4096) == 4096); + assert!(bounded_crashlog_size(G17P_CRASHLOG_MAX_BYTES + 1) == G17P_CRASHLOG_MAX_BYTES); + let gfx = G17PProcessor::Gfx.firmware_crash_buffer(); + let gfx1 = G17PProcessor::Gfx1.firmware_crash_buffer(); + assert!(gfx.dva == 0x100_01e1_c000 && gfx1.dva == 0x100_01f5_0000); + assert!(g17p_rtkit_uat_address(gfx.dva) == 0x01e1_c000); + assert!(g17p_rtkit_uat_address(gfx1.dva) == 0x01f5_0000); + assert!(gfx.size == 0x8000 && gfx1.size == 0x8000); + assert!(gfx.dva & (mmu::UAT_PGSZ as u64 - 1) == 0); + assert!(gfx1.dva & (mmu::UAT_PGSZ as u64 - 1) == 0); + assert!(gfx.dva + gfx.size as u64 <= 1u64 << 42); + assert!(gfx1.dva + gfx1.size as u64 <= 1u64 << 42); +}; + +/// Active G17P boot does not ask Rust to back system-endpoint buffers. The +/// generic RTKit core uses its coherent-DMA fallback when these callbacks are +/// absent. +pub(super) struct G17PNoRtkitBuffer; + +impl rtkit::Buffer for G17PNoRtkitBuffer { + fn iova(&self) -> Result { + Err(ENOTSUPP) + } + + fn buf(&mut self) -> Result> { + Err(ENOTSUPP) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(super) struct ExpectedProvider { + pub(super) role: G17PAscwrapV6Role, + pub(super) wrapper: (u64, u64), + pub(super) iop_vbar: (u64, u64), +} + +pub(super) fn validate_provider( + provider: &G17PMailboxProvider, + expected: ExpectedProvider, +) -> Result { + let lifecycle = provider.lifecycle()?; + if lifecycle.role != expected.role + || lifecycle.wrapper != expected.wrapper + || lifecycle.iop_vbar != expected.iop_vbar + { + return Err(EINVAL); + } + + Ok(lifecycle) +} diff --git a/drivers/gpu/drm/asahi/m5/render.rs b/drivers/gpu/drm/asahi/m5/render.rs new file mode 100644 index 0000000000000..22bede0991343 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/render.rs @@ -0,0 +1,508 @@ +// SPDX-License-Identifier: MIT +//! M5/G17G graphics register construction from owned render resources. +//! +//! Common resource lowering is shared with G17P. Register order, tile packing +//! and per-stage controls follow the native 25G76 M5 reference. This codec is +//! not a claim that Linux TA/3D submission or presentation is qualified. + +use crate::m5::render_desc::{ + self, G17pRenderParameters, RegisterWrite, RenderBuildError, RenderDescriptorMetadata, + RenderDescriptorObjects, +}; + +pub(crate) const TA_REGISTER_COUNT: usize = 82; +pub(crate) const FRAGMENT_REGISTER_COUNT: usize = 90; + +/// Encode the TA parameter-manager metrics slot in the compact GART window. +/// The native 25G76 slot at 0x1000080040 produces register 1c910 = 0x80041: +/// the low bit enables the record; the remaining bits address its 64 bytes. +pub(crate) fn parameter_buffer_metrics_record( + scene_metrics: u64, +) -> Result { + let offset = scene_metrics.checked_sub(0x10_0000_0000) + .ok_or(M5RenderBuildError::OwnershipMismatch)?; + if offset >= (1u64 << 32) || offset & 0x3f != 0 { + return Err(M5RenderBuildError::OwnershipMismatch); + } + Ok(offset | 1) +} + +/// Initial M5 PB slot with fresh ring cursors. The owning job chooses the +/// hardware slot separately and retains the page-list mapping. +pub(crate) fn initial_parameter_buffer_descriptor( + page_list: u64, + page_count: u32, +) -> Result<[u32; 4], M5RenderBuildError> { + if page_list == 0 || page_list >= (1u64 << 42) || page_list & 0x7f != 0 + || page_count == 0 || page_count >= (1 << 22) { + return Err(M5RenderBuildError::OwnershipMismatch); + } + // 25G76 halLoadPBDesc, 89de844..89de8dc. The descriptor has four + // dwords; +0's low flags and both cursors start at zero. Native's + // untagged user address is translated into its PB segment encoding. + let segment = ((page_list + 0x70_0000_0000) & 0x70_0000_0000) >> 8; + Ok([((page_list >> 4) as u32) & !7, + (segment as u32 & 0xf000_0000) | page_count, 0, 0]) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum M5RenderBuildError { + Common(RenderBuildError), + SharedRegisterLayout, + TileCountOutOfRange, + OverlappingTileFlags, + DispatchBitAlreadySet, + InvalidContext, + OwnershipMismatch, + InvalidUscState, +} + +impl From for M5RenderBuildError { + fn from(error: RenderBuildError) -> Self { + Self::Common(error) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5RenderStageControls { + /// Native host descriptor +0x1120 (TA) / +0x7e8 (fragment). + pub(crate) resource_flags: u64, + /// Explicit per-stage d419/d429 input, independent of the work key. + pub(crate) resource_control: u64, + /// Native +0x1128 / +0x7f0; a zero source selects the native 0x60 fallback. + pub(crate) ptc_max: u32, + pub(crate) work_key: u64, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5RenderControls { + pub(crate) ta: M5RenderStageControls, + pub(crate) fragment: M5RenderStageControls, + pub(crate) ta_tile_control: u64, + /// Base value for the two 1c898 writes. Bit zero is supplied by the codec. + pub(crate) ta_dispatch_control: u64, + pub(crate) fragment_raster_control: u64, + /// Non-geometry bits for 16068. Never includes tile counts, utile or layers. + pub(crate) fragment_tile_flags: u64, + /// M5 adds this second pair of store-program bindings at 153b1/153b9. + pub(crate) store_pipeline_2_bind: u64, + pub(crate) store_pipeline_2: u64, + pub(crate) partial_store_pipeline_2_bind: u64, + pub(crate) partial_store_pipeline_2: u64, + pub(crate) partial_tile_flags: u64, +} + +/// Per-submission USC private-memory accounting, separate from user status +/// registers and queue completion stamps. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5RenderUscState { + pub(crate) control: u64, + /// AGXUMADataRec +0x50. Native allocatePagesEnd derives this from pool + /// sizes and 4-KiB allocation units; it is a byte count, not a GPU VA. + pub(crate) required_bytes: u64, + /// Capacity actually backed by this job's retained USC allocation pages. + pub(crate) allocated_bytes: u64, + /// A 64-byte slot in the firmware-visible statistics ring. + pub(crate) statistics: u64, +} + +impl M5RenderUscState { + fn valid(self) -> bool { + let firmware_range = |address: u64, size: u64| { + address >= 0xffff_fc00_0000_0000 + && address & 0x3f == 0 + && address.checked_add(size).is_some() + }; + firmware_range(self.control, 0x80) + && firmware_range(self.statistics, 0x40) + && self.required_bytes != 0 + && self.required_bytes <= self.allocated_bytes + && self.allocated_bytes & 0xfff == 0 + } +} + +/// Fill the native USC fields only after the caller owns the pool and the +/// statistics slot. Other runtime fields still need queue/link publication. +/// Validate both stages before modifying either descriptor. +pub(crate) fn apply_usc_submission_state( + ta: &mut [u8], + fragment: &mut [u8], + ta_state: M5RenderUscState, + fragment_state: M5RenderUscState, +) -> Result<(), M5RenderBuildError> { + if ta.len() < render_desc::TA_DESCRIPTOR_SIZE + || fragment.len() < render_desc::FRAGMENT_DESCRIPTOR_SIZE + { + return Err(RenderBuildError::BufferTooSmall.into()); + } + if !ta_state.valid() || !fragment_state.valid() { + return Err(M5RenderBuildError::InvalidUscState); + } + // 25G76 AGXTAChannelSKSM::submitBuffer: 8a244c4..8a244ec. + // AGX3DChannelSKSM::submitBuffer takes the corresponding value from + // host +0xba0 = AGXUMADataRec +0x50 at 895b70c..895b718. + for (raw, state, control, required, statistics) in [ + (ta, ta_state, 0x934, 0x93d, 0x945), + (fragment, fragment_state, 0x21ce, 0x21d7, 0x21df), + ] { + put_u64(raw, control, state.control); + put_u64(raw, required, state.required_bytes); + put_u64(raw, statistics, state.statistics); + } + Ok(()) +} + +const EMPTY_REGISTER: RegisterWrite = RegisterWrite { + number: 0, + value: 0, +}; + +struct RegisterList { + values: [RegisterWrite; N], + count: usize, +} + +impl RegisterList { + fn new() -> Self { + Self { + values: [EMPTY_REGISTER; N], + count: 0, + } + } + + fn push(&mut self, number: u32, value: u64) -> Result<(), M5RenderBuildError> { + if self.count == N { + return Err(M5RenderBuildError::SharedRegisterLayout); + } + self.values[self.count] = RegisterWrite { number, value }; + self.count += 1; + Ok(()) + } + + fn finish(self) -> Result<[RegisterWrite; N], M5RenderBuildError> { + if self.count != N { + return Err(M5RenderBuildError::SharedRegisterLayout); + } + Ok(self.values) + } +} + +fn value(registers: &[RegisterWrite], number: u32) -> Result { + registers + .iter() + .find(|r| r.number == number) + .map(|r| r.value) + .ok_or(M5RenderBuildError::SharedRegisterLayout) +} + +const fn ptc_control(maximum: u32) -> u64 { + let maximum = if maximum == 0 { 0x60 } else { maximum }; + ((maximum as u64) << 32) | 0x400020 +} + +fn tile_state(p: &G17pRenderParameters, flags: u64) -> Result { + let tiles_x = (p.width as u64 + 31) / 32; + let tiles_y = (p.height as u64 + 31) / 32; + if !(1..=1024).contains(&tiles_x) || !(1..=1024).contains(&tiles_y) { + return Err(M5RenderBuildError::TileCountOutOfRange); + } + // 25G76 fragment generator: bfi at 89dcb98, 89dcbb8 and 89dcbbc. + let geometry_mask = (0xfffff_u64 << 42) | (0xf_u64 << 38) | (1_u64 << 32); + if flags & geometry_mask != 0 { + return Err(M5RenderBuildError::OverlappingTileFlags); + } + Ok(flags + | ((tiles_x - 1) << 42) + | ((tiles_y - 1) << 52) + | ((p.utile_config & 0xf000) << 26) + | if p.layers > 1 { 1_u64 << 32 } else { 0 }) +} + +fn tile_blocks(pixels: u32) -> u64 { + let tiles = (pixels as u64 + 31) / 32; + let first = (((tiles + 3) / 4) + 3) & !3; + // Native TA host +1208/+120c supplies 0x40200c for the reference: + // boundaries 12, 8, 4 in ten-bit fields, versus G17P's nine-bit fields. + (3 * first) | ((2 * first) << 10) | (first << 20) +} + +pub(crate) fn build_ta_registers( + p: &G17pRenderParameters, + controls: &M5RenderControls, +) -> Result<[RegisterWrite; TA_REGISTER_COUNT], M5RenderBuildError> { + // M5's captured register program addresses heap metadata directly. + // G17P's layered path now uses a separate layer table in these slots. + let mut common_parameters = *p; + common_parameters.layermeta = p.heapmeta; + let common = render_desc::build_ta_registers(&common_parameters)?; + if controls.ta_dispatch_control & 1 != 0 { + return Err(M5RenderBuildError::DispatchBitAlreadySet); + } + // Validate the M5 tile fields even when only constructing the TA half. + tile_state(p, controls.fragment_tile_flags)?; + let mut out = RegisterList::new(); + for mut register in common { + match register.number { + 0x0a309 | 0x0a5a1 | 0x0d419 => continue, + 0x1c8f8 => { + out.push(0x0d499, controls.ta.resource_flags)?; + out.push(0x0d419, controls.ta.resource_control)?; + out.push(0x0a5a1, ptc_control(controls.ta.ptc_max))?; + register.value = controls.ta_tile_control; + } + 0x10171 => { + for (number, source) in [(0x1ca50, 0x101b9), (0x1ca58, 0x10149), (0x1ca60, 0x10141)] + { + out.push(number, value(&common, source)?)?; + } + out.push(0x1ca70, tile_blocks(p.width))?; + out.push(0x1ca78, tile_blocks(p.height))?; + out.push(0x1ca68, value(&common, 0x1c081)?)?; + } + 0x1c069 => register.value = tile_blocks(p.width), + 0x1c071 => register.value = tile_blocks(p.height), + 0x1c898 => { + if register.value > 1 { + return Err(M5RenderBuildError::SharedRegisterLayout); + } + register.value |= controls.ta_dispatch_control; + } + 0x10799 => out.push(0x1a149, 0)?, + 0x10209 => { + out.push(0x0a739, 0)?; + register.value = controls.ta.work_key; + } + 0x1c9f0 | 0x14320 => register.value = controls.ta.work_key, + 0x14308 => register.value = p.usc_flist_hardware_buffer_id as i32 as i64 as u64, + _ => {} + } + out.push(register.number, register.value)?; + if register.number == 0x01740 { + out.push(0x0a739, 0)?; + } + } + out.finish() +} + +pub(crate) fn build_fragment_registers( + p: &G17pRenderParameters, + controls: &M5RenderControls, +) -> Result<[RegisterWrite; FRAGMENT_REGISTER_COUNT], M5RenderBuildError> { + // M5's captured register program addresses heap metadata directly. + // G17P's layered path now uses a separate layer table in these slots. + let mut common_parameters = *p; + common_parameters.layermeta = p.heapmeta; + let common = render_desc::build_fragment_registers(&common_parameters)?; + let geometry = tile_state(p, controls.fragment_tile_flags)?; + let mut out = RegisterList::new(); + let mut dispatch_writes = 0; + let mut tile_writes = 0; + for mut register in common { + match register.number { + 0x0a301 | 0x15109 | 0x15101 | 0x160a8 | 0x0a5a9 | 0x0d429 => continue, + 0x100b1 => register.number = 0x16469, + 0x100d9 => register.number = 0x16471, + 0x100b8 => register.number = 0x16138, + 0x10791 => register.value = controls.fragment_raster_control, + 0x15321 => { + out.push(0x0d491, controls.fragment.resource_flags)?; + out.push(0x0d429, controls.fragment.resource_control)?; + out.push(0x0a5a9, ptc_control(controls.fragment.ptc_max))?; + } + 0x16068 => { + tile_writes += 1; + if tile_writes == 1 { + register.value = geometry; + } + } + 0x16020 => { + dispatch_writes += 1; + if dispatch_writes == 3 { + if register.value != 0 { + return Err(M5RenderBuildError::SharedRegisterLayout); + } + continue; + } + } + 0x160e0 => out.push(0x1a151, 0)?, + 0x10211 => { + out.push(0x0a741, 0)?; + register.value = controls.fragment.work_key; + } + 0x10420 => register.value = controls.fragment.work_key, + 0x14048 => register.value = p.usc_flist_hardware_buffer_id as i32 as i64 as u64, + _ => {} + } + out.push(register.number, register.value)?; + if register.number == 0x15381 { + out.push(0x153b1, controls.store_pipeline_2_bind)?; + out.push(0x153b9, controls.store_pipeline_2)?; + } + if register.number == 0x01731 { + out.push(0x0a741, 0)?; + } + } + if dispatch_writes != 3 || tile_writes != 2 { + return Err(M5RenderBuildError::SharedRegisterLayout); + } + out.finish() +} + +fn partial_registers( + common: &[RegisterWrite], + insert_after: u32, + controls: &M5RenderControls, +) -> Result<[RegisterWrite; N], M5RenderBuildError> { + let mut out = RegisterList::new(); + for register in common { + let bits = if register.number == 0x10039 { + controls.partial_tile_flags + } else { + 0 + }; + out.push(register.number, register.value | bits)?; + if register.number == insert_after { + out.push(0x153b1, controls.partial_store_pipeline_2_bind)?; + out.push(0x153b9, controls.partial_store_pipeline_2)?; + } + } + out.finish() +} + +pub(crate) fn build_partial_store_registers( + p: &G17pRenderParameters, + controls: &M5RenderControls, +) -> Result<[RegisterWrite; 18], M5RenderBuildError> { + partial_registers(&render_desc::partial_store_registers(p), 0x15381, controls) +} + +pub(crate) fn build_partial_resume_registers( + p: &G17pRenderParameters, + controls: &M5RenderControls, +) -> Result<[RegisterWrite; 25], M5RenderBuildError> { + partial_registers(&render_desc::partial_resume_registers(p), 0x15381, controls) +} + +pub(crate) fn build_partial_load_registers( + p: &G17pRenderParameters, + controls: &M5RenderControls, +) -> Result<[RegisterWrite; 12], M5RenderBuildError> { + partial_registers(&render_desc::partial_load_registers(p), 0x15309, controls) +} + +fn work_key( + p: &G17pRenderParameters, + metadata: RenderDescriptorMetadata, +) -> Result { + if metadata.context_id == 0 || metadata.context_id > 255 { + return Err(M5RenderBuildError::InvalidContext); + } + if metadata.ta_hardware_buffer_id != p.ta_hardware_buffer_id { + return Err(M5RenderBuildError::OwnershipMismatch); + } + metadata + .submission_ordinal + .checked_add(metadata.submission_ordinal / 2) + .ok_or(M5RenderBuildError::Common( + RenderBuildError::ArithmeticOverflow, + ))?; + Ok(((metadata.context_id as u64) << 8) | (metadata.command_buffer_state_word & 0x3f) as u64) +} + +fn alias_offset(alias: u64, offset: u64) -> Result { + alias.checked_add(offset).ok_or(M5RenderBuildError::Common( + RenderBuildError::ArithmeticOverflow, + )) +} + +fn put_u16(raw: &mut [u8], offset: usize, value: u16) { + raw[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u32(raw: &mut [u8], offset: usize, value: u32) { + raw[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u64(raw: &mut [u8], offset: usize, value: u64) { + raw[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +/// Construct the M5 TA record's common layout and all register programs. +/// Runtime ownership/completion fields must be populated before publication. +#[inline(never)] +pub(crate) fn build_ta_descriptor_base( + p: &G17pRenderParameters, + controls: &M5RenderControls, + objects: RenderDescriptorObjects, + metadata: RenderDescriptorMetadata, + low_alias: u64, + raw: &mut [u8], +) -> Result<(), M5RenderBuildError> { + let mut controls = *controls; + controls.ta.work_key = work_key(p, metadata)?; + let program = alias_offset(low_alias, 0x60)?; + alias_offset(low_alias, render_desc::TA_DESCRIPTOR_SIZE as u64)?; + let registers = build_ta_registers(p, &controls)?; + render_desc::build_ta_descriptor_base(p, objects, metadata, ®isters, raw)?; + // Native boundaries: main work ends before the final a739/deflake/dispatch. + for (offset, count) in [ + (0x38, TA_REGISTER_COUNT - 3), + (0x3a, TA_REGISTER_COUNT), + (0x3c, TA_REGISTER_COUNT), + ] { + put_u16(raw, offset, count as u16); + } + put_u64(raw, 0x760, program); + Ok(()) +} + +/// Construct the M5 fragment record, including all three partial programs. +/// The shared encoder is pure and does not apply Neo diagnostic overrides. +#[inline(never)] +pub(crate) fn build_fragment_descriptor_base( + p: &G17pRenderParameters, + controls: &M5RenderControls, + objects: RenderDescriptorObjects, + metadata: RenderDescriptorMetadata, + low_alias: u64, + raw: &mut [u8], +) -> Result<(), M5RenderBuildError> { + let mut controls = *controls; + controls.fragment.work_key = work_key(p, metadata)?; + alias_offset(low_alias, render_desc::FRAGMENT_DESCRIPTOR_SIZE as u64)?; + let main = build_fragment_registers(p, &controls)?; + let store = build_partial_store_registers(p, &controls)?; + let resume = build_partial_resume_registers(p, &controls)?; + let load = build_partial_load_registers(p, &controls)?; + render_desc::build_fragment_descriptor_base( + p, + objects, + metadata, + render_desc::G17pFragmentRegisters { + main: &main, + store: &store, + resume: &resume, + load: &load, + }, + raw, + )?; + put_u32(raw, 0x50, 1); + put_u32(raw, 0x90, 1); + for (offset, count) in [ + (0x80, FRAGMENT_REGISTER_COUNT - 3), + (0x82, FRAGMENT_REGISTER_COUNT - 1), + (0x84, FRAGMENT_REGISTER_COUNT - 1), + (0x88, FRAGMENT_REGISTER_COUNT), + ] { + put_u16(raw, offset, count as u16); + } + for (offset, target) in [ + (0x7a0, 0xa0), + (0xec0, 0x7c0), + (0x15e0, 0xee0), + (0x1d00, 0x1600), + ] { + put_u64(raw, offset, alias_offset(low_alias, target)?); + } + Ok(()) +} diff --git a/drivers/gpu/drm/asahi/m5/render_desc.rs b/drivers/gpu/drm/asahi/m5/render_desc.rs new file mode 100644 index 0000000000000..42a556acde208 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/render_desc.rs @@ -0,0 +1,1138 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +const TA_REGISTER_COUNT: usize = 73; + +const FRAGMENT_REGISTER_COUNT: usize = 89; + +/// Both embedded register lists match the kext EXACTLY -- same writes, same +/// unique registers, same order -- verified against 2048-byte captures of the +/// native TA and 3D command records (macos-trace recs2048-gfx.txt): +/// +/// TA 73 writes, 71 unique, list ends at +0x3cc +/// 3D 89 writes, 86 unique, list ends at +0x4cc +/// +/// A 1024-byte capture cuts the 3D list at exactly +0x400 and hides its last +/// 17 writes, which briefly looked like 14 registers "Metal never writes" -- +/// they were entries 72..85. Assert the counts so a future truncated capture +/// cannot produce that conclusion again. +const _: () = assert!(TA_REGISTER_COUNT == 73); + +const _: () = assert!(FRAGMENT_REGISTER_COUNT == 89); + +const PARTIAL_STORE_REGISTER_COUNT: usize = 16; + +const PARTIAL_RESUME_REGISTER_COUNT: usize = 23; + +const PARTIAL_LOAD_REGISTER_COUNT: usize = 10; + +const REGISTER_BYTES: usize = 12; + +pub(crate) const TA_DESCRIPTOR_SIZE: usize = 0x9c0; + +pub(crate) const FRAGMENT_DESCRIPTOR_SIZE: usize = 0x2240; + +/// Native render-setup field copied through command descriptor +0xc00 to the +/// final 3D command tail at +0x2110. This is independent of SGX's GPC +/// performance-state map register. +const G17P_FRAGMENT_TAIL_SETUP_WORD: u32 = u32::MAX; + +/// J700 shared-runtime flag snapshot copied by native 3D submit into type-1 +/// command lanes +0x2124/+0x2128. +/// +/// The kext resolves the accelerator's shared event-stamp/HWDSID internal +/// resource at +0x1a130, obtains its CPU mapping, reads byte bit 0 at mapping +/// +0x2ad/+0x2ae, and widens them before per-draw register generation. The +/// working Neo Metal snapshot contains 1/1. +const G17P_NEO_FRAGMENT_SHARED_RUNTIME_FLAG_SNAPSHOT: [u32; 2] = [1, 1]; + +pub(crate) const G17P_EOT_RESOURCE_SPEC: u64 = 0x8; + +pub(crate) const G17P_LOAD_RESOURCE_SPEC: u64 = 0x0007_8000_0000_0040; + +pub(crate) const G17P_SOURCE_BG_PIPELINE: u64 = 0x0000_0100_0199_0240; + +pub(crate) const G17P_SOURCE_EOT_PIPELINE: u64 = 0x0000_0100_0199_0640; + +const TILE_WIDTH: u64 = 32; + +const TILE_HEIGHT: u64 = 32; + +const MACRO_TILES_X: u64 = 4; + +const MACRO_TILES_Y: u64 = 4; + +const REGION_ENTRY_SIZE: u64 = 5; + +/// Base added by G17P's compact VDM control-stream register (0x1c880). +/// The register retains the legacy 40-bit {TTBR selector, 39-bit offset} +/// shape, so lower-root user addresses are encoded relative to this base. +const G17P_USER_BASE: u64 = 0x10_0000_0000; + +const G17P_VDM_USER_WINDOW_SIZE: u64 = 1 << 39; + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum RenderBuildError { + ZeroDimensions, + LayerCountOutOfRange, + UtileDimensions, + AddressBeforeContext, + UserAddressOutOfRange, + VdmAddressOutOfRange, + BufferTooSmall, + ArithmeticOverflow, +} + +impl RenderBuildError { +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct RegisterWrite { + pub(crate) number: u32, + pub(crate) value: u64, +} + +impl RegisterWrite { + const fn new(number: u32, value: u64) -> Self { + Self { number, value } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct G17pRenderParameters { + pub(crate) width: u32, + pub(crate) height: u32, + pub(crate) context_base: u64, + /// Allocation epoch of the trusted execution-context lease, shared by TA/3D. + pub(crate) context_generation: u8, + pub(crate) tilemap: u64, + /// Per-layer tiler metadata, which native places between the tilemap and + /// the heap metadata. It is empty, and so equal to `heapmeta`, for a + /// single-layer target. + pub(crate) layermeta: u64, + pub(crate) heapmeta: u64, + pub(crate) tpc: u64, + /// Geometry size of the owned TPC subregion, before capacity page rounding. + pub(crate) tpc_size: u64, + pub(crate) deflake_1: u64, + pub(crate) deflake_2: u64, + pub(crate) deflake_3: u64, + pub(crate) encoder: u64, + pub(crate) ta_status: u64, + pub(crate) fragment_status: u64, + pub(crate) store_pipeline_bind: u64, + pub(crate) store_pipeline: u64, + pub(crate) load_pipeline_bind: u64, + pub(crate) load_pipeline: u64, + pub(crate) partial_store_pipeline_bind: u64, + pub(crate) partial_store_pipeline: u64, + pub(crate) partial_load_pipeline_bind: u64, + pub(crate) partial_load_pipeline: u64, + pub(crate) scissor_array: u64, + pub(crate) depth_bias_array: u64, + pub(crate) aux_fb: u64, + pub(crate) occlusion_query_base: u64, + pub(crate) depth_buffer: u64, + pub(crate) stencil_buffer: u64, + pub(crate) depth_aux_buffer: u64, + pub(crate) stencil_aux_buffer: u64, + pub(crate) depth_stride: u64, + pub(crate) stencil_stride: u64, + pub(crate) depth_aux_stride: u64, + pub(crate) stencil_aux_stride: u64, + pub(crate) depth_clear_value_bits: u32, + pub(crate) stencil_clear_value: u32, + pub(crate) depth_flags: u64, + /// ZLS control used by every firmware partial-store/load/resume phase. + /// Unlike the pass-boundary control, an attached depth/stencil surface + /// must be both loaded and stored across an internal split. + pub(crate) partial_depth_flags: u64, + pub(crate) depth_dimensions: u64, + pub(crate) merge_upper_x_bits: u32, + pub(crate) merge_upper_y_bits: u32, + pub(crate) layers: u16, + /// Sample count: 1, 2 or 4. Defaults to 1, so every existing parameter + /// vector keeps its exact register program. + pub(crate) samples: u8, + pub(crate) utile_width: u8, + pub(crate) utile_height: u8, + pub(crate) utile_config: u64, + pub(crate) multisample_control: u64, + pub(crate) ppp_control: u64, + pub(crate) tib_blocks: u64, + pub(crate) tile_config: u64, + pub(crate) aux_fb_flags: u64, + pub(crate) aux_fb_page_count: u64, + pub(crate) cycle: u64, + pub(crate) record_index: u64, + /// TA event correlation written to 0x1ca10/0x014a1/0x0a349. + /// Native sources this independently from the fragment correlation. + pub(crate) lifecycle: u64, + /// Fragment event correlation written to 0x160e0/0x01499/0x0a341. + pub(crate) fragment_lifecycle: u64, + pub(crate) sampler_array: u64, + pub(crate) sampler_count: u32, + pub(crate) process_empty_tiles: bool, + pub(crate) ta_timestamp_start: u64, + pub(crate) ta_timestamp_end: u64, + pub(crate) fragment_timestamp_start: u64, + pub(crate) fragment_timestamp_end: u64, + /// Write the VDM control-stream register (0x1c880) as a full GPU virtual + /// address instead of the native user-process compact form. + /// + /// SCOPE CORRECTED against the macOS oracle. This flag once covered every + /// register `ta_offset` feeds, justified from the legacy G14X path where + /// all of them are whole pointers. A real Metal render pass on THIS chip + /// says otherwise: the captured TA command record writes tilemap, TPC and + /// heapmeta as small context-relative offsets (see `ta_offset`). The legacy + /// encoding does not transfer to G17P, so those six registers are always + /// relative now and this flag applies to the VDM stream alone. Native first + /// lowers the task VA to a task-relative offset, maps the same backing at + /// 0x1000000000 + offset in the GART window, and writes that offset here. + /// Linux userspace supplies the full GART-alias VA; this kernel subtracts + /// the architectural 0x1000000000 base. Hardware adds it back for compact + /// pointers whose bit 39 is clear. + pub(crate) absolute_pointers: bool, + /// + /// Legacy diagnostic OR-mask for the BG resource-specifier high 17 bits. + /// Native calls this field PassControlMaskType and derives it from shader + /// outputs, including extension of the highest active pass bit; it is not + /// an address class or a universal constant. Main and partial shaders can + /// legitimately differ. Default zero preserves the userspace mask; + /// a nonzero value is an explicit diagnostic override only. + pub(crate) bg_resource_prefix: u64, + /// Historical opt-in diagnostic changing byte 2 of the USC private-memory + /// budget qword at TA +0x93d. It must not override +0x94d: that byte is the + /// allocation generation of the execution context, not a PM mode flag. + /// The captured budget is not yet derived from our pool allocation. + pub(crate) native_pm_bytes: bool, + /// Hardware-buffer ID allocated for this TA command. Native allocates it + /// from the accelerator's 0x7f-entry `AGXHardwareBufferIDManager`, stores + /// it in the host-side `AGXTACommandDescriptor` at +0x1248/+0x928, and the + /// register generator emits that value as register 0x1c830. Those two host + /// offsets are not fields in this final 0x9c0-byte firmware command. + pub(crate) ta_hardware_buffer_id: u32, + /// HardwareBufferID of the retained USC private-memory FList shared by TA + /// and 3D. Native allocates this from the USC manager (accelerator + /// +0x133c8), independently of the TA parameter-buffer manager above, and + /// emits the same ID in TA register 0x14308 and fragment register 0x14048. + pub(crate) usc_flist_hardware_buffer_id: u32, + /// Diagnostic capture-value bitmask retained for fields whose proper + /// inputs are not modeled yet. In particular, the 0xa5a* values are + /// assembled from workload-derived USC pool limits. Their captured values + /// are not architectural literals and must not become defaults. + pub(crate) native_ta_registers: u32, + /// Retained GPU-ID diagnostic snapshot, not the fragment parameter-buffer + /// owner. The old 0x1c838 use confused host descriptor +0x928 with a + /// different object's transient raw-command +0x928 field. + pub(crate) gpc_perf_state_map: u32, + /// Low nibble of SGX 0xe01480, copied by native 3D submit to tail +0x210c. + pub(crate) gpc_perf_state_map_low: u32, + /// Bit 0 of SGX 0xe0141c, copied by native 3D submit to tail +0x2104. + pub(crate) gpc_perf_state_control: u32, + /// GPU address of the selected native 0x80 Scene-state entry, or 0 for + /// none. The command-record binding is carried by `RenderDescriptorObjects` + /// in both TA and 3D; this copy is retained for diagnostics. + pub(crate) parameter_buffer: u64, +} + +impl G17pRenderParameters { + + pub(crate) const fn source_rsrc8() -> Self { + Self { + width: 64, + height: 64, + context_base: 0x0000_0010_0000_0000, + context_generation: 1, + tilemap: 0x0000_0010_001b_0000, + layermeta: 0x0000_0010_001b_5000, + heapmeta: 0x0000_0010_001b_5000, + tpc: 0x0000_0010_0024_0000, + tpc_size: 0x800, + deflake_1: 0x0000_0010_0006_82a0, + deflake_2: 0x0000_0010_0006_8020, + deflake_3: 0x0000_0010_0006_8000, + encoder: 0x0000_0010_0001_8000, + ta_status: 0x0000_0010_0007_8000, + fragment_status: 0x0000_0010_001a_8000, + store_pipeline_bind: G17P_EOT_RESOURCE_SPEC, + store_pipeline: G17P_SOURCE_EOT_PIPELINE, + load_pipeline_bind: G17P_LOAD_RESOURCE_SPEC, + load_pipeline: G17P_SOURCE_BG_PIPELINE, + partial_store_pipeline_bind: 0, + partial_store_pipeline: 0, + partial_load_pipeline_bind: 0, + partial_load_pipeline: 0, + scissor_array: 0x0000_0100_019a_0000, + depth_bias_array: 0x0000_0100_01af_8000, + aux_fb: 0x0000_0100_01aa_8000, + occlusion_query_base: 0, + depth_buffer: 0, + stencil_buffer: 0, + depth_aux_buffer: 0, + stencil_aux_buffer: 0, + depth_stride: 0, + stencil_stride: 0, + depth_aux_stride: 0, + stencil_aux_stride: 0, + depth_clear_value_bits: 0x3f80_0000, + stencil_clear_value: 0, + depth_flags: 0, + partial_depth_flags: 0, + depth_dimensions: 0, + merge_upper_x_bits: 0x3cdd_b3d9, + merge_upper_y_bits: 0x3cdd_b3d9, + layers: 1, + samples: 1, + utile_width: 32, + utile_height: 32, + utile_config: 0xa000, + multisample_control: 0x88, + ppp_control: 0x202, + tib_blocks: 8, + tile_config: 0x10280, + aux_fb_flags: 0xc001, + aux_fb_page_count: 0x10_0000, + cycle: 0x17_8020, + record_index: 0x8_0005, + lifecycle: 0, + fragment_lifecycle: 0, + sampler_array: 0, + sampler_count: 0, + process_empty_tiles: true, + ta_timestamp_start: 0xffff_fc20_0002_4c68, + ta_timestamp_end: 0, + fragment_timestamp_start: 0xffff_fc20_0002_4c68, + fragment_timestamp_end: 0xffff_fc20_0002_4c70, + absolute_pointers: false, + bg_resource_prefix: 0, + native_pm_bytes: false, + ta_hardware_buffer_id: 0, + usc_flist_hardware_buffer_id: 0, + native_ta_registers: 0, + gpc_perf_state_map: 0, + gpc_perf_state_map_low: 0, + gpc_perf_state_control: 0, + parameter_buffer: 0, + } + } +} + +#[derive(Debug, Copy, Clone)] +struct Geometry { + tiles_x: u64, + tiles_y: u64, + size1: u64, + size2: u64, + size3: u64, + x_blocks: u64, + y_blocks: u64, + screen: u64, + pixels: u64, + macro_size: u64, +} + +const fn align(value: u64, alignment: u64) -> u64 { + (value + alignment - 1) & !(alignment - 1) +} + +fn geometry(parameters: &G17pRenderParameters) -> Result { + if parameters.width == 0 || parameters.height == 0 { + return Err(RenderBuildError::ZeroDimensions); + } + if parameters.layers == 0 || parameters.layers > 2048 { + return Err(RenderBuildError::LayerCountOutOfRange); + } + + let width = parameters.width as u64; + let height = parameters.height as u64; + let tiles_x = (width + TILE_WIDTH - 1) / TILE_WIDTH; + let tiles_y = (height + TILE_HEIGHT - 1) / TILE_HEIGHT; + let (utile_width, utile_height) = (parameters.utile_width, parameters.utile_height); + if !matches!((utile_width, utile_height), (32, 32) | (32, 16) | (16, 16)) { + return Err(RenderBuildError::UtileDimensions); + } + let utiles_per_tile_x = TILE_WIDTH / utile_width as u64; + let utiles_per_tile_y = TILE_HEIGHT / utile_height as u64; + // Four samples split the utile in Y. Measured against Apple's own + // four-sample render: size1 0x14 -> 0x28, size3 0x20 -> 0x40 and + // macro_size 0x40004 -> 0x40008, where only the y term moves. All three + // follow from doubling this one term; two samples do not split. + let utiles_per_tile_y = if parameters.samples == 4 { + utiles_per_tile_y * 2 + } else { + utiles_per_tile_y + }; + let utiles_per_tile = utiles_per_tile_x * utiles_per_tile_y; + let mtile_x1 = align((tiles_x + MACRO_TILES_X - 1) / MACRO_TILES_X, 4); + let mtile_y1 = align((tiles_y + MACRO_TILES_Y - 1) / MACRO_TILES_Y, 4); + let mtile_x2 = 2 * mtile_x1; + let mtile_x3 = 3 * mtile_x1; + let mtile_y2 = 2 * mtile_y1; + let mtile_y3 = 3 * mtile_y1; + let mtile_stride = mtile_x1 * mtile_y1; + let size1 = (REGION_ENTRY_SIZE * mtile_stride * utiles_per_tile + 3) / 4; + + Ok(Geometry { + tiles_x, + tiles_y, + size1, + size2: mtile_stride, + size3: 2 * mtile_stride * utiles_per_tile, + x_blocks: mtile_x3 | (mtile_x2 << 9) | (mtile_x1 << 18), + y_blocks: mtile_y3 | (mtile_y2 << 9) | (mtile_y1 << 18), + screen: ((tiles_y - 1) << 12) | (tiles_x - 1), + pixels: (width - 1) | ((height - 1) << 16), + macro_size: mtile_y1 * utiles_per_tile_y | ((mtile_x1 * utiles_per_tile_x) << 16), + }) +} + +/// Context-relative offset. ALWAYS relative -- a real Metal render pass on this +/// chip writes small offsets into these registers, not addresses. +/// +/// Oracle: the TA command record captured from `mtlg.m` (macos-trace +/// `recs-gfx.txt`, dumped by `recs.d` at `requestChannelCommandTA`) carries an +/// embedded register list that decodes field-for-field against this function's +/// output -- same registers, same order, 12-byte entries of u32 number plus u64 +/// value -- with these values: +/// +/// 0x01748 = 1 (matches) +/// 0x10141 = 0x200 (matches) +/// 0x1c039 = 0x0119ba00 tilemap <- OFFSET, not a VA +/// 0x1c9c8 = 0x0119ba00 tilemap +/// 0x1c0a1 = 0x01290000 tpc <- OFFSET +/// 0x1c031 = 0x800000000119ca00 heapmeta | bit63 (matches the form) +/// 0x1c9c0 = 0x800000000119ca00 heapmeta +/// 0x1c051 = 0x003a0012006b0003 (matches the constant exactly) +/// +/// Writing full virtual addresses here -- which is what the legacy G14X path +/// does, and what an earlier version of this driver was changed to do -- points +/// the tiler's tilemap, TPC and heapmeta at values the firmware cannot use. +fn ta_resource_offset( + parameters: &G17pRenderParameters, + address: u64, +) -> Result { + address + .checked_sub(parameters.context_base) + .ok_or(RenderBuildError::AddressBeforeContext) +} + +/// Compact user/GART address consumed by the TA register and descriptor +/// fields. Native maps these objects in the architectural 0x1000000000 window +/// and publishes the offset, not the full address. Descriptor +0x7d6 is only +/// 32 bits wide, so reject aliases that cannot be represented consistently. +fn ta_user_offset(address: u64) -> Result { + let offset = address + .checked_sub(G17P_USER_BASE) + .ok_or(RenderBuildError::UserAddressOutOfRange)?; + + if offset > u32::MAX as u64 { + return Err(RenderBuildError::UserAddressOutOfRange); + } + + Ok(offset) +} + +fn vdm_user_offset(address: u64) -> Result { + let offset = address + .checked_sub(G17P_USER_BASE) + .ok_or(RenderBuildError::VdmAddressOutOfRange)?; + + if offset >= G17P_VDM_USER_WINDOW_SIZE { + return Err(RenderBuildError::VdmAddressOutOfRange); + } + + Ok(offset) +} + +pub(crate) fn build_ta_registers( + p: &G17pRenderParameters, +) -> Result<[RegisterWrite; TA_REGISTER_COUNT], RenderBuildError> { + build_ta_registers_for_work_key(p, render_work_key(1, 0)) +} + +fn build_ta_registers_for_work_key( + p: &G17pRenderParameters, + work_key: u64, +) -> Result<[RegisterWrite; TA_REGISTER_COUNT], RenderBuildError> { + let g = geometry(p)?; + let tilemap = ta_resource_offset(p, p.tilemap)?; + let layermeta = ta_resource_offset(p, p.layermeta)?; + let heapmeta = ta_resource_offset(p, p.heapmeta)?; + let tpc = ta_resource_offset(p, p.tpc)?; + let deflake_1 = ta_user_offset(p.deflake_1)?; + let deflake_2 = ta_user_offset(p.deflake_2)?; + let deflake_3 = ta_user_offset(p.deflake_3)?; + // The VDM control stream is the one pointer the 192-byte capture window + // does not reach (register 0x1c880 sits past the end of the dump), and it + // is the one that is not relative to the driver-private `context_base`. + // macOS first lowers the task VA to a task-relative offset, then maps the + // backing at 0x1000000000 + offset in the GART window. Linux userspace gives + // us that full alias VA, so this hardware encoder subtracts the GART base. + // Bit 39 selects the upper UAT root; refuse an offset that would silently + // change roots. Keep the full-address escape hatch diagnostic-only. + let encoder = if p.absolute_pointers { + p.encoder + } else { + vdm_user_offset(p.encoder)? + }; + // generateTARegisterListG16Common: the layer count less one with bit 15, + // plus bit 14 and a process-empty-tiles select for a layered target. The + // pipe mirror 0x1c9e8 keeps only the layered bit and the count. + let mut layer_mode = 0x8000 | (p.layers as u64 - 1); + if p.layers > 1 { + layer_mode |= 0x4000 | if p.process_empty_tiles { 0x2000 } else { 0x1000 }; + } + + Ok([ + RegisterWrite::new(0x01748, 1), + // Native N=1 uses 0x200 and N=2 uses 0x0. The one-layer source profile + // selects the N=1 value, matching descriptor byte +0x789 above. + RegisterWrite::new(0x10141, 0x200), + RegisterWrite::new(0x1c039, tilemap), + RegisterWrite::new(0x1c9c8, tilemap), + RegisterWrite::new(0x1c0a1, tpc), + RegisterWrite::new(0x1c031, heapmeta | 0x8000_0000_0000_0000), + RegisterWrite::new(0x1c9c0, heapmeta | 0x8000_0000_0000_0000), + RegisterWrite::new(0x1c051, 0x003a_0012_006b_0003), + RegisterWrite::new(0x1c061, 1), + RegisterWrite::new(0x10149, p.utile_config), + RegisterWrite::new(0x10139, p.multisample_control), + RegisterWrite::new(0x10111, deflake_1), + RegisterWrite::new(0x1c9b0, deflake_1), + RegisterWrite::new(0x10119, deflake_2), + RegisterWrite::new(0x1c9b8, deflake_2), + RegisterWrite::new(0x1c958, 1), + RegisterWrite::new(0x1c950, deflake_3 | 0x0004_0000_0000_0000), + RegisterWrite::new(0x1c930, 0), + RegisterWrite::new(0x1c880, encoder), + RegisterWrite::new(0x1c079, layermeta), + RegisterWrite::new(0x1c9d8, layermeta), + RegisterWrite::new(0x10151, 0), + RegisterWrite::new(0x1c199, 0), + RegisterWrite::new(0x1c1a1, 0), + RegisterWrite::new(0x1c1a9, 0), + RegisterWrite::new(0x1c1b1, 0), + RegisterWrite::new(0x1c1b9, 0), + RegisterWrite::new(0x1c8f8, 0x8860), + RegisterWrite::new(0x1c0b1, g.size1), + RegisterWrite::new(0x1c850, g.size1), + // Silicon holds 0x10131 at 0x88 at ONE, TWO and FOUR samples while + // 0x10139 carries the real sample position table (all five captures in + // logs/m5-msaa-native-hv-20260915-101837). Driving this from + // multisample_control would write the position table here, which + // Apple never does. + RegisterWrite::new(0x10131, 0x88), + RegisterWrite::new(0x10121, p.ppp_control), + RegisterWrite::new(0x10129, g.pixels), + RegisterWrite::new(0x101b9, g.screen), + RegisterWrite::new(0x1c069, g.x_blocks), + RegisterWrite::new(0x1c071, g.y_blocks), + RegisterWrite::new(0x1c081, g.size2), + RegisterWrite::new(0x1c0a9, g.size3), + RegisterWrite::new(0x10171, 0x100), + RegisterWrite::new(0x10169, layer_mode), + RegisterWrite::new(0x0a309, 0), + RegisterWrite::new(0x1c8e0, u64::MAX), + RegisterWrite::new(0x1c8e8, u64::MAX), + RegisterWrite::new(0x1c898, 0), + RegisterWrite::new(0x101e1, 0x1c), + RegisterWrite::new(0x1c9e8, layer_mode & 0x47ff), + RegisterWrite::new(0x1a099, 0), + RegisterWrite::new(0x1a0a1, 0), + RegisterWrite::new(0x1a069, 0), + RegisterWrite::new(0x1a071, 0), + RegisterWrite::new(0x1a0c9, 0), + RegisterWrite::new(0x1a0d1, 0), + RegisterWrite::new(0x101c9, 0), + RegisterWrite::new(0x0d471, 0), + RegisterWrite::new(0x1a0f1, 8), + RegisterWrite::new(0x10799, 0xff_0000), + // Native sources this from AGXHardwareBufferIDManager. It is neither a + // PBDesc ring index nor a capture-stable literal. + RegisterWrite::new(0x1c830, p.ta_hardware_buffer_id as u64), + RegisterWrite::new(0x1ca30, p.cycle), + RegisterWrite::new(0x16c39, p.cycle), + RegisterWrite::new(0x1c910, p.record_index), + // Native derives the high word from the TA AGXUMADataRec PTC/DUPM + // maximum at host descriptor +0x1488, copied through command +0x1158. + // halUpdatePTCMaxCount computes max(0x60, min(pool_input / active_kicks, + // 0x200)); Linux does not yet carry that pool input. Follow the kext's + // exact zero-source fallback 0x60_0040_0020. Bit 1 retains one working + // Metal trace's workload-derived 0xfe value as a diagnostic only. + RegisterWrite::new( + 0x0a5a1, + if p.native_ta_registers & 2 != 0 { + 0x0000_00fe_0040_0020 + } else { + 0x0000_0060_0040_0020 + }, + ), + RegisterWrite::new(0x0d419, 0x0000_0002_0000_0001), + RegisterWrite::new(0x1ca10, p.lifecycle), + RegisterWrite::new(0x014a1, p.lifecycle), + RegisterWrite::new(0x0a349, p.lifecycle), + RegisterWrite::new(0x10209, work_key), + RegisterWrite::new(0x1c9f0, work_key), + RegisterWrite::new(0x14320, work_key), + // AGXTACommandDescriptor::prepare receives the shared USC FList ID + // through descriptor +0x1410. Optional GART/feature payloads are absent + // in Linux, so the retained owner's ID is the complete value. + RegisterWrite::new(0x14308, p.usc_flist_hardware_buffer_id as u64), + RegisterWrite::new(0x14318, p.ta_status | 1), + RegisterWrite::new(0x01740, 1), + RegisterWrite::new(0x1c880, deflake_1), + RegisterWrite::new(0x1c898, 1), + ]) +} + +pub(crate) fn build_fragment_registers( + p: &G17pRenderParameters, +) -> Result<[RegisterWrite; FRAGMENT_REGISTER_COUNT], RenderBuildError> { + build_fragment_registers_for_work_key(p, render_work_key(1, 1)) +} + +fn build_fragment_registers_for_work_key( + p: &G17pRenderParameters, + work_key: u64, +) -> Result<[RegisterWrite; FRAGMENT_REGISTER_COUNT], RenderBuildError> { + let g = geometry(p)?; + let tile_state = 0x3717f + | ((g.tiles_x - 1) << 44) + | ((g.tiles_y - 1) << 53) + | 0x20_0000_0000 + | (if p.layers > 1 { 0x1_0000_0000 } else { 0 }) + | ((p.utile_config & 0xf000) << 28); + + Ok([ + RegisterWrite::new(0x01739, 1), + RegisterWrite::new(0x10009, p.utile_config), + RegisterWrite::new(0x15379, p.store_pipeline_bind), + RegisterWrite::new(0x15381, p.store_pipeline), + RegisterWrite::new(0x15369, p.load_pipeline_bind), + RegisterWrite::new(0x15371, p.load_pipeline), + RegisterWrite::new(0x15131, p.merge_upper_x_bits as u64), + RegisterWrite::new(0x15139, p.merge_upper_y_bits as u64), + RegisterWrite::new(0x100a1, 0), + RegisterWrite::new(0x15069, 0), + RegisterWrite::new(0x15071, 0), + RegisterWrite::new(0x16058, 0), + RegisterWrite::new(0x10019, p.multisample_control), + RegisterWrite::new(0x100b1, g.macro_size), + RegisterWrite::new(0x16030, g.macro_size), + RegisterWrite::new(0x100d9, g.screen), + RegisterWrite::new(0x0a301, 0), + RegisterWrite::new(0x10791, 0xff_0200), + RegisterWrite::new(0x16098, p.heapmeta), + RegisterWrite::new(0x15109, p.scissor_array), + RegisterWrite::new(0x15101, p.depth_bias_array), + RegisterWrite::new(0x15021, p.aux_fb_flags), + RegisterWrite::new(0x15211, ((p.height as u64) << 32) | p.width as u64), + RegisterWrite::new(0x15049, p.aux_fb_page_count), + RegisterWrite::new(0x10051, p.tib_blocks), + RegisterWrite::new(0x15321, p.depth_dimensions), + RegisterWrite::new(0x15301, p.depth_clear_value_bits as u64), + RegisterWrite::new(0x15309, (p.stencil_clear_value | 0x300) as u64), + RegisterWrite::new(0x15311, p.occlusion_query_base), + RegisterWrite::new(0x15319, p.depth_flags), + RegisterWrite::new(0x15349, 0x0404_0404), + RegisterWrite::new(0x15351, 0), + RegisterWrite::new(0x15329, p.depth_buffer), + RegisterWrite::new(0x15331, p.depth_buffer), + RegisterWrite::new(0x15339, p.stencil_buffer), + RegisterWrite::new(0x15341, p.stencil_buffer), + RegisterWrite::new(0x15231, 0), + RegisterWrite::new(0x15221, 0), + RegisterWrite::new(0x15239, 0), + RegisterWrite::new(0x15229, 0), + RegisterWrite::new(0x15401, p.depth_stride), + RegisterWrite::new(0x15421, p.depth_stride), + RegisterWrite::new(0x15409, p.stencil_stride), + RegisterWrite::new(0x15429, p.stencil_stride), + RegisterWrite::new(0x153c1, p.depth_aux_buffer), + RegisterWrite::new(0x15411, p.depth_aux_stride), + RegisterWrite::new(0x153c9, p.depth_aux_buffer), + RegisterWrite::new(0x15431, p.depth_aux_stride), + RegisterWrite::new(0x153d1, p.stencil_aux_buffer), + RegisterWrite::new(0x15419, p.stencil_aux_stride), + RegisterWrite::new(0x153d9, p.stencil_aux_buffer), + RegisterWrite::new(0x15439, p.stencil_aux_stride), + RegisterWrite::new(0x16429, p.tilemap), + RegisterWrite::new(0x16060, p.layermeta), + RegisterWrite::new(0x16431, (4 * g.size1) << 24), + RegisterWrite::new(0x10039, p.tile_config), + RegisterWrite::new(0x16020, 0), + RegisterWrite::new(0x16451, 0), + RegisterWrite::new(0x15359, 0), + RegisterWrite::new(0x100b8, 0x8860), + RegisterWrite::new(0x16461, p.aux_fb), + RegisterWrite::new(0x16090, p.aux_fb), + RegisterWrite::new(0x101e9, 0x1c), + RegisterWrite::new(0x160a8, 0), + RegisterWrite::new(0x16068, tile_state), + RegisterWrite::new(0x1a0a9, 0), + RegisterWrite::new(0x1a0b1, 0), + RegisterWrite::new(0x1a079, 0), + RegisterWrite::new(0x1a081, 0), + RegisterWrite::new(0x1a0d9, 0), + RegisterWrite::new(0x1a0e1, 0), + RegisterWrite::new(0x101c1, 0), + RegisterWrite::new(0x0d469, 0), + RegisterWrite::new(0x1a0f9, 8), + // Fragment analog of TA 0x0a5a1. Native derives its high word from the + // 3D AGXUMADataRec PTC/DUPM maximum at host descriptor +0xc00, copied + // through command +0x818. Linux has no owned pool-size input yet, so + // use the exact 0x60 zero-source fallback. Bit 3 retains one captured, + // workload-derived 0xd5 value only as a diagnostic. + RegisterWrite::new( + 0x0a5a9, + if p.native_ta_registers & 8 != 0 { + 0x0000_00d5_0040_0020 + } else { + 0x0000_0060_0040_0020 + }, + ), + RegisterWrite::new(0x0d429, 0x0000_0002_0000_0001), + RegisterWrite::new(0x160e0, p.fragment_lifecycle), + RegisterWrite::new(0x01499, p.fragment_lifecycle), + RegisterWrite::new(0x0a341, p.fragment_lifecycle), + // The fragment must use the same parameter-buffer owner as TA 1c830. + // Native TA::prepare stores its allocated HWPB ID at host +928; the + // same derived host descriptor is submitted through both channels. + // generate3DRegisterList reads that HOST field at 8a5c7cc. Its wrapper + // at 8a515d8 tail-calls with x1=raw command, x2=host descriptor: the + // unused channel argument in the mangled common-function name is NOT + // present in the optimized calling convention. Raw command +928 has + // a different producer and must not be used to infer this register. + RegisterWrite::new(0x1c838, p.ta_hardware_buffer_id as u64), + RegisterWrite::new(0x1ca28, p.cycle), + RegisterWrite::new(0x10211, work_key), + RegisterWrite::new(0x10420, work_key), + // AGX3DCommandDescriptor::prepare receives this ID from the USC pool's + // HardwareBufferIDManager and generate3DRegisterList ORs it with an + // optional GART payload and feature bit. Linux currently has neither + // optional source, so publish the retained USC FList owner's exact ID. + RegisterWrite::new(0x14048, p.usc_flist_hardware_buffer_id as u64), + RegisterWrite::new(0x14080, p.fragment_status | 1), + RegisterWrite::new(0x01731, 1), + RegisterWrite::new(0x16020, 1), + RegisterWrite::new(0x16020, 0), + RegisterWrite::new(0x16068, 0x4_0000), + ]) +} + +pub(crate) fn partial_store_registers( + p: &G17pRenderParameters, +) -> [RegisterWrite; PARTIAL_STORE_REGISTER_COUNT] { + [ + RegisterWrite::new(0x15379, p.partial_store_pipeline_bind), + RegisterWrite::new(0x15381, p.partial_store_pipeline), + RegisterWrite::new(0x10039, p.tile_config), + RegisterWrite::new(0x15359, 0x20), + RegisterWrite::new(0x15331, p.depth_buffer), + RegisterWrite::new(0x153c9, p.depth_aux_buffer), + RegisterWrite::new(0x15341, p.stencil_buffer), + RegisterWrite::new(0x153d9, p.stencil_aux_buffer), + RegisterWrite::new(0x15421, p.depth_stride), + RegisterWrite::new(0x15431, p.depth_aux_stride), + RegisterWrite::new(0x15429, p.stencil_stride), + RegisterWrite::new(0x15439, p.stencil_aux_stride), + RegisterWrite::new(0x15221, 0), + RegisterWrite::new(0x15229, 0), + RegisterWrite::new(0x15319, p.partial_depth_flags), + RegisterWrite::new(0x15349, 0x0404_0404), + ] +} + +pub(crate) fn partial_resume_registers( + p: &G17pRenderParameters, +) -> [RegisterWrite; PARTIAL_RESUME_REGISTER_COUNT] { + [ + RegisterWrite::new(0x15379, p.partial_store_pipeline_bind), + RegisterWrite::new(0x15381, p.partial_store_pipeline), + RegisterWrite::new(0x15369, p.partial_load_pipeline_bind), + RegisterWrite::new(0x15371, p.partial_load_pipeline), + RegisterWrite::new(0x10039, p.tile_config & 0xffff), + RegisterWrite::new(0x15359, 0x20), + RegisterWrite::new(0x15331, p.depth_buffer), + RegisterWrite::new(0x153c9, p.depth_aux_buffer), + RegisterWrite::new(0x15341, p.stencil_buffer), + RegisterWrite::new(0x153d9, p.stencil_aux_buffer), + RegisterWrite::new(0x15421, p.depth_stride), + RegisterWrite::new(0x15431, p.depth_aux_stride), + RegisterWrite::new(0x15429, p.stencil_stride), + RegisterWrite::new(0x15439, p.stencil_aux_stride), + RegisterWrite::new(0x15221, 0), + RegisterWrite::new(0x15229, 0), + RegisterWrite::new(0x15309, (p.stencil_clear_value | 0x300) as u64), + RegisterWrite::new(0x15329, p.depth_buffer), + RegisterWrite::new(0x153c1, p.depth_aux_buffer), + RegisterWrite::new(0x15339, p.stencil_buffer), + RegisterWrite::new(0x153d1, p.stencil_aux_buffer), + RegisterWrite::new(0x15319, p.partial_depth_flags), + RegisterWrite::new(0x15349, 0x0404_0404), + ] +} + +pub(crate) fn partial_load_registers( + p: &G17pRenderParameters, +) -> [RegisterWrite; PARTIAL_LOAD_REGISTER_COUNT] { + [ + RegisterWrite::new(0x15369, p.partial_load_pipeline_bind), + RegisterWrite::new(0x15371, p.partial_load_pipeline), + RegisterWrite::new(0x10039, p.tile_config & 0xffff), + RegisterWrite::new(0x15309, (p.stencil_clear_value | 0x300) as u64), + RegisterWrite::new(0x15329, p.depth_buffer), + RegisterWrite::new(0x153c1, p.depth_aux_buffer), + RegisterWrite::new(0x15339, p.stencil_buffer), + RegisterWrite::new(0x153d1, p.stencil_aux_buffer), + RegisterWrite::new(0x15319, p.partial_depth_flags), + RegisterWrite::new(0x15349, 0x0404_0404), + ] +} + +fn put_u8(raw: &mut [u8], offset: usize, value: u8) { + raw[offset] = value; +} + +fn put_u16(raw: &mut [u8], offset: usize, value: u16) { + raw[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u32(raw: &mut [u8], offset: usize, value: u32) { + raw[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u64(raw: &mut [u8], offset: usize, value: u64) { + raw[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +fn encode_registers(raw: &mut [u8], offset: usize, registers: &[RegisterWrite]) { + for (index, register) in registers.iter().enumerate() { + let entry = offset + index * REGISTER_BYTES; + put_u32(raw, entry, register.number); + put_u64(raw, entry + 4, register.value); + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum RenderDescriptorKind { + Tiling, + Fragment, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct RenderDescriptorObjects { + pub(crate) record_a: u64, + pub(crate) shared: u64, + pub(crate) record_b: u64, + pub(crate) zero: u64, +} + +impl RenderDescriptorObjects { + +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct RenderDescriptorMetadata { + pub(crate) context_id: u32, + pub(crate) submission_ordinal: u64, + /// Monotonic state tag allocated by the command buffer's 36-entry state + /// ring. This is neither the selected ring index nor any QID/HWID. Native + /// retains the full word in the selected state object and places only its + /// low six bits in the stage work key. + pub(crate) command_buffer_state_word: u32, + /// TA HardwareBufferID copied to firmware descriptor +0x18. + /// + /// Every working native descriptor corpus couples this field to register + /// 0x1c830 exactly (for example 2/2, 4/4, and 5/5). The same allocator + /// result is also PBState +0x0c and the descriptor-ring index consumed by + /// `halLoadPBDesc`. + pub(crate) ta_hardware_buffer_id: u32, + pub(crate) submit_sequence: u64, +} + +impl RenderDescriptorMetadata { +} + +/// Native's TA/3D register-list producer couples the command-buffer state tag +/// to the descriptor's allocated application-GART context. The physical QID, +/// QoS HardwareBufferID, descriptor-array slot and 36-entry state-ring index +/// are independent namespaces and must not be substituted here. +const fn render_work_key(context_id: u32, command_buffer_state_word: u32) -> u64 { + ((context_id as u64) << 8) | ((command_buffer_state_word & 0x3f) as u64) +} + +fn descriptor_work_ordinal(ordinal: u64) -> u32 { + (ordinal as u32).wrapping_add((ordinal / 2) as u32) +} + +fn write_common_descriptor( + kind: RenderDescriptorKind, + objects: RenderDescriptorObjects, + metadata: RenderDescriptorMetadata, + registers: &[RegisterWrite], + raw: &mut [u8], +) { + let (selector, pointers, register_offset, pointer_gap) = match kind { + RenderDescriptorKind::Tiling => (0u32, 0x10usize, 0x60usize, 8usize), + RenderDescriptorKind::Fragment => (1u32, 0x20usize, 0xa0usize, 0usize), + }; + put_u32(raw, 0, selector); + put_u64(raw, 4, metadata.submit_sequence); + put_u32(raw, 0x0c, metadata.context_id); + + let addresses = [ + objects.record_a, + objects.shared, + objects.record_b, + objects.zero, + ]; + let mut offset = pointers; + for (index, address) in addresses.iter().enumerate() { + put_u64(raw, offset, *address); + offset += 8; + if index == 0 { + offset += pointer_gap; + } + } + encode_registers(raw, register_offset, registers); + + let work = descriptor_work_ordinal(metadata.submission_ordinal); + match kind { + RenderDescriptorKind::Tiling => { + put_u32(raw, 0x18, metadata.ta_hardware_buffer_id); + put_u32(raw, 0x48, work); + } + RenderDescriptorKind::Fragment => {} + } +} + +pub(crate) fn build_ta_descriptor_base( + parameters: &G17pRenderParameters, + objects: RenderDescriptorObjects, + metadata: RenderDescriptorMetadata, + registers: &[RegisterWrite], + raw: &mut [u8], +) -> Result<(), RenderBuildError> { + if raw.len() < TA_DESCRIPTOR_SIZE { + return Err(RenderBuildError::BufferTooSmall); + } + if registers.is_empty() || registers.len() > (0x660 - 0x60) / REGISTER_BYTES { + return Err(RenderBuildError::BufferTooSmall); + } + raw[..TA_DESCRIPTOR_SIZE].fill(0); + write_common_descriptor( + RenderDescriptorKind::Tiling, + objects, + metadata, + registers, + raw, + ); + + // Like the fragment boundaries, these are generated for every native TA + // command (25G83 88bdfc4/88be090/88be1a4), not only a queue's first kick. + // The final three entries are 01740, 1c880, 1c898; firmware reads +38 and + // +3a/+3c to select the corresponding embedded RCE boundaries. + put_u16(raw, 0x38, (TA_REGISTER_COUNT - 2) as u16); + put_u16(raw, 0x3a, TA_REGISTER_COUNT as u16); + put_u16(raw, 0x3c, TA_REGISTER_COUNT as u16); + + let deflake = ta_user_offset(parameters.deflake_1)?; + let sampler_max = if parameters.sampler_count == 0 { + 0 + } else { + parameters.sampler_count + 1 + }; + put_u32( + raw, + 0x0768, + (((registers.len() * REGISTER_BYTES) as u32) << 16) | registers.len() as u32, + ); + put_u64(raw, 0x0780, parameters.tpc); + // Native copies RTMemory's geometry-derived TPC size beside its pointer + // on every submission (25G83 88fd970..974), independent of queue lifetime. + put_u64(raw, 0x0788, parameters.tpc_size); + put_u32(raw, 0x07d6, deflake as u32); + put_u32(raw, 0x0876, u32::MAX); + put_u64(raw, 0x087a, parameters.sampler_array); + put_u32(raw, 0x0882, parameters.sampler_count); + put_u32(raw, 0x0886, sampler_max); + // Present in 436/438 valid G17P TA records, including both exact 32x32 + // geometry matches. This belongs to the TA output/activation tail; leaving + // it zero is a structural mismatch before the linked 3D job is generated. + put_u32(raw, 0x0892, 1); + put_u8(raw, 0x0932, 0x44); + put_u8(raw, 0x093c, 1); + put_u8(raw, 0x094d, parameters.context_generation); + put_u64(raw, 0x08fe, parameters.ta_timestamp_start); + put_u64(raw, 0x0906, parameters.ta_timestamp_end); + // +0x090e/+0x0916 are caller-visible timestamp destinations. Firmware + // writes them only inside its timestamp aperture, so they stay zero; the + // completion publishes the pass envelope to userspace instead. + // AGXTAChannelSKSM::submitBuffer mirrors the same dependency/current pair + // consumed by the TA RCE program into the firmware command. These fields + // are deliberately unaligned in the native 0x9c0-byte command layout. + put_u32(raw, 0x086e, (parameters.lifecycle >> 32) as u32); + put_u64(raw, 0x08ce, parameters.lifecycle as u32 as u64); + Ok(()) +} + +fn put_embedded_registers( + raw: &mut [u8], + header_offset: usize, + program_offset: usize, + registers: &[RegisterWrite], +) { + let bytes = registers.len() * REGISTER_BYTES; + put_u32( + raw, + header_offset, + ((bytes as u32) << 16) | registers.len() as u32, + ); + encode_registers(raw, program_offset, registers); +} + +pub(crate) struct G17pFragmentRegisters<'a> { + pub(crate) main: &'a [RegisterWrite], + pub(crate) store: &'a [RegisterWrite], + pub(crate) resume: &'a [RegisterWrite], + pub(crate) load: &'a [RegisterWrite], +} + +pub(crate) fn build_fragment_descriptor_base( + parameters: &G17pRenderParameters, + objects: RenderDescriptorObjects, + metadata: RenderDescriptorMetadata, + programs: G17pFragmentRegisters<'_>, + raw: &mut [u8], +) -> Result<(), RenderBuildError> { + if raw.len() < FRAGMENT_DESCRIPTOR_SIZE { + return Err(RenderBuildError::BufferTooSmall); + } + if programs.main.is_empty() + || programs.main.len() > (0x6a0 - 0xa0) / REGISTER_BYTES + || programs.store.len() > (0xec0 - 0x7c0) / REGISTER_BYTES + || programs.resume.len() > (0x15e0 - 0xee0) / REGISTER_BYTES + || programs.load.len() > (0x1d00 - 0x1600) / REGISTER_BYTES + { + return Err(RenderBuildError::BufferTooSmall); + } + raw[..FRAGMENT_DESCRIPTOR_SIZE].fill(0); + let geometry = geometry(parameters)?; + let register_count = programs.main.len(); + write_common_descriptor( + RenderDescriptorKind::Fragment, + objects, + metadata, + programs.main, + raw, + ); + + put_u64(raw, 0x40, parameters.tilemap); + put_u64(raw, 0x48, parameters.multisample_control); + // Native copies the render target's sample count through host +0x8c8 + // into every fragment descriptor at +0x50 (25G83: 0x8839d80, + // 0x8837af8..0x8837b08). It is not first-work metadata. The UAPI has + // already encoded log2(samples) in UTILE_CONFIG bits [1:0]. + put_u32(raw, 0x50, 1u32 << (parameters.utile_config & 3)); + put_u32(raw, 0x54, geometry.macro_size as u32); + put_u32(raw, 0x68, parameters.merge_upper_x_bits); + put_u32(raw, 0x6c, parameters.merge_upper_y_bits); + put_u64(raw, 0x78, geometry.tiles_x * geometry.tiles_y); + + // RCE boundaries belong to every command, including retained queue kicks. + // Native emits these from the running register count (25G83 88c0740, + // 88c07ac, 88c08c8, 88c0970); firmware consumes +80/+82/+84/+88 when + // selecting an entry in this command's embedded program. The fixed recipe + // ends with 01731=1, 16020=1, 16020=0, 16068=40000. Boundaries are after + // 01731, after the first 16020, that same entry, and the complete program. + // Keeping these only in the cold wrapper left ordinary restages at zero. + put_u16(raw, 0x80, (register_count - 3) as u16); + put_u16(raw, 0x82, (register_count - 2) as u16); + put_u16(raw, 0x84, (register_count - 2) as u16); + put_u16(raw, 0x88, register_count as u16); + + put_u32( + raw, + 0x07a8, + (((register_count * REGISTER_BYTES) as u32) << 16) | register_count as u32, + ); + put_embedded_registers(raw, 0x0ec8, 0x07c0, programs.store); + put_embedded_registers(raw, 0x15e8, 0x0ee0, programs.resume); + put_embedded_registers(raw, 0x1d08, 0x1600, programs.load); + + put_u64(raw, 0x1d20, parameters.depth_bias_array); + put_u64(raw, 0x1d30, parameters.scissor_array); + put_u64(raw, 0x1d40, parameters.occlusion_query_base); + put_u64(raw, 0x1e78, parameters.load_pipeline_bind); + put_u64(raw, 0x1e80, parameters.load_pipeline); + put_u64(raw, 0x1ea8, parameters.partial_load_pipeline_bind); + put_u64(raw, 0x1eb0, parameters.partial_load_pipeline); + put_u32(raw, 0x1ec0, 0x0404_0404); + put_u64(raw, 0x1f38, parameters.tib_blocks); + put_u64(raw, 0x1f40, parameters.aux_fb_flags); + put_u32(raw, 0x1f48, parameters.width); + put_u32(raw, 0x1f4c, parameters.height); + put_u64(raw, 0x1f50, parameters.aux_fb_page_count); + put_u64(raw, 0x1f58, parameters.tile_config); + put_u32(raw, 0x1f78, parameters.store_pipeline_bind as u32); + put_u64(raw, 0x1f7c, parameters.store_pipeline); + put_u32(raw, 0x1f98, parameters.partial_store_pipeline_bind as u32); + put_u64(raw, 0x1f9c, parameters.partial_store_pipeline); + put_u32(raw, 0x1fa8, parameters.depth_clear_value_bits); + put_u64(raw, 0x1fac, (parameters.tib_blocks << 33) | 0x300); + // Native copies isMemorylessRender through the UMD render record +0x240, + // parsed record +0x1b8, and host descriptor +0x8bf into this byte. It is + // not a TIB-size predicate: native's memoryless policy also selects the + // shortened SPM phase programs. The admitted render UAPI represents + // memory-backed resources and has no memoryless-render policy or matching + // SPM-program construction. Keep that policy clear even for >8 TIB + // blocks; supporting memoryless renders requires modeling both together. + // Empty-tile processing remains independent in register 0x10039 bit 16. + put_u8(raw, 0x2100, 0); + // Exact G17P tail copied by AGX3DChannelSKSM::submitBuffer. +0x2104 is the + // accelerator control snapshot and +0x210c its low map nibble. +0x2110 is + // a separate render-setup field: prepare copies descriptor +0xc00 to setup + // +0x818, processRenderSetup carries it to +0x89c, and submitBuffer emits + // it here. Working Metal commands carry the invariant all-ones value. + put_u32(raw, 0x2104, parameters.gpc_perf_state_control); + // AGX3DChannelSKSM::submitBuffer mirrors the same dependency/current pair + // consumed by the fragment RCE program into the firmware command. + put_u32(raw, 0x2108, (parameters.fragment_lifecycle >> 32) as u32); + put_u32(raw, 0x210c, parameters.gpc_perf_state_map_low); + put_u32(raw, 0x2110, G17P_FRAGMENT_TAIL_SETUP_WORD); + // Native submitBuffer zeros +0x2114..+0x2123. Sampler state reaches the + // GPU through its real register/program path, not these command-tail + // lanes. The first two following flag lanes reproduce the working Neo + // shared-runtime snapshot; the final two come from per-command descriptor + // bytes and retain their constructor-zero values until those inputs are + // modeled. + put_u32( + raw, + 0x2124, + G17P_NEO_FRAGMENT_SHARED_RUNTIME_FLAG_SNAPSHOT[0], + ); + put_u32( + raw, + 0x2128, + G17P_NEO_FRAGMENT_SHARED_RUNTIME_FLAG_SNAPSHOT[1], + ); + put_u64(raw, 0x2168, parameters.fragment_lifecycle as u32 as u64); + put_u64(raw, 0x2198, parameters.fragment_timestamp_start); + put_u64(raw, 0x21a0, parameters.fragment_timestamp_end); + // +0x21a8/+0x21b0: caller-visible destinations, zero as in the TA record. + put_u8(raw, 0x21cc, 0x53); + put_u8(raw, 0x21d6, 1); + put_u8(raw, 0x21e7, parameters.context_generation); + put_u8(raw, 0x2208, 1); + put_u8(raw, 0x220c, 1); + put_u8(raw, 0x222d, g17p_frg_hwdsid_mode()); + Ok(()) +} + +/// FRG +0x222d mode byte: Linux has always written 1; all 160 native light +/// FRG captures hold 0. +fn g17p_frg_hwdsid_mode() -> u8 { + 1 +} + diff --git a/drivers/gpu/drm/asahi/m5/render_target.rs b/drivers/gpu/drm/asahi/m5/render_target.rs new file mode 100644 index 0000000000000..a277377cb5851 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/render_target.rs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Render-target allocation geometry and M5 viewport state. + +pub(crate) const PAGE_BYTES: usize = 0x4000; +pub(crate) const AUX_BYTES: usize = 0x8000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct M5RenderTargetLayout { + pub(crate) tilemap_bytes: usize, + pub(crate) heapmeta_offset: usize, + pub(crate) heapmeta_bytes: usize, + pub(crate) target_bytes: usize, + pub(crate) tpc_bytes: usize, +} + +fn align(value: usize, alignment: usize) -> Option { + Some(value.checked_add(alignment - 1)? & !(alignment - 1)) +} + +impl M5RenderTargetLayout { + pub(crate) fn new( + width: u32, height: u32, layers: u16, utile_width: u8, utile_height: u8, + clusters: u32, + ) -> Option { + if !(1..=16384).contains(&width) || !(1..=16384).contains(&height) + || !(1..=2048).contains(&layers) || clusters == 0 + || !matches!((utile_width, utile_height), (32, 32) | (32, 16) | (16, 16)) { + return None; + } + // Same 4x4 macrotile geometry as the register builders. M5 packs its + // boundaries in ten-bit fields; that does not change allocation size. + let tiles_x = (width as usize + 31) / 32; + let tiles_y = (height as usize + 31) / 32; + let per_mtile = align((tiles_x + 3) / 4, 4)? + .checked_mul(align((tiles_y + 3) / 4, 4)?)?; + let utiles = (32 / utile_width as usize) * (32 / utile_height as usize); + let tilemap_bytes = align(5usize.checked_mul(per_mtile)?.checked_mul(utiles)?, 4)? + .checked_mul(16)?.checked_mul(layers as usize)?; + let heapmeta_offset = align(tilemap_bytes, 0x1000)?; + let heapmeta_bytes = if layers > 1 { 0x300 } else { 0x200 }; + let target_bytes = align(heapmeta_offset.checked_add(heapmeta_bytes)?, PAGE_BYTES)?; + let tpc_bytes = align(8usize.checked_mul(per_mtile)?.checked_mul(utiles)? + .checked_mul(16)?.checked_mul(layers as usize)? + .checked_mul(clusters as usize)?, PAGE_BYTES)?; + Some(Self { tilemap_bytes, heapmeta_offset, heapmeta_bytes, target_bytes, tpc_bytes }) + } +} + +fn half_float_bits(value: u32) -> u32 { + // The admitted integer dimensions are exactly representable in binary32. + let highest = 31 - value.leading_zeros(); + ((highest + 126) << 23) | ((value << (23 - highest)) & 0x7fffff) +} + +/// Native M5 deflake page: viewport at +0x9c0, command header 0x3000. +/// G17P uses +0x900/0xc00 and must not supply this page. The eight nonzero +/// dwords match the M5 25G76 resource capture; dimensions are caller-owned. +pub(crate) fn initialize_deflake(page: &mut [u8], width: u32, height: u32) -> Option<()> { + if page.len() != PAGE_BYTES || !(1..=16384).contains(&width) + || !(1..=16384).contains(&height) { return None; } + page.fill(0); + let x = half_float_bits(width); + let y = half_float_bits(height); + for (offset, value) in [(0x9c0, 0x3000), + (0x9c4, 0x80000000 | ((width + 31) / 32 - 1)), + (0x9c8, (height + 31) / 32 - 1), (0x9d0, x), (0x9d4, x), + (0x9d8, y), (0x9dc, y | 0x80000000), (0x9e4, 0x3f800000)] { + page[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + Some(()) +} + diff --git a/drivers/gpu/drm/asahi/m5/resources.rs b/drivers/gpu/drm/asahi/m5/resources.rs new file mode 100644 index 0000000000000..30d94f4d97148 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources.rs @@ -0,0 +1,631 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +#![allow(dead_code)] + +//! Retained RAM for the J813 G17G/25G76 initialization graph. +//! +//! Construction only: no processor start, mailbox publication, work submission +//! or DRM registration. The eventual boot session must retain this entire +//! owner until BOTH firmware processors are stopped, including on failure. +//! M5 UAT lifecycle admission remains separate from this memory layout. + +use super::mapped::MappedObject; +use crate::{driver::AsahiDrmDevice, m5::initdata as init, mmu}; +use crate::m5::completion::{graphics_pointer_head, MAX_GRAPHICS_GENERATION}; +use core::sync::atomic::{fence, Ordering}; +use kernel::prelude::*; +use kernel::sync::Arc; + +mod firmware_view; +mod graphics_memory; +mod graphics_usc; +mod parameter_buffer; +mod target_memory; +mod graphics_job; +mod graphics_queues; +mod application_compute; + +const KERNEL_BASE: u64 = 0xffff_fc20_0000_0000; +const PRIVATE_BASE: u64 = KERNEL_BASE + 0x2_0000; +const ROOTS_BASE: u64 = KERNEL_BASE + 0x1a_8000; +const SHARED_BASE: u64 = KERNEL_BASE + 0xc078_8000; +const FWCTL_BASE: u64 = KERNEL_BASE + 0x1c_0000; +const SENTINEL_BASE: u64 = KERNEL_BASE + 0xc07e_0000; +const PBDESC_BASE: u64 = KERNEL_BASE + 0x15e_0000; +const UMA_BASE: u64 = KERNEL_BASE + 0x15e_8000; + +/// Owning mappings are dropped before the UAT. Aliases retain the SAME GEM +/// backing; no firmware pointer refers to a copied snapshot or temporary map. +pub(crate) struct M5FirmwareMemory { + primary_root: MappedObject, + secondary_root: MappedObject, + shared: MappedObject, + private: MappedObject, + region_a: MappedObject, + region_c: MappedObject, + fwctl: MappedObject, + aon: MappedObject, + qos: MappedObject, + pbdesc: MappedObject, + uma: MappedObject, + completions: KVec, + aliases: KVec, + registers: KVec, + graphics: Option<(graphics_job::M5GraphicsJob, graphics_queues::M5GraphicsQueues)>, + application_compute: Option, + application_outer_head: u32, + report_counts: [[u32; 2]; 2], + trace_printed: [u32; 2], + compute_kick_observed: bool, + compute_dispatch_returned: bool, + graphics_stamp_flags: u128, + uat: Arc, +} + +impl M5FirmwareMemory { + /// Internal defaults for the initial M5 render-state envelope. The DRM + /// translator replaces all program/input addresses, and owned target + /// allocation replaces private storage before any queue publication. + pub(crate) fn reference_render_profile() -> + (crate::m5::render_desc::G17pRenderParameters, crate::m5::render::M5RenderControls) { + graphics_job::triangle_parameters() + } + + /// All fallible preparation happens before publication. The caller must + /// pass a prepared M5 UAT while both processors await initdata. The + /// caller retains its own Arc until both CPUs stop, including when this + /// unpublished graph fails construction. There is no Neo tuning fallback. + #[inline(never)] + pub(crate) fn new_with_uat( + dev: &AsahiDrmDevice, + uat: Arc, + boot_timestamp: u64, + ) -> Result> { + let memory = Self::allocate_with_uat(dev, uat, boot_timestamp)?; + fence(Ordering::SeqCst); + Ok(memory) + } + + #[inline(never)] + fn allocate_with_uat( + dev: &AsahiDrmDevice, + uat: Arc, + boot_timestamp: u64, + ) -> Result> { + let mut registers = KVec::new(); + for window in init::M5_25G76_REGISTER_WINDOWS { + let (physical, virtual_address, span) = window.mapped_pages().map_err(|_| EINVAL)?; + let protection = match window.flag { + 0 => mmu::PROT_FW_MMIO_RO, + 2 => mmu::PROT_FW_MMIO_RW, + _ => return Err(EINVAL), + }; + // Page-table writes only. No register contents are accessed. + registers.push(uat.kernel_vm().map_io(dev.as_ref().as_ref(), virtual_address, physical.try_into()?, + span.try_into()?, protection)?, GFP_KERNEL)?; + } + let fixed = |address, size, protection| MappedObject::new_wc_at( + dev, uat.kernel_vm(), address, size, protection); + // Install every fixed address before allocator-selected objects. + let mut private = fixed(PRIVATE_BASE, init::M5_25G76_PRIVATE_CLUSTER_SIZE, mmu::PROT_FW_SHARED_RW)?; + // Separate mappings retain the empty page between the two roots. + let mut primary_root = fixed(ROOTS_BASE, init::ROOT_SIZE_PRIMARY, mmu::PROT_FW_SHARED_RO)?; + let mut secondary_root = fixed(ROOTS_BASE + init::SECONDARY_ROOT_DELTA, + init::ROOT_SIZE_SECONDARY, mmu::PROT_FW_SHARED_RO)?; + let mut shared = fixed(SHARED_BASE, init::NATIVE_SHARED_CLUSTER_SIZE, mmu::PROT_FW_PRIV_RW)?; + let region_a = fixed(KERNEL_BASE + 0x1b_8000, init::REGION_A_SIZE, mmu::PROT_FW_SHARED_RO)?; + let mut region_c = fixed(KERNEL_BASE + 0x1a_0000, init::REGION_C_SIZE, mmu::PROT_FW_SHARED_RO)?; + let fwctl = fixed(FWCTL_BASE, 0x4000, mmu::PROT_FW_SHARED_RW)?; + // These two tables have zero-backed mappings at handoff. Mode6 + // prepares its own UMA slot before any compute publication. + let mut pbdesc = fixed(PBDESC_BASE, 0x4000, mmu::PROT_FW_SHARED_RW)?; + let mut uma = fixed(UMA_BASE, 0x4000, mmu::PROT_FW_SHARED_RW)?; + let mut aliases = KVec::new(); + for (object, address) in [(&mut pbdesc, init::REGION_VIEW_LOW_ADDRS[0]), + (&mut uma, init::REGION_VIEW_LOW_ADDRS[1])] { + aliases.push(object.map_alias_at(uat.kernel_lower_vm(), address, + mmu::PROT_GPU_SHARED_RW)?, GFP_KERNEL)?; + if uat.kernel_vm().translate_iova(object.iova())? + != uat.kernel_lower_vm().translate_iova(address)? { + return Err(EFAULT); + } + } + + let mut completions = KVec::new(); + let mut completion_bindings = [init::G17PKsmCompletionAliases { low: 0, high: 0 }; 4]; + for (ordinal, binding) in completion_bindings.iter_mut().enumerate() { + // The fixed alias pairs are measured on M5, including ordinals + // 1 and 3 which are absent from the older Neo initialization. + let low = 0x70_0184_8000 + ordinal as u64 * 0x2_8000; + let high = KERNEL_BASE + 0xc07e_8000 + ordinal as u64 * 0x2_8000; + let mut backing = MappedObject::new_wc_at(dev, uat.kernel_vm(), high, + init::M5_25G76_COMPLETION_BACKING_SIZE, mmu::PROT_FW_PRIV_RW)?; + aliases.push(backing.map_alias_at(uat.kernel_lower_vm(), low, + mmu::PROT_GPU_SHARED_RW)?, GFP_KERNEL)?; + for offset in (0..init::M5_25G76_COMPLETION_BACKING_SIZE).step_by(mmu::UAT_PGSZ) { + if uat.kernel_vm().translate_iova(high + offset as u64)? + != uat.kernel_lower_vm().translate_iova(low + offset as u64)? { + return Err(EFAULT); + } + } + *binding = init::G17PKsmCompletionAliases { low, high }; + completions.push(backing, GFP_KERNEL)?; + } + // Keep allocator-selected objects below the high fixed graph, and + // above the PB/UMA tables. This cannot occupy the deferred blank + // sentinel address or its neighboring guard page. + let dynamic = KERNEL_BASE + 0x168_0000..KERNEL_BASE + 0x1000_0000; + let qos = MappedObject::new_wc_in_range(dev, uat.kernel_vm(), dynamic.clone(), + 0xe40, mmu::UAT_PGSZ as u64, + mmu::PROT_FW_SHARED_RW)?; + let mut aon = MappedObject::new_wc_in_range(dev, uat.kernel_vm(), dynamic, + init::M5_25G76_AON_PTD_SIZE, + mmu::UAT_PGSZ as u64, mmu::PROT_FW_PRIV_RW)?; + aon.with_bytes_mut(|out| init::encode_m5_25g76_aon_ptd(out).map_err(|_| EINVAL))?; + region_c.with_bytes_mut(|out| init::encode_region_c_for_profile( + init::RootProfile::J813G17G25G76, out).map_err(|_| EINVAL))?; + private.with_bytes_mut(|out| init::encode_m5_25g76_private_cluster( + FWCTL_BASE, out).map_err(|_| EINVAL))?; + + let addresses = init::SharedAddresses { + region_a: region_a.iova(), region_c: region_c.iova(), + hw_data_bundle: SHARED_BASE, hw_data_bundle_alloc: init::NATIVE_SHARED_CLUSTER_SIZE, + }; + let primary = init::InstanceAddresses { + root: ROOTS_BASE, main_config: SHARED_BASE + init::NATIVE_PRIMARY_MAIN_BUNDLE_OFFSET as u64, + status_a: PRIVATE_BASE + 0xee40, status_b: PRIVATE_BASE + 0x340, + secondary_extras: [0, 0], + }; + let secondary = init::InstanceAddresses { + root: ROOTS_BASE + init::SECONDARY_ROOT_DELTA, + main_config: SHARED_BASE + init::NATIVE_SECONDARY_MAIN_BUNDLE_OFFSET as u64, + status_a: PRIVATE_BASE + 0xc3100, status_b: 0, + secondary_extras: [primary.status_b + init::PRIMARY_STATUS_B_CONFIG_OFFSET as u64, + PRIVATE_BASE + 0x177400], + }; + let views = init::PrimaryRegionViews { + sentinel_high: SENTINEL_BASE, alias_high: [PBDESC_BASE, UMA_BASE], + }; + let trace_mask = crate::module_parameters::m5_fw_trace.value(); + if trace_mask & !0x203 != 0 { return Err(EINVAL); } + // Exact M5 GFX firmware 0x1fadc retains root+0xa8 (status A), + // then 0x3074..0x3088 copies status-A+0 into its trace flags. + // Bits 0 and 1 gate power/submission records; 0x6260 reads the + // NEXT byte and tests bit 1 (full-word bit 9) for recovery summary + // 0x909. Publish through the host field before either descriptor. + let native_trace = private.read_u32(primary.status_a)?; + private.write_u32(primary.status_a, native_trace | trace_mask)?; + shared.with_bytes_mut(|out| { + init::encode_m5_25g76_hw_data(completion_bindings, qos.iova(), + &mut out[..init::M5_25G76_HW_DATA_SIZE]).map_err(|_| EINVAL)?; + init::encode_m5_25g76_bundle_policy(init::M5PolicyBindings { + state: PRIVATE_BASE + 0x177480, aon_ptd: aon.iova(), boot_timestamp, + }, out).map_err(|_| EINVAL)?; + for (role, instance, grid, views) in [ + (init::InstanceRole::Primary, &primary, PRIVATE_BASE, Some(&views)), + (init::InstanceRole::Secondary, &secondary, PRIVATE_BASE + 0x1770c0, None), + ] { + let channels = init::derive_channel_table(role, grid, instance.status_a, + instance.main_config, SHARED_BASE); + let offset = (instance.main_config - SHARED_BASE) as usize; + init::encode_main_config_for_profile(init::RootProfile::J813G17G25G76, + role, &addresses, instance, &channels, views, + &mut out[offset..offset + init::MAIN_CONFIG_SIZE]).map_err(|_| EINVAL)?; + } + Ok(()) + })?; + primary_root.with_bytes_mut(|out| { + init::encode_root_for_profile(init::RootProfile::J813G17G25G76, + init::InstanceRole::Primary, &addresses, &primary, + out).map_err(|_| EINVAL) + })?; + secondary_root.with_bytes_mut(|out| { + init::encode_root_for_profile(init::RootProfile::J813G17G25G76, + init::InstanceRole::Secondary, &addresses, &secondary, + out).map_err(|_| EINVAL) + })?; + // Unlike PB/UMA, this future blank sentinel is unmapped at native + // handoff. It becomes zero-backed later in macOS initialization. + if uat.kernel_vm().translate_iova(SENTINEL_BASE).is_ok() { + return Err(EINVAL); + } + // Writes to all CPU WC mappings precede any future handoff. Only + // the two measured control openings are present; work rings and + // later compute/render descriptors remain unsubmitted. + fence(Ordering::SeqCst); + // Keep the retained graph off the kernel stack, including + // construction and error-return temporaries in the boot caller. + KBox::init(try_init!(Self { primary_root, secondary_root, shared, private, region_a, region_c, fwctl, aon, qos, + pbdesc, uma, completions, aliases, registers, graphics: None, + report_counts: [[0; 2]; 2], trace_printed: [0; 2], + compute_kick_observed: false, compute_dispatch_returned: false, + graphics_stamp_flags: 0, application_compute: None, + application_outer_head: 0, uat }), GFP_KERNEL) + } + + /// Prepare a first application job while retaining its actual VM. No + /// native program bundle or captured input/output pages are requested. + /// The caller has validated the command and all user mapping coverage. + #[allow(clippy::too_many_arguments)] + pub(crate) fn initialize_application_graphics( + &mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm, + parameters: crate::m5::render_desc::G17pRenderParameters, + controls: crate::m5::render::M5RenderControls, clusters: u32, + usc_required: [u64; 2], + ) -> Result { + if self.graphics.is_some() { return Err(EBUSY); } + let job = graphics_job::M5GraphicsJob::from_vm( + dev, &self.uat, vm, parameters, controls, clusters, usc_required)?; + self.attach_graphics(dev, job) + } + + fn attach_graphics(&mut self, dev: &AsahiDrmDevice, job: graphics_job::M5GraphicsJob) -> Result { + if self.graphics.is_some() { return Err(EBUSY); } + let queues = graphics_queues::M5GraphicsQueues::new(dev, &self.uat, &job)?; + let pb = job.parameter_descriptor()?; + self.pbdesc.with_bytes_mut(|out| { + let base = graphics_job::PB_HARDWARE_ID as usize * 16; + for (index, word) in pb.into_iter().enumerate() { + out[base + index * 4..base + index * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + Ok(()) + })?; + let usc = job.uma_descriptor(); + self.uma.with_bytes_mut(|out| { + let base = graphics_usc::HARDWARE_ID as usize * 32; + for (index, word) in usc.into_iter().enumerate() { + out[base + index * 8..base + index * 8 + 8].copy_from_slice(&word.to_le_bytes()); + } + Ok(()) + })?; + self.graphics = Some((job, queues)); + Ok(()) + } + + pub(crate) fn quarantine_graphics(&self) { + if let Some((job, _)) = &self.graphics { job.quarantine(); } + } + + /// Drain M5 report channels using the native producer contracts. + /// GFX 0x6ca8..0x6d18 emits 256 x 0x48 event records; 0x17e18 + /// emits 512 x 0x48 trace records. In each cursor object the host owns + /// +0 and firmware owns +0x20. Copy before releasing each slot. + pub(crate) fn drain_reports(&mut self, dev: &AsahiDrmDevice) -> Result { + let mut recovery = false; + for (role, status_offset) in [0xee40u64, 0xc3100].into_iter().enumerate() { + for (channel, (cursor_offset, ring_offset, capacity)) in + [(0x40u64, 0x2c0u64, 256u32), (0x240, 0xa6ac0, 512)] + .into_iter().enumerate() { + let cursor = PRIVATE_BASE + status_offset + cursor_offset; + let ring = (status_offset + ring_offset) as usize; + for _ in 0..128 { + let consumer = self.private.read_u32(cursor)?; + let producer = self.private.read_u32(cursor + 0x20)?; + if consumer >= capacity || producer >= capacity { return Err(EIO); } + if consumer == producer { break; } + fence(Ordering::Acquire); + let offset = ring + consumer as usize * 0x48; + let mut raw = [0u8; 0x48]; + self.private.with_bytes_mut(|bytes| { + raw.copy_from_slice(bytes.get(offset..offset + 0x48).ok_or(EINVAL)?); + Ok(()) + })?; + let word = |off: usize| u32::from_le_bytes(raw[off..off + 4].try_into().unwrap()); + let qword = |off: usize| u64::from_le_bytes(raw[off..off + 8].try_into().unwrap()); + let count = self.report_counts[role][channel]; + if channel == 0 { + // Type 1 (graphics stamps) arrives for every job. + if word(0) == 1 { + dev_dbg!(dev.as_ref(), "M5_EVENT role={} ordinal={} type={} payload={:x?}\n", + role, count, word(0), [qword(4), qword(12), qword(20), qword(28), qword(36)]); + } else { + dev_dbg!(dev.as_ref(), "M5_EVENT role={} ordinal={} type={} payload={:x?}\n", + role, count, word(0), [qword(4), qword(12), qword(20), qword(28), qword(36)]); + } + recovery |= word(0) == 4; + if role == 0 && word(0) == 1 { + self.graphics_stamp_flags |= u128::from(qword(4)) + | (u128::from(qword(12)) << 64); + } + } else { + let args = [qword(12), qword(20), qword(28), qword(36)]; + // This one-shot diagnostic owns qid11/stamp1. The + // exact M5 trace point precedes the hardware kick; + // the admission probe also requires its later callback + // return trace. Firmware-private counters can be cached. + if role == 0 && word(0) == 5 && word(44) == 0x41 + && args == [11, 1, 2, 1] { + self.compute_kick_observed = true; + } + // 0x26aa4 invokes the pending-work callback, which + // dispatches tag14 and writes SGX+0x21018 at0x11f5c. + // 0x26ac4 emits 0x130 only after that callback returns. + if role == 0 && self.compute_kick_observed && word(0) == 5 + && word(44) == 0x130 && args == [4, 0, 0, 0] { + self.compute_dispatch_returned = true; + } + // Exact M5 0x24eb4/0x26754 emit zero-argument + // processing-loop brackets. Count and consume them + // without spending the diagnostic print budget. + let loop_marker = word(0) == 5 && args == [0; 4] + && matches!(word(44) & 0x00ff_ffff, 0x105 | 0x106); + if !loop_marker && self.trace_printed[role] < if role == 0 { 512 } else { 16 } { + dev_dbg!(dev.as_ref(), "M5_TRACE role={} ordinal={} timestamp={} type={} id={:#x} args={:x?}\n", + role, count, qword(4), word(0), word(44), args); + self.trace_printed[role] += 1; + } + } + self.report_counts[role][channel] = count.saturating_add(1); + fence(Ordering::SeqCst); + self.private.write_u32(cursor, (consumer + 1) % capacity)?; + } + } + } + Ok(recovery) + } + + pub(crate) fn graphics_status(&mut self) -> Result<([u32; 3], [[u32; 3]; 2], [u32; 5])> { + let mut outer = [0; 3]; + let base = init::WORK_STATE_GRID_OFFSETS[8]; + for index in 0..3 { + outer[index] = self.private.read_u32(PRIVATE_BASE + + (base + index * init::CHANNEL_STATE_SPACING) as u64)?; + } + let (job, queues) = self.graphics.as_mut().ok_or(EINVAL)?; + Ok((outer, queues.counters()?, job.progress()?)) + } + + pub(crate) fn graphics_completion(&mut self) -> Result { + let (job, queues) = self.graphics.as_mut().ok_or(EINVAL)?; + let progress = job.progress()?; + let scheduler = job.scheduler_status()?; + Ok(crate::m5::completion::M5GraphicsCompletion { + submitted: progress[0], completed: scheduler[0], linked: scheduler[1], + list: queues.completion_list()?, stamps: [progress[1], progress[3]], + signalled: self.graphics_stamp_flags, + }) + } + + pub(crate) fn graphics_pair_complete( + completion: crate::m5::completion::M5GraphicsCompletion, + generation: u32, + ) -> bool { + (1..=MAX_GRAPHICS_GENERATION).contains(&generation) + && completion.pair_complete_at(graphics_queues::JOB_LIST, generation * 0x100) + } + + pub(crate) fn graphics_installation_status(&mut self) -> Result<([[u64; 5]; 2], [u64; 2], [u64; 2])> { + self.graphics.as_mut().ok_or(EINVAL)?.1.installation_status() + } + + pub(crate) fn graphics_queues_installed(&mut self) -> Result { + self.graphics.as_mut().ok_or(EINVAL)?.1.installed() + } + + pub(crate) fn publish_graphics_install(&mut self) -> Result { + let (outer, inner, progress) = self.graphics_status()?; + if outer != [0; 3] || inner != [[0, 0, 1]; 2] + || progress != [2, 0, 0, 0, 0] { return Err(EBUSY); } + if self.graphics_installation_status()? != ([[0; 5]; 2], [0; 2], [0xffff, 0]) { + return Err(EBUSY); + } + self.publish_graphics_records(0, 1) + } + + pub(crate) fn publish_graphics_job(&mut self) -> Result { + let (outer, inner, progress) = self.graphics_status()?; + if outer != [2; 3] || inner != [[1; 3]; 2] + || progress != [2, 0, 0, 0, 0] { return Err(EBUSY); } + let (job, queues) = self.graphics.as_mut().ok_or(EINVAL)?; + if !queues.installed()? { return Err(EBUSY); } + self.graphics_stamp_flags = 0; + job.publish_context()?; + queues.publish_draw()?; + self.publish_graphics_records(2, 4) + } + + /// Reuse only a fully retired pair, replacing its application descriptors + /// while preserving firmware-owned PB/USC state and the installed queues. + #[allow(clippy::too_many_arguments)] + /// A different submitting VM takes over the retired job in place: same + /// context slot, descriptor graph, queues and PB/USC pools. The compute + /// owner shares that context, so its operands follow the job. + fn hand_off_application(&mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm) -> Result { + let (job, _) = self.graphics.as_mut().ok_or(EINVAL)?; + if job.owns_vm(vm) { return Ok(()); } + job.rebind_vm(dev, vm).inspect_err(|e| pr_err!("M5: rebind_vm failed: {:?}\n", e))?; + job.publish_context().inspect_err(|e| pr_err!("M5: publish_context failed: {:?}\n", e))?; + Ok(()) + } + + pub(crate) fn publish_next_application_job( + &mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm, + parameters: crate::m5::render_desc::G17pRenderParameters, + controls: crate::m5::render::M5RenderControls, clusters: u32, + usc_required: [u64; 2], generation: u32, + ) -> Result { + if !(2..=MAX_GRAPHICS_GENERATION).contains(&generation) { return Err(EINVAL); } + let previous = generation - 1; + let (outer, inner, _) = self.graphics_status()?; + if outer != [self.application_outer_head; 3] + || inner != [[graphics_pointer_head(previous); 3]; 2] + || !Self::graphics_pair_complete(self.graphics_completion()?, previous) { + return Err(EBUSY); + } + self.hand_off_application(dev, vm)?; + let (job, queues) = self.graphics.as_mut().ok_or(EINVAL)?; + job.prepare_application_frame(dev, vm, parameters, controls, clusters, + usc_required, generation).inspect_err(|e| pr_err!("M5: prepare_application_frame failed: {:?}\n", e))?; + queues.publish_next_draw(job, generation).inspect_err(|e| pr_err!("M5: publish_next_draw failed: {:?}\n", e))?; + self.graphics_stamp_flags = 0; + self.publish_graphics_records(self.application_outer_head as usize, + graphics_pointer_head(generation) as u16) + } + + fn publish_graphics_records(&mut self, outer_index: usize, inner_head: u16) -> Result { + // Only recycle storage after every outer consumer reaches the old + // producer. The application caller also requires paired retirement. + if outer_index >= 256 || self.graphics_status()?.0 != [outer_index as u32; 3] { + return Err(EBUSY); + } + self.shared.with_bytes_mut(|out| { + for stage in 0..2 { + let offset = init::WORK_RING_BUNDLE_OFFSETS[8] + ((outer_index + stage) % 256) * 24; + let record = &mut out[offset..offset + 24]; + record.fill(0); + let address = graphics_queues::M5GraphicsQueues::queue_address(stage)?; + record[8..16].copy_from_slice(&address.to_le_bytes()); + record[16..20].copy_from_slice(&2u32.to_le_bytes()); + record[20..22].copy_from_slice(&inner_head.to_le_bytes()); + record[22] = graphics_job::QUEUE_IDS[stage]; + record[23] = 1; + } + Ok(()) + })?; + fence(Ordering::SeqCst); + // Both stage-tagged SKSM queues travel through the CL_2 command ring. + let producer = init::WORK_STATE_GRID_OFFSETS[8] + 2 * init::CHANNEL_STATE_SPACING; + self.private.write_u32(PRIVATE_BASE + producer as u64, ((outer_index + 2) % 256) as u32)?; + self.application_outer_head = ((outer_index + 2) % 256) as u32; + fence(Ordering::SeqCst); + Ok(()) + } + + pub(crate) fn application_outer_head(&self) -> u32 { self.application_outer_head } + + /// Initial admission is deliberately one compute job after retired graphics. + /// No private diagnostic context, queue 11, or replacement UMA is installed. + pub(crate) fn initialize_application_compute(&mut self, dev: &AsahiDrmDevice, + vm: &mmu::Vm, command: &crate::m5::command::TranslatedComputeCommand, + graphics_generation: u32) -> Result { + if self.application_compute.is_some() || self.application_outer_head + 2 > 256 { + return Err(ENOTSUPP); + } + let (outer, inner, _) = self.graphics_status()?; + if graphics_generation == 0 || outer != [self.application_outer_head; 3] + || inner != [[graphics_pointer_head(graphics_generation); 3]; 2] + || !Self::graphics_pair_complete(self.graphics_completion()?, graphics_generation) { + return Err(EBUSY); + } + self.hand_off_application(dev, vm)?; + let job = &self.graphics.as_ref().ok_or(EINVAL)?.0; + self.application_compute = Some(application_compute::M5ApplicationCompute::new( + dev, &self.uat, job, command)?); + Ok(()) + } + + pub(crate) fn application_compute_installed(&mut self) -> Result { + let compute = self.application_compute.as_mut().ok_or(EINVAL)?; + Ok(compute.counters()? == [1; 3] && compute.installed()?) + } + + /// Publish one command-ring record for queue 12. `dispatch` false is the + /// installation record; true is dispatch generation `generation`, whose + /// inner head is the producer that generation's three pointers reach. + pub(crate) fn publish_application_compute(&mut self, dispatch: bool, + generation: u32) -> Result { + let outer_index = self.application_outer_head as usize; + if outer_index >= 256 || self.graphics_status()?.0 != [outer_index as u32; 3] { + return Err(EBUSY); + } + let inner_head = u16::try_from(application_compute::compute_pointer_head( + if dispatch { generation } else { 0 })).map_err(|_| EINVAL)?; + let compute = self.application_compute.as_mut().ok_or(EINVAL)?; + if dispatch { + // Preserve the retired graphics notifications for later render reuse. + self.graphics_stamp_flags &= !(1u128 << application_compute::QUEUE_ID); + compute.publish_dispatch(generation)?; + } else if compute.counters()? != [0, 0, 1] { return Err(EBUSY); } + let offset = init::WORK_RING_BUNDLE_OFFSETS[8] + outer_index * 24; + self.shared.with_bytes_mut(|out| { + let record = &mut out[offset..offset + 24]; + // Every outer consumer reached this slot (checked above), so its + // prior user, graphics or compute, has retired. Graphics records + // wrap this ring after 128 renders, so even the first compute + // record can land on a used slot. + record.fill(0); + record[8..16].copy_from_slice( + &application_compute::M5ApplicationCompute::queue_address().to_le_bytes()); + record[16..20].copy_from_slice(&2u32.to_le_bytes()); + record[20..22].copy_from_slice(&inner_head.to_le_bytes()); + record[22] = application_compute::QUEUE_ID; + record[23] = 1; + Ok(()) + })?; + fence(Ordering::SeqCst); + let head = ((outer_index + 1) % 256) as u32; + let producer = init::WORK_STATE_GRID_OFFSETS[8] + 2 * init::CHANNEL_STATE_SPACING; + self.private.write_u32(PRIVATE_BASE + producer as u64, head)?; + self.application_outer_head = head; + fence(Ordering::SeqCst); + Ok(()) + } + + /// Stage a further dispatch on the already installed compute queue. The + /// installed owner keeps its VM, USC and operand storage; only the command + /// stream and the generation's stamps change. + pub(crate) fn prepare_next_application_compute(&mut self, dev: &AsahiDrmDevice, + vm: &mmu::Vm, command: &crate::m5::command::TranslatedComputeCommand, + generation: u32) -> Result { + if !(2..=MAX_GRAPHICS_GENERATION).contains(&generation) { return Err(EINVAL); } + self.hand_off_application(dev, vm)?; + let (job, _) = self.graphics.as_ref().ok_or(EINVAL)?; + self.application_compute.as_mut().ok_or(EINVAL)? + .prepare_next_dispatch(job, command, generation) + } + + pub(crate) fn application_compute_complete(&mut self, generation: u32) -> Result { + let (outer, _, _) = self.graphics_status()?; + Ok(outer == [self.application_outer_head; 3] + && self.application_compute.as_mut().ok_or(EINVAL)? + .complete(self.graphics_stamp_flags, generation)?) + } + + pub(crate) fn application_compute_status(&mut self) + -> Result<([u32; 3], crate::m5::completion::M5ComputeCompletion)> { + let compute = self.application_compute.as_mut().ok_or(EINVAL)?; + Ok((compute.counters()?, compute.completion(self.graphics_stamp_flags)?)) + } + + pub(crate) fn publish_idle_wake(&mut self) -> Result { + if self.control_counters()? != [[1; 3]; 2] { return Err(EBUSY); } + self.shared.with_bytes_mut(|out| { + let record = &mut out[0x1eac0..0x1eb00]; + if record.iter().any(|x| *x != 0) { return Err(EBUSY); } + record[..4].copy_from_slice(&0x0au32.to_le_bytes()); + Ok(()) + })?; + fence(Ordering::SeqCst); + let producer = init::WORK_STATE_GRID_OFFSETS[init::CONTROL_CHANNEL_INDEX] + + 2 * init::CHANNEL_STATE_SPACING; + self.private.write_u32(PRIVATE_BASE + producer as u64, 2)?; + fence(Ordering::SeqCst); + Ok(()) + } + + pub(crate) fn root(&self, secondary: bool) -> u64 { + if secondary { self.secondary_root.iova() } else { self.primary_root.iova() } + } + + /// Read the actual shared control state, not a detached host copy. The + /// offsets and three pointers per role are checked by the M5 capture + /// verifier against both native main objects and the private arena. + pub(crate) fn control_counters(&mut self) -> Result<[[u32; 3]; 2]> { + self.private.with_bytes_mut(|bytes| { + let mut counters = [[0; 3]; 2]; + for (role, grid) in [0usize, 0x1770c0].into_iter().enumerate() { + let base = grid + init::WORK_STATE_GRID_OFFSETS[init::CONTROL_CHANNEL_INDEX]; + for (index, value) in counters[role].iter_mut().enumerate() { + let offset = base + index * init::CHANNEL_STATE_SPACING; + let word = bytes.get(offset..offset + 4).ok_or(EINVAL)?; + // SAFETY: arena and native counter offsets are u32 aligned; + // this bounded WC mapping is retained while firmware runs. + *value = unsafe { core::ptr::read_volatile(word.as_ptr().cast::()) }; + } + } + fence(Ordering::Acquire); + Ok(counters) + }) + } + +} diff --git a/drivers/gpu/drm/asahi/m5/resources/application_compute.rs b/drivers/gpu/drm/asahi/m5/resources/application_compute.rs new file mode 100644 index 0000000000000..4f84edbd0875b --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/application_compute.rs @@ -0,0 +1,305 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! One application compute dispatch sharing the retained graphics VM and USC. +//! +//! Queue 12 is separate from TA/fragment queues 10/11. All publication and +//! completion gates are explicit; constructing this owner does not submit it. + +use super::{graphics_job::M5GraphicsJob, graphics_usc, + firmware_view::FirmwareDataView, MappedObject}; +use crate::{driver::AsahiDrmDevice, m5::submission, m5::command, + m5::channel, m5::completion::{graphics_pointer_head, GRAPHICS_POINTER_COUNT, + MAX_GRAPHICS_GENERATION}, m5::compute, m5::sksm, mmu}; +use kernel::prelude::*; + +pub(super) const QUEUE_ID: u8 = 12; +const GRAPH: u64 = 0xffff_fc20_c008_0000; +const POINTERS: usize = 0x4000; +const ITEMS: usize = 0x8000; +/// Past the 0x500 command pointers the channel state declares, as for the +/// graphics queues, so the producer head wraps like theirs. +const CONFIG: usize = ITEMS + GRAPHICS_POINTER_COUNT as usize * 8; +const CONTROL: usize = 0xc000; +const _: () = assert!(CONFIG + 0x300 <= CONTROL); + +/// Installation publishes one command pointer; every dispatch generation then +/// appends the same three -- descriptor, channel config, kick -- so the +/// producer head runs 1, 4, 7, ... (mod 0x500) exactly as +/// graphics_pointer_head() does for queues 10/11. +pub(super) const fn compute_pointer_head(generation: u32) -> u32 { + graphics_pointer_head(generation) +} + +pub(super) const fn compute_generation_admitted(generation: u32) -> bool { + generation >= 1 && generation <= MAX_GRAPHICS_GENERATION +} + +const LIST: u64 = GRAPH + 0x10000; +const ENTRY: u64 = 0xffff_fc20_003d_0000; +const ENTRY_LOW: u64 = 0x70_0063_0000; +const DESC: u64 = 0xffff_fc20_c040_0000; +const DESC_LOW: u64 = 0x70_0038_0000; +const SCHEDULER: u64 = DESC + 0x4000; +const ZERO: u64 = DESC + 0x8000; +const SIGNALS: u64 = DESC + 0x10000; + +pub(super) struct M5ApplicationCompute { + aliases: KVec, + descriptor: MappedObject, + graph: MappedObject, + entry: MappedObject, + list: MappedObject, + signals: MappedObject, + /// GPU address of the job's compute storage. + storage: u64, + /// The operands mapped into the VM that took the graphics job over. + firmware: FirmwareDataView, +} + +impl M5ApplicationCompute { + pub(super) fn new(dev: &AsahiDrmDevice, uat: &mmu::Uat, job: &M5GraphicsJob, + command: &command::TranslatedComputeCommand) -> Result { + // The adapter excludes helpers, timestamps, legacy sampler registers + // and the Neo add3 proof ABI before allocating or publishing anything. + if command.sampler_heap != 0 || command.sampler_count != 0 + || command.g17p_add3_buffers.is_some() { return Err(ENOTSUPP); } + // Validate observation support and vacancy before publishing a queue. + let firmware = FirmwareDataView::new(dev)?; + if firmware.queue_registration(QUEUE_ID)? != ([0; 5], 0) { return Err(EBUSY); } + // 128 KiB operands, a preemption page and a zero robustness page. + // Their addresses come from the application's reserved driver arena. + let storage = job.compute_storage(); + let mut descriptor = MappedObject::new_wc_at(dev, uat.kernel_vm(), DESC, + 0x10000, mmu::PROT_FW_PRIV_RW)?; + let mut entry = MappedObject::new_wc_at(dev, uat.kernel_vm(), ENTRY, + 0x20000, mmu::PROT_FW_PRIV_RW)?; + let mut aliases = KVec::new(); + for (object, low, size) in [(&mut descriptor, DESC_LOW, 0x10000), + (&mut entry, ENTRY_LOW, 0x20000)] { + aliases.push(object.map_alias_at(uat.kernel_lower_vm(), low, + mmu::PROT_GPU_SHARED_RW)?, GFP_KERNEL)?; + for offset in (0..size).step_by(mmu::UAT_PGSZ) { + if uat.kernel_vm().translate_iova(object.iova() + offset as u64)? + != uat.kernel_lower_vm().translate_iova(low + offset as u64)? { + return Err(EFAULT); + } + } + } + let mut signals = MappedObject::new_wc_at(dev, uat.kernel_vm(), SIGNALS, + 0x4000, mmu::PROT_FW_SHARED_RW)?; + // The submitted count is the host's and stays put; firmware republishes + // the completed count into the scheduler record each generation. + signals.write_u32(SIGNALS, 1)?; + Self::encode_descriptor(&mut descriptor, job, command, storage, 1)?; + let mut graph = MappedObject::new_wc_at(dev, uat.kernel_vm(), GRAPH, + 0x10000, mmu::PROT_FW_PRIV_RW)?; + let mut list = MappedObject::new_wc_at(dev, uat.kernel_vm(), LIST, + 0x4000, mmu::PROT_FW_SHARED_RW)?; + list.with_bytes_mut(|out| { put64(out, 8, LIST); Ok(()) })?; + let prepared = Self::prepare_entry(1)?; + entry.with_bytes_mut(|out| { + let offset = prepared.offset as usize; + out[offset..offset + prepared.bytes.len()].copy_from_slice(&prepared.bytes); + Ok(()) + })?; + let configuration = |install| channel::encode_m5_channel_config( + channel::M5ChannelConfig { + ring_low: ENTRY_LOW, ring_high: ENTRY, queue_id: QUEUE_ID, priority: 2, + install_queue: install, gpu_context: job.context_id(), + event: if install { None } else { Some(channel::M5ChannelEvent { + address: job.usc_control(), timestamp: 1, index: graphics_usc::HARDWARE_ID, + }) }, + channel_control: GRAPH + CONTROL as u64, update_scheduler: install, + scheduler_index: 0, channel_stamp_index: 0, + update_context: !install, owner_context: if install { 0 } else { 1 }, + extended_command: false, + }).map_err(|_| EINVAL); + let install = configuration(true)?; + let config = configuration(false)?; + let kick = Self::prepare_kick(1)?; + graph.with_bytes_mut(|out| { + let reset = submission::encode_m5_25g76_channel_state_reset( + submission::M5ChannelStateResetValues { + uncached_state: GRAPH + POINTERS as u64, + command_pointer_ring: GRAPH + ITEMS as u64, gpu_va_10: LIST, + word_48: 0, gpu_va_9c: GRAPH + CONTROL as u64, + }); + let queue = usize::from(QUEUE_ID) * 0xc0; + out[queue..queue + 0xc0].copy_from_slice(&reset); + for offset in [0x28, 0x2c, 0x40] { put32(out, queue + offset, 2); } + out[queue + 0x36..queue + 0x38].fill(0xff); + put32(out, POINTERS + 0x50, u32::MAX); + put32(out, POINTERS + 0x60, 0x500); + out[CONTROL..CONTROL + 2].fill(0xff); + out[CONTROL + 5] = 1; + out[CONTROL + 0x26] = 2; + out[CONTROL + 0x33] = 0xff; + for (offset, bytes) in [(CONFIG, &install[..]), (CONFIG + 0x100, &config[..]), + (CONFIG + 0x200, &kick[..])] { + out[offset..offset + bytes.len()].copy_from_slice(bytes); + } + for (index, address) in [GRAPH + CONFIG as u64, DESC, + GRAPH + CONFIG as u64 + 0x100, GRAPH + CONFIG as u64 + 0x200] + .into_iter().enumerate() { put64(out, ITEMS + index * 8, address); } + put32(out, POINTERS + 0x40, 1); + Ok(()) + })?; + Ok(Self { aliases, descriptor, graph, entry, list, signals, storage, + firmware }) + } + + pub(super) fn queue_address() -> u64 { GRAPH + QUEUE_ID as u64 * 0xc0 } + + /// Re-encode the whole descriptor for one dispatch generation. The + /// scheduler record is cleared and re-seeded exactly as + /// M5GraphicsJob::rebuild_retired_frame() does for queues 10/11: firmware + /// republishes the completed count into it, so a stale one would satisfy + /// the next generation's completion gate before the dispatch even ran. + fn encode_descriptor(descriptor: &mut MappedObject, job: &M5GraphicsJob, + command: &command::TranslatedComputeCommand, storage: u64, + generation: u32) -> Result { + if !compute_generation_admitted(generation) { return Err(EINVAL); } + descriptor.with_bytes_mut(|out| { + out[0x4000..0x4000 + 0xc8].fill(0); + put64(out, 0x4000, SIGNALS); + put32(out, 0x4010, 0x50); + compute::encode_m5_compute_descriptor(compute::M5ComputeDescriptor { + registers: compute::M5ComputeParameters { + preempt_base: storage + 0x20000, + cdm_base: command.control_stream_base, + dispatch_identity: 0x0000_0001_0000_0001, + context_id: job.context_id(), work_ordinal: 0, + robustness: storage + 0x24000, + operand_state_base: storage, + private_pool_hw_id: u64::from(graphics_usc::HARDWARE_ID), + descriptor_control_530: 0x54b, descriptor_control_538: 0xf5, + descriptor_flag_60a: false, descriptor_flag_60b: false, + }, + submit_sequence: 0, scheduler_record: SCHEDULER, + descriptor_low_alias: DESC_LOW, + cdm_terminator: command.control_stream_terminator, + dispatch_stamps: [SIGNALS + 0x40, SIGNALS + 0x80], + event_machine_stamp: generation * 0x100, queue_id: u32::from(QUEUE_ID), + queue_ordinal: 0, has_event: false, submission_index: generation, + status: [SIGNALS + 0xc0, SIGNALS + 0xc8], + shared_control: job.usc_control(), shared_control_enabled: true, + event_metadata: [0; 16], zero_page: ZERO, owner_id: 1, + descriptor_work_ordinal: 0, + }, &mut out[..0x1000]).map_err(|_| EINVAL) + }) + } + + fn prepare_entry(generation: u32) -> Result { + if !compute_generation_admitted(generation) { return Err(EINVAL); } + let stamp = u64::from(generation); + sksm::prepare_m5_sksm_entry(sksm::M5SksmQueue { + id: QUEUE_ID, priority: 2, current_stamp: stamp, submitted: 0, + previous_stamp: if generation == 1 { None } else { Some(stamp - 1) }, + }, sksm::M5SksmOperands { + barriers: &[], first_predecessor: 0, implicit_dependency_type: 1, + mcache: None, flag_bit1: false, flag_bit61: false, flag_bit63: false, + payload: [DESC, Self::queue_address()], qos_byte_32: 3, qos_class_40: 8, + qos_word_48: 0xffff, event_mask: [0; 4], rce_kind: 0, + rce: [sksm::M5SksmRce { address: DESC_LOW + 0x40, tag: 37 }, + sksm::M5SksmRce { address: DESC_LOW + 0x760, tag: 4 }, + sksm::M5SksmRce { address: 0, tag: 0 }, + sksm::M5SksmRce { address: 0, tag: 0 }], + auxiliary: 0x3f_ffff_ffff_ffff, + }).map_err(|_| EINVAL) + } + + fn prepare_kick(generation: u32) -> Result<[u8; 21]> { + if !compute_generation_admitted(generation) { return Err(EINVAL); } + sksm::encode_m5_sksm_add_kicks(QUEUE_ID, 2, u64::from(generation), 1) + .map_err(|_| EINVAL) + } + + /// Stage a further dispatch on the installed queue. Nothing here is + /// published: the producer head moves only in publish_dispatch(). + pub(super) fn prepare_next_dispatch(&mut self, job: &M5GraphicsJob, + command: &command::TranslatedComputeCommand, generation: u32) -> Result { + if generation < 2 || !compute_generation_admitted(generation) { return Err(EINVAL); } + if self.counters()? != [compute_pointer_head(generation - 1); 3] + || !self.installed()? { return Err(EBUSY); } + Self::encode_descriptor(&mut self.descriptor, job, command, + self.storage, generation)?; + let prepared = Self::prepare_entry(generation)?; + self.entry.with_bytes_mut(|out| { + let offset = prepared.offset as usize; + let slot = &mut out[offset..offset + prepared.bytes.len()]; + // Every preceding dispatch has retired, including the prior user + // of this 256-entry SKSM slot. Preserve the first-use check. + if generation < 256 && slot.iter().any(|byte| *byte != 0) { + return Err(EBUSY); + } + slot.copy_from_slice(&prepared.bytes); + Ok(()) + })?; + let kick = Self::prepare_kick(generation)?; + self.graph.with_bytes_mut(|out| { + out[CONFIG + 0x200..CONFIG + 0x200 + kick.len()].copy_from_slice(&kick); + for (index, address) in [DESC, GRAPH + CONFIG as u64 + 0x100, + GRAPH + CONFIG as u64 + 0x200].into_iter().enumerate() { + let absolute = 1 + (generation as usize - 1) * 3 + index; + let offset = ITEMS + (absolute % GRAPHICS_POINTER_COUNT as usize) * 8; + if absolute < GRAPHICS_POINTER_COUNT as usize + && out[offset..offset + 8].iter().any(|byte| *byte != 0) { + return Err(EBUSY); + } + put64(out, offset, address); + } + Ok(()) + }) + } + + pub(super) fn counters(&mut self) -> Result<[u32; 3]> { + let mut out = [0; 3]; + for (index, offset) in [0, 0x30, 0x40].into_iter().enumerate() { + out[index] = self.graph.read_u32(GRAPH + (POINTERS + offset) as u64)?; + } + Ok(out) + } + + pub(super) fn installed(&mut self) -> Result { + let (slot, scheduler) = self.firmware.queue_registration(QUEUE_ID)?; + let header = self.graph.read_u32(GRAPH + CONTROL as u64)?; + let bitmap = self.graph.read_u64(GRAPH + CONTROL as u64 + 0x12)?; + Ok(slot[0] & 1 != 0 && slot[1] == ENTRY && slot[2] == ENTRY_LOW + && slot[3] == 4u64 << 32 && slot[4] as u32 == 2 + && scheduler == GRAPH + CONTROL as u64 + && header & 0xff != 0xff && (header >> 8) & 0xff != 0xff + && (header >> 16) & 0xff == 4 && bitmap == 1u64 << QUEUE_ID) + } + + pub(super) fn publish_dispatch(&mut self, generation: u32) -> Result { + if !compute_generation_admitted(generation) { return Err(EINVAL); } + if self.counters()? != [compute_pointer_head(generation - 1); 3] + || !self.installed()? { return Err(EBUSY); } + self.graph.write_u32(GRAPH + POINTERS as u64 + 0x40, + compute_pointer_head(generation)) + } + + pub(super) fn completion(&mut self, signalled: u128) + -> Result { + Ok(crate::m5::completion::M5ComputeCompletion { + submitted: self.signals.read_u32(SIGNALS)?, + completed: self.descriptor.read_u32(SCHEDULER + 0xc)?, + linked: self.descriptor.read_u32(SCHEDULER + 0x94)?, + list: [self.list.read_u64(LIST)?, self.list.read_u64(LIST + 8)?], + stamp: self.signals.read_u32(SIGNALS + 0x40)?, signalled, + }) + } + + pub(super) fn complete(&mut self, signalled: u128, generation: u32) -> Result { + if !compute_generation_admitted(generation) { return Err(EINVAL); } + Ok(self.counters()? == [compute_pointer_head(generation); 3] + && self.completion(signalled)? + .complete_at(LIST, QUEUE_ID, generation * 0x100)) + } +} + +fn put32(out: &mut [u8], offset: usize, value: u32) { + out[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} +fn put64(out: &mut [u8], offset: usize, value: u64) { + out[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} diff --git a/drivers/gpu/drm/asahi/m5/resources/firmware_view.rs b/drivers/gpu/drm/asahi/m5/resources/firmware_view.rs new file mode 100644 index 0000000000000..54ed6c966ac76 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/firmware_view.rs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Read-only view of the GFX firmware's DATA segment (the `gfx-data` reserved region). + +use crate::driver::AsahiDrmDevice; +use core::sync::atomic::{fence, Ordering}; +use kernel::{c_str, io, prelude::*}; + +pub(super) struct FirmwareDataView { + map: io::mem::Mem, + cache_line: usize, +} + +// SAFETY: This owns a fixed mapping of reserved RAM, read only through +// bounded volatile accesses. It neither transfers ownership nor writes DATA. +unsafe impl Send for FirmwareDataView {} +// SAFETY: Concurrent read-only volatile observations do not mutate host state. +unsafe impl Sync for FirmwareDataView {} + +impl FirmwareDataView { + pub(super) fn new(dev: &AsahiDrmDevice) -> Result { + let resource = dev.as_ref().as_ref().of_node().ok_or(EINVAL)? + .reserved_mem_region_to_resource_byname(c_str!("gfx-data"))?; + if resource.size() != 0x134000 || resource.start() < 0x100_0000_0000 + || resource.start() & 0x3fff != 0 + || resource.start().checked_add(resource.size()).ok_or(EOVERFLOW)? > 0x104_0000_0000 + || 0x127430 - 0x4c000 + 13 * 0x28 > resource.size() as usize + || 0x1257e0 - 0x4c000 + 13 * 8 > resource.size() as usize + || 0x178458 - 0x4c000 + 8 > resource.size() as usize { + return Err(EINVAL); + } + let ctr: u64; + // SAFETY: CTR_EL0 is an architectural read-only cache geometry register. + unsafe { core::arch::asm!("mrs {ctr}, ctr_el0", ctr = out(reg) ctr, + options(nomem, nostack, preserves_flags)) }; + let cache_line = 4usize << ((ctr >> 16) & 0xf); + if cache_line > 0x4000 { return Err(EINVAL); } + // SAFETY: WB matches reserved System RAM. The host never writes this + // extent; observations invalidate covering lines before volatile reads. + let map = unsafe { io::mem::Mem::try_new(resource, io::mem::MemFlag::WB.into()) }?; + fence(Ordering::SeqCst); + Ok(Self { map, cache_line }) + } + + fn words(&self, offset: usize) -> [u64; N] { + // All callers use constructor-checked queue, scheduler or power extents. + let line = self.cache_line; + let start = offset & !(line - 1); + let end = (offset + N * 8 + line - 1) & !(line - 1); + for offset in (start..end).step_by(line) { + // SAFETY: Whole covering lines are inside the retained DATA view. + // The host never dirties them; do not clean stale data to firmware. + unsafe { core::arch::asm!("dc ivac, {addr}", + addr = in(reg) self.map.ptr().add(offset), + options(nostack, preserves_flags)) }; + } + // SAFETY: Complete invalidations before volatile observations. + unsafe { core::arch::asm!("dsb sy", options(nostack, preserves_flags)) }; + let mut out = [0; N]; + for (index, value) in out.iter_mut().enumerate() { + // SAFETY: The constructor bounds-checks every supported extent. + *value = unsafe { core::ptr::read_volatile( + self.map.ptr().add(offset + index * 8).cast::()) }; + } + fence(Ordering::Acquire); + out + } + + pub(super) fn queue_registration(&self, queue_id: u8) -> Result<([u64; 5], u64)> { + // TA/fragment own 10/11; application compute owns 12. The constructor + // bounds both complete tables through the last admitted queue. + if !(10..=12).contains(&queue_id) { return Err(EINVAL); } + Ok((self.words::<5>(0x127430 - 0x4c000 + queue_id as usize * 0x28), + self.words::<1>(0x1257e0 - 0x4c000 + queue_id as usize * 8)[0])) + } +} diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs new file mode 100644 index 0000000000000..0245811e9b5db --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs @@ -0,0 +1,512 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Owned TA/fragment resource graph for the bounded native-program test. +//! Construction leaves roots and queues unpublished. Submission wiring must +//! retain this owner through completion, faults and firmware shutdown. + +use super::{graphics_memory::M5GraphicsMemory, graphics_usc, MappedObject}; +use super::parameter_buffer::{M5ParameterBuffer, BLOCK_BYTES, PAGE_LIST_BYTES, PAGE_COUNT}; +use super::target_memory::M5TargetMemory; +use crate::{driver::AsahiDrmDevice, m5::render_desc, m5::render, mmu}; +use crate::m5::completion::MAX_GRAPHICS_GENERATION; +use kernel::prelude::*; + +const HIGH: u64 = 0xffff_fc20_c100_0000; +const LOW: u64 = 0x70_0030_0000; +const BYTES: usize = 0x40000; +const TA: usize = 0; +const FRAGMENT: usize = 0x4000; +const SCHEDULER: usize = 0x8000; +const SIGNALS_HIGH: u64 = HIGH + 0x80000; +const SUBMITTED: usize = 0; +const PM: usize = 0xc000; +const PM_SHARED: usize = 0x10000; +const PM_COUNTER: usize = 0x14000; +const PM_BLOCKS: usize = 0x18000; +const USC: usize = 0x1c000; +const USC_INNER: usize = 0x20000; +const USC_STATISTICS: usize = 0x24000; +const SCENES: usize = 0x30000; +const SCENE_ZERO: usize = SCENES + 80 * 0x80; +const TIMESTAMPS: usize = 0x38000; +const STAMPS_A: usize = 0x4000; +const STAMPS_B: usize = 0x8000; +const PAGE_LIST_HIGH: u64 = HIGH + 0x40000; +const METRICS_HIGH: u64 = HIGH + 0x60000; +const USER_BASE: u64 = 0x10_0000_0000; +pub(super) const PB_HARDWARE_ID: u32 = 0; +pub(super) const QUEUE_IDS: [u8; 2] = [10, 11]; +// Match Mesa's framebuffer dimensions; target allocations follow each size. +// Parameter-pool growth for more complex scenes remains separate. +use crate::m5::command::M5_MAX_RENDER_DIMENSION as MAX_APPLICATION_DIMENSION; +/// Retired targets kept for reuse. A video player cycles through a handful of +/// pass sizes every frame and a compositor's frames alternate with it, so +/// allocating per size change put several milliseconds on most jobs. +const TARGET_CACHE_ENTRIES: usize = 8; +/// Compute operands (128 KiB), a preemption page and a zero robustness page. +const COMPUTE_STORAGE_BYTES: usize = 0x28000; + +pub(super) struct M5GraphicsJob { + // The first owner's context retracts its roots before page release. + program: M5GraphicsMemory, + parameter_buffer: M5ParameterBuffer, + /// Storage of application compute, reserved with the parameter buffer so that its + /// address is free in every VM the job is handed to. + compute_storage: MappedObject, + target_memory: M5TargetMemory, + aliases: KVec, + // PB/USC pool views in a VM this job was handed to; empty for the first + // owner, whose pools were allocated in its own VM. + vm_aliases: KVec, + graph_alias: mmu::KernelMapping, + graph: MappedObject, + signals: MappedObject, + descriptor_template: KVec, + scene_template: KVec, + generation: u32, + target_shape: [u32; 5], + /// The VM `target_memory` lives in; a handoff leaves it behind. + target_vm: u64, + /// Retired targets by (VM, shape), least recently used first. + target_cache: KVec<(u64, [u32; 5], M5TargetMemory)>, +} + +impl M5GraphicsJob { + + /// Build a job from the submitting VM and translated application state. + /// No captured program is loaded; the caller supplies stage controls and + /// USC requirements derived for its program. Submission remains explicit. + #[allow(clippy::too_many_arguments)] + pub(super) fn from_vm( + dev: &AsahiDrmDevice, uat: &mmu::Uat, vm: &mmu::Vm, + parameters: render_desc::G17pRenderParameters, controls: render::M5RenderControls, + clusters: u32, usc_required: [u64; 2], + ) -> Result { + let program = M5GraphicsMemory::from_vm(dev, uat, vm)?; + Self::from_memory(dev, uat, program, parameters, controls, clusters, usc_required) + } + + #[allow(clippy::too_many_arguments)] + fn from_memory( + dev: &AsahiDrmDevice, uat: &mmu::Uat, program: M5GraphicsMemory, + mut p: render_desc::G17pRenderParameters, controls: render::M5RenderControls, + clusters: u32, usc_required: [u64; 2], + ) -> Result { + if !(1..=MAX_APPLICATION_DIMENSION).contains(&p.width) + || !(1..=MAX_APPLICATION_DIMENSION).contains(&p.height) + || p.layers != 1 || clusters != 1 { + return Err(ENOTSUPP); + } + let mut parameter_buffer = M5ParameterBuffer::new_reference(dev, &program)?; + let compute_storage = program.allocate_compact( + dev, COMPUTE_STORAGE_BYTES, 0x8000, mmu::PROT_GPU_SHARED_RW)?; + let target_memory = M5TargetMemory::new(dev, &program, &p, clusters)?; + target_memory.apply(&mut p); + p.cycle = parameter_buffer.scene_cycle(); + // Keep the PM register and firmware scene descriptor on the same + // owned metrics slot. The captured address is unmapped in a new VM. + p.record_index = render::parameter_buffer_metrics_record( + parameter_buffer.metrics() + 0x40).map_err(|_| EINVAL)?; + p.ta_hardware_buffer_id = PB_HARDWARE_ID; + p.usc_flist_hardware_buffer_id = graphics_usc::HARDWARE_ID; + p.ta_timestamp_start = HIGH + TIMESTAMPS as u64; + p.ta_timestamp_end = p.ta_timestamp_start + 8; + p.fragment_timestamp_start = p.ta_timestamp_start; + p.fragment_timestamp_end = p.ta_timestamp_end; + let mut graph = MappedObject::new_wc_at(dev, uat.kernel_vm(), HIGH, + BYTES, mmu::PROT_FW_PRIV_RW)?; + // Native submitted totals and host-visible stamps are uncached in + // firmware. Keep them separate from the cached descriptor graph. + let mut signals = MappedObject::new_wc_at(dev, uat.kernel_vm(), SIGNALS_HIGH, + 0xc000, mmu::PROT_FW_SHARED_RW)?; + signals.write_u32(SIGNALS_HIGH + SUBMITTED as u64, 2)?; + let graph_alias = graph.map_alias_at(uat.kernel_lower_vm(), LOW, + mmu::PROT_GPU_SHARED_RW)?; + for offset in (0..BYTES).step_by(mmu::UAT_PGSZ) { + if uat.kernel_vm().translate_iova(HIGH + offset as u64)? + != uat.kernel_lower_vm().translate_iova(LOW + offset as u64)? { + return Err(EFAULT); + } + } + let aliases = parameter_buffer.firmware_aliases( + uat, program.vm(), PAGE_LIST_HIGH, METRICS_HIGH, + )?; + let block_page_bases = parameter_buffer.block_page_bases()?; + graph.with_bytes_mut(|out| { + put64(out, SCHEDULER, SIGNALS_HIGH + SUBMITTED as u64); + put32(out, SCHEDULER + 0x10, 0x50); + // Two submitted stage records; firmware compares its completed + // count with this total, then unlinks the scheduler. + for (block, base) in block_page_bases.into_iter().enumerate() { + put32(out, PM_BLOCKS + block * 8, base); + } + put32(out, PM_SHARED, 3); + put32(out, PM_SHARED + 4, 3); + put32(out, PM_SHARED + 0x60, 1); + put32(out, PM_COUNTER, 1); + for (offset, value) in [(0xc, PB_HARDWARE_ID), (0x30, PAGE_LIST_BYTES as u32), + (0x34, PAGE_COUNT), (0x38, 1650), (0x3c, 3), (0x54, PAGE_COUNT - 1), + (0x58, BLOCK_BYTES as u32), (0x7c, 1650 * 16), (0x80, 550 * 16)] { + put32(out, PM + offset, value); + } + for (offset, address) in [(0x20, PAGE_LIST_HIGH), (0x28, parameter_buffer.page_list()), + (0x44, HIGH + PM_BLOCKS as u64), (0x4c, HIGH + PM_SHARED as u64), + (0x64, HIGH + PM_COUNTER as u64), (0x84, parameter_buffer.discard_offset())] { + put64(out, PM + offset, address); + } + // This sole job owns scene 1. M5 metrics use 64-byte spacing, + // unlike Neo dwords. Other reserved scenes remain unassigned; + // do not guess a scratch-ring wrap rule from a single draw. + let selected_scene = SCENES + 0x80; + put64(out, selected_scene, parameter_buffer.metrics() + 0x40); + put64(out, selected_scene + 8, METRICS_HIGH + 0x40); + put64(out, selected_scene + 0x28, parameter_buffer.scene_cycle()); + put64(out, selected_scene + 0x40, HIGH + PM_SHARED as u64 + 0x40); + put64(out, SCENES + 0x80 + 0x4c, 1); + put32(out, USC_INNER, 1); + program.usc().encode_initial_owner(HIGH + USC_INNER as u64, + &mut out[USC..USC + 0x70])?; + + Self::encode_descriptors(out, &p, &controls, program.context_id(), usc_required)?; + Ok(()) + })?; + let mut descriptor_template = KVec::new(); + let mut scene_template = KVec::new(); + graph.with_bytes_mut(|out| { + descriptor_template.extend_from_slice(&out[..SCHEDULER], GFP_KERNEL)?; + scene_template.extend_from_slice(&out[SCENES + 0x80..SCENES + 0x100], GFP_KERNEL)?; + Ok(()) + })?; + let target_vm = program.vm().id(); + Ok(Self { program, parameter_buffer, compute_storage, target_memory, aliases, + vm_aliases: KVec::new(), + graph_alias, graph, signals, descriptor_template, scene_template, generation: 1, + target_shape: [p.width, p.height, u32::from(p.layers), + u32::from(p.utile_width), u32::from(p.utile_height)], + target_vm, target_cache: KVec::new() }) + } + + #[allow(clippy::too_many_arguments)] + fn encode_descriptors( + out: &mut [u8], p: &render_desc::G17pRenderParameters, + controls: &render::M5RenderControls, context_id: u8, + usc_required: [u64; 2], + ) -> Result { + let objects = render_desc::RenderDescriptorObjects { + record_a: HIGH + SCHEDULER as u64, + shared: HIGH + PM as u64, + record_b: HIGH + SCENES as u64 + 0x80, + zero: HIGH + SCENE_ZERO as u64, + }; + let metadata = render_desc::RenderDescriptorMetadata { + context_id: context_id as u32, submission_ordinal: 0, command_buffer_state_word: 0, + ta_hardware_buffer_id: PB_HARDWARE_ID, submit_sequence: 1, + }; + render::build_ta_descriptor_base(p, controls, objects, metadata, + LOW + TA as u64, &mut out[TA..TA + render_desc::TA_DESCRIPTOR_SIZE]) + .map_err(|_| EINVAL)?; + render::build_fragment_descriptor_base(p, controls, objects, + render_desc::RenderDescriptorMetadata { submit_sequence: 0, ..metadata }, + LOW + FRAGMENT as u64, + &mut out[FRAGMENT..FRAGMENT + render_desc::FRAGMENT_DESCRIPTOR_SIZE]) + .map_err(|_| EINVAL)?; + let (ta, fragment) = out.split_at_mut(FRAGMENT); + let ta_usc = render::M5RenderUscState { + control: HIGH + USC as u64, required_bytes: usc_required[0], + allocated_bytes: graphics_usc::CAPACITY_BYTES, + statistics: HIGH + USC_STATISTICS as u64, + }; + render::apply_usc_submission_state(ta, fragment, ta_usc, + render::M5RenderUscState { + required_bytes: usc_required[1], statistics: ta_usc.statistics + 0x40, ..ta_usc + }).map_err(|_| EINVAL)?; + // This bounded first submission owns hardware stamp1 in each + // queue and event-machine timestamp0x100. Do not import native + // allocator history (the captured queues had stamps2/3). + put32(ta, 0x79c, QUEUE_IDS[1] as u32); + put64(ta, 0x7a0, 0x100); + put64(ta, 0x7a8, 1); + ta[0x7b0] = 1; + ta[0x7b1] = 1; + put64(ta, 0x8a6, SIGNALS_HIGH + STAMPS_A as u64 + QUEUE_IDS[0] as u64 * 4); + put64(ta, 0x8ae, SIGNALS_HIGH + STAMPS_B as u64 + QUEUE_IDS[0] as u64 * 4); + put32(ta, 0x8b6, 0x100); + put32(ta, 0x8ba, QUEUE_IDS[0] as u32); + put64(ta, 0x8c6, (1u64 << 40) | 1); + put64(fragment, 0x2140, SIGNALS_HIGH + STAMPS_A as u64 + QUEUE_IDS[1] as u64 * 4); + put64(fragment, 0x2148, SIGNALS_HIGH + STAMPS_B as u64 + QUEUE_IDS[1] as u64 * 4); + put32(fragment, 0x2150, 0x100); + put32(fragment, 0x2154, QUEUE_IDS[1] as u32); + put32(fragment, 0x215c, 0); + put64(fragment, 0x2160, (1u64 << 40) | 1); + // Fixed 256x256 reference controls independently observed in + // the successful 25G76 draw; these replace inherited Neo values. + ta[0x789] = 8; + ta[0x85f] = 7; + put32(ta, 0x892, 0); + ta[0x932] = 0; + put32(fragment, 0x1fb0, 8); + fragment[0x21cc] = 0; + fragment[0x222d] = 0; + Ok(()) + } + + pub(super) fn parameter_descriptor(&self) -> Result<[u32; 4]> { + render::initial_parameter_buffer_descriptor(self.parameter_buffer.page_list(), PAGE_COUNT) + .map_err(|_| EINVAL) + } + + pub(super) fn uma_descriptor(&self) -> [u64; 4] { self.program.usc().descriptor() } + + pub(super) fn roots(&self) -> [u64; 2] { self.program.roots() } + + pub(super) fn context_id(&self) -> u8 { self.program.context_id() } + + pub(super) fn owns_vm(&self, vm: &mmu::Vm) -> bool { + self.program.vm().id() == vm.id() + } + + /// Hand this fully retired job to another submitting VM. The hardware + /// context slot, descriptor graph, signals, queues and the PB/USC pools + /// all keep their firmware-visible addresses: the context is re-leased + /// for the new VM and the pools are aliased into it. The previous VM's + /// render targets are not used in the new VM: they stay cached under the + /// previous VM for its next turn, and the next application frame takes or + /// allocates targets in the new VM. The caller publishes the new roots + /// before the next draw. + pub(super) fn rebind_vm(&mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm) -> Result { + if self.owns_vm(vm) { return Ok(()); } + if self.scheduler_status()? != [2, 0] { return Err(EBUSY); } + let progress = self.progress()?; + if progress[0] != 2 || progress[1] != self.generation * 0x100 + || progress[3] != self.generation * 0x100 { return Err(EBUSY); } + // Release an earlier handoff's views before reserving the same + // addresses in the incoming VM. + self.vm_aliases = KVec::new(); + let mut aliases = self.program.rebind(dev, vm)?; + for alias in self.parameter_buffer.alias_into(vm)? { + aliases.push(alias, GFP_KERNEL)?; + } + let storage = self.compute_storage.iova(); + if let Some(alias) = self.compute_storage.map_alias_at_with_guards( + vm, storage, mmu::PROT_GPU_SHARED_RW, 2)? { + aliases.push(alias, GFP_KERNEL)?; + } + self.vm_aliases = aliases; + dev_dbg!(dev.as_ref(), "M5_RENDER_VM_HANDOFF context={} generation={} vm={}\n", + self.program.context_id(), self.generation, vm.id()); + Ok(()) + } + + /// Compute shares this application's published roots and USC owner. Only + /// its operand/preemption storage is its own: the GPU address of that storage. + pub(super) fn compute_storage(&self) -> u64 { + self.compute_storage.iova() + } + + pub(super) fn descriptor_addresses(&self, stage: usize) -> Result<[u64; 2]> { + let offset = match stage { 0 => TA, 1 => FRAGMENT, _ => return Err(EINVAL) }; + Ok([HIGH + offset as u64, LOW + offset as u64]) + } + + pub(super) fn usc_control(&self) -> u64 { HIGH + USC as u64 } + + pub(super) fn parameter_state(&self) -> u64 { HIGH + PM as u64 } + + pub(super) fn publish_context(&mut self) -> Result { self.program.publish() } + + pub(super) fn quarantine(&self) { self.program.quarantine(); } + + pub(super) fn progress(&mut self) -> Result<[u32; 5]> { + Ok([self.signals.read_u32(SIGNALS_HIGH + SUBMITTED as u64)?, + self.signals.read_u32(SIGNALS_HIGH + STAMPS_A as u64 + QUEUE_IDS[0] as u64 * 4)?, + self.signals.read_u32(SIGNALS_HIGH + STAMPS_B as u64 + QUEUE_IDS[0] as u64 * 4)?, + self.signals.read_u32(SIGNALS_HIGH + STAMPS_A as u64 + QUEUE_IDS[1] as u64 * 4)?, + self.signals.read_u32(SIGNALS_HIGH + STAMPS_B as u64 + QUEUE_IDS[1] as u64 * 4)?]) + } + + pub(super) fn scheduler_status(&mut self) -> Result<[u32; 2]> { + // GFX cleans this 0xc8-byte object after unlinking the finished pair. + Ok([self.graph.read_u32(HIGH + SCHEDULER as u64 + 0xc)?, + self.graph.read_u32(HIGH + SCHEDULER as u64 + 0x94)?]) + } + + fn rebuild_retired_frame(&mut self, generation: u32) -> Result { + if generation != self.generation + 1 || generation > MAX_GRAPHICS_GENERATION + || self.scheduler_status()? != [2, 0] { + return Err(EBUSY); + } + let progress = self.progress()?; + if progress[0] != 2 || progress[1] != self.generation * 0x100 + || progress[3] != self.generation * 0x100 { return Err(EBUSY); } + self.graph.with_bytes_mut(|out| { + out[..SCHEDULER].copy_from_slice(&self.descriptor_template); + out[SCHEDULER..SCHEDULER + 0xc8].fill(0); + put64(out, SCHEDULER, SIGNALS_HIGH + SUBMITTED as u64); + put32(out, SCHEDULER + 0x10, 0x50); + out[SCENES + 0x80..SCENES + 0x100].copy_from_slice(&self.scene_template); + out[TIMESTAMPS..TIMESTAMPS + 16].fill(0); + let stamp = generation * 0x100; + put64(out, TA + 0x7a0, stamp as u64); + put64(out, TA + 0x7a8, generation as u64); + put32(out, TA + 0x8b6, stamp); + put64(out, TA + 0x8c6, (1u64 << 40) | generation as u64); + put32(out, FRAGMENT + 0x2150, stamp); + put64(out, FRAGMENT + 0x2160, (1u64 << 40) | generation as u64); + Ok(()) + })?; + // Leave previous stamps intact: they must be superseded by firmware, + // never host-written to the expected new completion value. + self.generation = generation; + Ok(()) + } + + /// Re-encode a retired application's descriptors without replaying its old + /// command pointers. The current bounded queue retains one VM. Target + /// storage can change only after complete retirement; the job + /// stamp keeps increasing and context replacement remains unsupported. + #[allow(clippy::too_many_arguments)] + pub(super) fn prepare_application_frame( + &mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm, mut p: render_desc::G17pRenderParameters, + controls: render::M5RenderControls, clusters: u32, + usc_required: [u64; 2], generation: u32, + ) -> Result { + if vm.id() != self.program.vm().id() || clusters != 1 + || !(1..=MAX_APPLICATION_DIMENSION).contains(&p.width) + || !(1..=MAX_APPLICATION_DIMENSION).contains(&p.height) || p.layers != 1 + || generation != self.generation + 1 || generation > MAX_GRAPHICS_GENERATION { + return Err(ENOTSUPP); + } + // Validate retirement before allocating or releasing any target pages. + // The caller additionally checks both queues, stamps and event bits. + let progress = self.progress()?; + if self.scheduler_status()? != [2, 0] || progress[0] != 2 + || progress[1] != self.generation * 0x100 + || progress[3] != self.generation * 0x100 { return Err(EBUSY); } + let shape = [p.width, p.height, u32::from(p.layers), + u32::from(p.utile_width), u32::from(p.utile_height)]; + let vm_id = self.program.vm().id(); + let replacement = if (vm_id, shape) != (self.target_vm, self.target_shape) { + let cached = self.target_cache.iter() + .position(|(cached_vm, cached_shape, _)| (*cached_vm, *cached_shape) == (vm_id, shape)); + Some(match cached { + Some(index) => self.target_cache.remove(index).map_err(|_| EINVAL)?.2, + None => M5TargetMemory::new(dev, &self.program, &p, clusters).inspect_err(|e| pr_err!("M5: target memory failed: {:?}\n", e))?, + }) + } else { None }; + replacement.as_ref().unwrap_or(&self.target_memory).apply(&mut p); + p.cycle = self.parameter_buffer.scene_cycle(); + p.record_index = render::parameter_buffer_metrics_record( + self.parameter_buffer.metrics() + 0x40).map_err(|_| EINVAL)?; + p.ta_hardware_buffer_id = PB_HARDWARE_ID; + p.usc_flist_hardware_buffer_id = graphics_usc::HARDWARE_ID; + p.ta_timestamp_start = HIGH + TIMESTAMPS as u64; + p.ta_timestamp_end = p.ta_timestamp_start + 8; + p.fragment_timestamp_start = p.ta_timestamp_start; + p.fragment_timestamp_end = p.ta_timestamp_end; + let mut descriptors = KVec::new(); + descriptors.extend_from_slice(&self.descriptor_template, GFP_KERNEL)?; + Self::encode_descriptors(&mut descriptors, &p, &controls, + self.program.context_id(), usc_required).inspect_err(|e| pr_err!("M5: encode_descriptors failed: {:?}\n", e))?; + self.descriptor_template = descriptors; + // The application owns its output. It must never be erased by the + // native diagnostic's sentinel/reset logic. + self.rebuild_retired_frame(generation).inspect_err(|e| pr_err!("M5: rebuild_retired_frame failed: {:?}\n", e))?; + if let Some(target) = replacement { + dev_dbg!(dev.as_ref(), "M5_RENDER_TARGET_RESIZE generation={} old={:?} new={:?}\n", + generation, self.target_shape, shape); + let retired = core::mem::replace(&mut self.target_memory, target); + if self.target_cache.len() == TARGET_CACHE_ENTRIES { + self.target_cache.remove(0).map_err(|_| EINVAL)?; + } + self.target_cache.push((self.target_vm, self.target_shape, retired), GFP_KERNEL)?; + self.target_vm = vm_id; + self.target_shape = shape; + } + Ok(()) + } + +} + +fn put32(out: &mut [u8], offset: usize, value: u32) { + out[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} +fn put64(out: &mut [u8], offset: usize, value: u64) { + out[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +pub(super) fn triangle_parameters() -> (render_desc::G17pRenderParameters, render::M5RenderControls) { + let mut p = render_desc::G17pRenderParameters::source_rsrc8(); + p.aux_fb = 0x10000288000; + p.aux_fb_flags = 0x10c001; + p.aux_fb_page_count = 0x100000; + p.context_base = USER_BASE; + p.cycle = 0x220040; + p.deflake_1 = 0x1000068340; + p.deflake_2 = 0x1000068040; + p.deflake_3 = 0x1000068000; + p.depth_aux_buffer = 0; + p.depth_aux_stride = 0; + p.depth_buffer = 0; + p.depth_clear_value_bits = 0x3f800000; + p.depth_dimensions = 0; + p.depth_flags = 0; + p.depth_stride = 0; + p.encoder = 0x1000018000; + p.fragment_lifecycle = 0x4089f4c0508e74c; + p.fragment_status = 0x1000258000; + p.heapmeta = 0x1000261000; + p.width = 256; + p.height = 256; + p.layers = 1; + p.lifecycle = 0x4089f4c0508e74d; + p.load_pipeline = 0x10000170200; + p.load_pipeline_bind = 0xffff800000000040; + p.merge_upper_x_bits = 0x3bddb3d9; + p.merge_upper_y_bits = 0x3bddb3d9; + p.multisample_control = 0x88; + p.occlusion_query_base = 0; + p.ppp_control = 0x202; + p.record_index = 0x80041; + p.stencil_aux_buffer = 0; + p.stencil_aux_stride = 0; + p.stencil_buffer = 0; + p.stencil_clear_value = 0; + p.stencil_stride = 0; + p.store_pipeline = 0x10000170400; + p.store_pipeline_bind = 0; + p.ta_hardware_buffer_id = PB_HARDWARE_ID; + p.ta_status = 0x1000078000; + p.tib_blocks = 0; + p.tile_config = 0x10280; + p.tilemap = 0x1000260000; + p.tpc = 0x1000288000; + p.usc_flist_hardware_buffer_id = graphics_usc::HARDWARE_ID; + p.utile_config = 0xa000; + p.utile_height = 32; + p.utile_width = 32; + p.absolute_pointers = false; + p.partial_store_pipeline_bind = 0; + p.partial_store_pipeline = 0x10000170400; + p.partial_load_pipeline_bind = 0xffff800000000040; + p.partial_load_pipeline = 0x10000170000; + p.depth_bias_array = 0x100002d8000; + p.scissor_array = 0x10000180000; + p.ta_timestamp_start = HIGH + TIMESTAMPS as u64; + p.ta_timestamp_end = p.ta_timestamp_start + 8; + p.fragment_timestamp_start = p.ta_timestamp_start; + p.fragment_timestamp_end = p.ta_timestamp_end; + let controls = render::M5RenderControls { + ta: render::M5RenderStageControls { + resource_flags: 0x4054b, resource_control: 0x200000001, ptc_max: 0xc6, work_key: 0x300, + }, + fragment: render::M5RenderStageControls { + resource_flags: 0x104054b, resource_control: 0x200000001, ptc_max: 0xce, work_key: 0x300, + }, + ta_tile_control: 0x10c08860, ta_dispatch_control: 0x700, + fragment_raster_control: 0x200000ff0200, fragment_tile_flags: 0x200003717f, + store_pipeline_2_bind: 0, store_pipeline_2: 0x10000170400, + partial_store_pipeline_2_bind: 0, partial_store_pipeline_2: 0x10000170400, + partial_tile_flags: 0x200000, + }; + (p, controls) +} diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_memory.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_memory.rs new file mode 100644 index 0000000000000..cf9a2f93efb03 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_memory.rs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Retained M5 render VM and private storage, with an optional native test program. +//! +//! Allocation is separate from root publication and queue submission. A future +//! job owner keeps this graph alive through queue completion. After a fault, +//! ownership remains retained until both firmware CPUs stop. Captured physical +//! backing is never installed. + +use super::MappedObject; +use super::graphics_usc::M5GraphicsUsc; +use crate::{driver::AsahiDrmDevice, mmu}; + +/// Pages of a client VM aliased into the context, at most this many. +const PAGE_BYTES: usize = 0x4000; +const MAX_PAGES: usize = 384; +use kernel::prelude::*; + +pub(super) struct M5GraphicsMemory { + // Retract any published roots before dropping their mapping owners. + context: mmu::M5ExecutionContext, + // Keep user mappings and GEM backing across handle close/VM teardown. + // This guard's bookkeeping is generation-neutral despite its old name. + user_mappings: Option, + pages: KVec, + usc: M5GraphicsUsc, + output_first: Option, +} + +impl M5GraphicsMemory { + + /// Keep the actual submitting VM and allocate only driver-owned storage. + /// Application shader/input/output mappings remain in that VM; no native + /// program firmware or captured pages are requested by this constructor. + pub(super) fn from_vm(dev: &AsahiDrmDevice, uat: &mmu::Uat, vm: &mmu::Vm) -> Result { + crate::m5::vm_layout::compact_range(&vm.kernel_range()).ok_or(EINVAL)?; + let user_mappings = vm.retain_job()?; + let context = uat.new_m5_execution_context(vm)?; + let usc = M5GraphicsUsc::new_application(dev, context.vm())?; + Ok(Self { context, user_mappings: Some(user_mappings), pages: KVec::new(), usc, output_first: None }) + } + + /// Hand the retained USC pool and this context slot to another + /// application VM. The previous roots are retracted first (with ASID + /// invalidation), the same hardware context is re-leased for `vm`, and + /// the pool is aliased at unchanged addresses, so every firmware record + /// that names the context or the pool keeps its value. The caller has + /// verified that the previous owner's work is completely retired and + /// publishes the new roots explicitly afterwards. + pub(super) fn rebind(&mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm) + -> Result> { + crate::m5::vm_layout::compact_range(&vm.kernel_range()).ok_or(EINVAL)?; + // Only application owners hand over; the native diagnostic program + // keeps captured pages in its private VM. + if !self.pages.is_empty() || self.output_first.is_some() { return Err(ENOTSUPP); } + let user_mappings = vm.retain_job()?; + self.context.rebind(vm)?; + // Release the previous VM's mapping hold only after its roots are gone. + self.user_mappings = Some(user_mappings); + let aliases = self.usc.alias_into(vm)?; + dev_dbg!(dev.as_ref(), "M5_GRAPHICS_CONTEXT id={} rebound vm={} roots={:x?}; USC pool aliased\n", + self.context.context_id(), vm.id(), self.context.roots()); + Ok(aliases) + } + + /// Return an owning allocation in the compact TA resource arena. The + /// render job retains it until completion or confirmed processor stop. + pub(super) fn allocate_compact( + &self, dev: &AsahiDrmDevice, size: usize, alignment: u64, prot: mmu::Prot, + ) -> Result { + let range = crate::m5::vm_layout::compact_range(&self.vm().kernel_range()).ok_or(EINVAL)?; + MappedObject::new_wc_in_range_with_guards( + dev, self.vm(), range, size, alignment, prot, 2, + ) + } + + /// Job construction can add its own objects before root publication. + pub(super) fn vm(&self) -> &mmu::Vm { + self.context.vm() + } + + pub(super) fn context_id(&self) -> u8 { self.context.context_id() } + + pub(super) fn roots(&self) -> [u64; 2] { + self.context.roots() + } + + pub(super) fn usc(&self) -> &M5GraphicsUsc { + &self.usc + } + + /// A stop request is not proof that hardware has released these mappings. + /// Close VM_BIND admission before any future error fence can wake userspace. + pub(super) fn quarantine(&self) { + if let Some(guard) = &self.user_mappings { + guard.quarantine(); + } + } + + /// Alias existing owned user pages into the firmware VM. PM page lists + /// and scene counters must share backing with their user GPU views. + /// The returned mappings belong to the eventual retained job owner. + pub(super) fn alias_kernel_pages( + &mut self, + uat: &mmu::Uat, + user_address: u64, + kernel_address: u64, + bytes: usize, + ) -> Result> { + if self.context.is_current() { + return Err(EBUSY); + } + if bytes == 0 + || bytes > MAX_PAGES * PAGE_BYTES + || bytes % PAGE_BYTES != 0 + || (user_address | kernel_address) & (PAGE_BYTES as u64 - 1) != 0 + { + return Err(EINVAL); + } + user_address.checked_add(bytes as u64).ok_or(EOVERFLOW)?; + kernel_address.checked_add(bytes as u64).ok_or(EOVERFLOW)?; + let mut indices = KVec::new(); + for offset in (0..bytes).step_by(PAGE_BYTES) { + let address = user_address + offset as u64; + let index = self + .pages + .iter() + .position(|page| page.iova() == address) + .ok_or(EFAULT)?; + indices.push(index, GFP_KERNEL)?; + } + let mut aliases = KVec::new(); + for (ordinal, index) in indices.iter().enumerate() { + let high = kernel_address + (ordinal * PAGE_BYTES) as u64; + let alias = + self.pages[*index].map_alias_at(uat.kernel_vm(), high, mmu::PROT_FW_SHARED_RW)?; + if uat.kernel_vm().translate_iova(high)? + != self + .context + .vm() + .translate_iova(self.pages[*index].iova())? + { + return Err(EFAULT); + } + aliases.push(alias, GFP_KERNEL)?; + } + Ok(aliases) + } + + /// Read a word from a retained reference page while preparing its job. + pub(super) fn read_word(&mut self, address: u64) -> Result { + if address & 3 != 0 { + return Err(EINVAL); + } + let base = address & !(PAGE_BYTES as u64 - 1); + let page = self + .pages + .iter_mut() + .find(|page| page.iova() == base) + .ok_or(EFAULT)?; + page.read_u32(address) + } + + /// Reset owned PM outputs before exposing the context to either firmware. + pub(super) fn clear_pages(&mut self, address: u64, bytes: usize) -> Result { + if self.context.is_current() || bytes == 0 || bytes % PAGE_BYTES != 0 + || address & (PAGE_BYTES as u64 - 1) != 0 { + return Err(EINVAL); + } + let end = address.checked_add(bytes as u64).ok_or(EOVERFLOW)?; + let count = self.pages.iter().filter(|p| p.iova() >= address && p.iova() < end).count(); + if count != bytes / PAGE_BYTES { return Err(EFAULT); } + for page in self.pages.iter_mut().filter(|p| p.iova() >= address && p.iova() < end) { + page.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + } + Ok(()) + } + + pub(super) fn write_word(&mut self, address: u64, value: u32) -> Result { + if self.context.is_current() || address & 3 != 0 { return Err(EINVAL); } + let base = address & !(PAGE_BYTES as u64 - 1); + let offset = (address - base) as usize; + let page = self.pages.iter_mut().find(|p| p.iova() == base).ok_or(EFAULT)?; + page.with_bytes_mut(|out| { + out[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + Ok(()) + }) + } + + /// Call only after the complete TA/3D resource graph is prepared. + pub(super) fn publish(&mut self) -> Result { + self.context.publish() + } + + pub(super) fn is_current(&self) -> bool { + self.context.is_current() + } + +} diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_queues.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_queues.rs new file mode 100644 index 0000000000000..02850fbe073df --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_queues.rs @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Paired first-submission queues for the retained M5 graphics experiment. + +use super::{graphics_job::{M5GraphicsJob, PB_HARDWARE_ID, QUEUE_IDS}, graphics_usc, + firmware_view::FirmwareDataView, MappedObject}; +use crate::{driver::AsahiDrmDevice, m5::submission, m5::channel, m5::sksm, mmu}; +use crate::m5::completion::{graphics_pointer_head, GRAPHICS_POINTER_COUNT, + MAX_GRAPHICS_GENERATION}; +use kernel::prelude::*; + +const HIGH: u64 = 0xffff_fc20_c000_0000; +const ENTRY_HIGH: u64 = 0xffff_fc20_0039_0000; +const ENTRY_LOW: u64 = 0x70_005f_0000; +const ENTRY_BYTES: usize = 0x20000; +const CONTROL: usize = 0x18000; +// Native TA and fragment channel+0x10 both point to fffffc2000000048. +// One scheduler belongs to one intrusive list even when two SKSM queues run it. +pub(super) const JOB_LIST: u64 = HIGH + 0x20000; +const POINTERS: [usize; 2] = [0x4000, 0xc000]; +const ITEMS: [usize; 2] = [0x8000, 0x10000]; +const CONFIG: [usize; 2] = [0xa800, 0x12800]; + +pub(super) struct M5GraphicsQueues { + aliases: KVec, + entries: KVec, + graph: MappedObject, + job_list: MappedObject, + firmware: FirmwareDataView, +} + +impl M5GraphicsQueues { + pub(super) fn new(dev: &AsahiDrmDevice, uat: &mmu::Uat, job: &M5GraphicsJob) -> Result { + let mut graph = MappedObject::new_wc_at(dev, uat.kernel_vm(), HIGH, + 0x20000, mmu::PROT_FW_PRIV_RW)?; + let mut job_list = MappedObject::new_wc_at(dev, uat.kernel_vm(), JOB_LIST, + 0x4000, mmu::PROT_FW_SHARED_RW)?; + job_list.with_bytes_mut(|out| { put64(out, 8, JOB_LIST); Ok(()) })?; + let mut entries = KVec::new(); + let mut aliases = KVec::new(); + for stage in 0..2 { + let id = QUEUE_IDS[stage]; + let high = ENTRY_HIGH + (stage * ENTRY_BYTES) as u64; + let low = ENTRY_LOW + (stage * ENTRY_BYTES) as u64; + let mut entry = MappedObject::new_wc_at(dev, uat.kernel_vm(), high, + ENTRY_BYTES, mmu::PROT_FW_PRIV_RW)?; + let alias = entry.map_alias_at(uat.kernel_lower_vm(), low, mmu::PROT_GPU_SHARED_RW)?; + for offset in (0..ENTRY_BYTES).step_by(mmu::UAT_PGSZ) { + if uat.kernel_vm().translate_iova(high + offset as u64)? + != uat.kernel_lower_vm().translate_iova(low + offset as u64)? { + return Err(EFAULT); + } + } + let [descriptor, _] = job.descriptor_addresses(stage)?; + let dm = if stage == 0 { sksm::M5DataMaster::Tiling } + else { sksm::M5DataMaster::Fragment }; + let prepared = Self::prepare_entry(job, stage, 1)?; + entry.with_bytes_mut(|out| { + out[prepared.offset as usize..prepared.offset as usize + prepared.bytes.len()] + .copy_from_slice(&prepared.bytes); + Ok(()) + })?; + let install = channel::encode_m5_channel_config_for(channel::M5ChannelConfig { + ring_low: low, ring_high: high, queue_id: id, priority: 2, + install_queue: true, gpu_context: job.context_id(), event: None, + channel_control: HIGH + CONTROL as u64, update_scheduler: true, + scheduler_index: 0, channel_stamp_index: stage as u32, + update_context: false, owner_context: 0, extended_command: false, + }, stage as u32, 2, None, None).map_err(|_| EINVAL)?; + let config = channel::encode_m5_channel_config_for(channel::M5ChannelConfig { + ring_low: low, ring_high: high, queue_id: id, priority: 2, + install_queue: false, gpu_context: job.context_id(), + event: Some(channel::M5ChannelEvent { address: job.usc_control(), + timestamp: 1, index: graphics_usc::HARDWARE_ID }), + channel_control: HIGH + CONTROL as u64, update_scheduler: false, + scheduler_index: 0, channel_stamp_index: stage as u32, + update_context: true, owner_context: 1, extended_command: false, + }, stage as u32, 2, Some(0), if stage == 0 { + Some(channel::M5ParameterBufferEvent { address: job.parameter_state(), + timestamp: 1, hardware_buffer_id: PB_HARDWARE_ID, manager_id: 0 }) + } else { None }).map_err(|_| EINVAL)?; + let kick = sksm::encode_m5_sksm_add_kicks_for(dm, id, 2, 1, 1) + .map_err(|_| EINVAL)?; + graph.with_bytes_mut(|out| { + let pointers = POINTERS[stage]; + let queue = id as usize * 0xc0; + let reset = submission::encode_m5_25g76_channel_state_reset( + submission::M5ChannelStateResetValues { + uncached_state: HIGH + pointers as u64, + command_pointer_ring: HIGH + ITEMS[stage] as u64, + gpu_va_10: JOB_LIST, word_48: 0, + gpu_va_9c: HIGH + CONTROL as u64, + }); + out[queue..queue + 0xc0].copy_from_slice(&reset); + for offset in [0x28, 0x2c, 0x40] { put32(out, queue + offset, 2); } + out[queue + 0x36..queue + 0x38].fill(0xff); + put32(out, pointers + 0x50, u32::MAX); + put32(out, pointers + 0x60, 0x500); + out[CONFIG[stage]..CONFIG[stage] + install.len()].copy_from_slice(&install); + out[CONFIG[stage] + 0x100..CONFIG[stage] + 0x100 + config.len()].copy_from_slice(&config); + out[CONFIG[stage] + 0x200..CONFIG[stage] + 0x200 + kick.len()].copy_from_slice(&kick); + for (index, address) in [HIGH + CONFIG[stage] as u64, descriptor, + HIGH + CONFIG[stage] as u64 + 0x100, + HIGH + CONFIG[stage] as u64 + 0x200].into_iter().enumerate() { + put64(out, ITEMS[stage] + index * 8, address); + } + // Publish only installation. The draw stays beyond the producer + // until both firmware queue slots and scheduler bindings verify. + put32(out, pointers + 0x40, 1); + Ok(()) + })?; + aliases.push(alias, GFP_KERNEL)?; + entries.push(entry, GFP_KERNEL)?; + } + graph.with_bytes_mut(|out| { + out[CONTROL..CONTROL + 2].fill(0xff); + out[CONTROL + 5] = 1; + out[CONTROL + 0x26] = 2; + out[CONTROL + 0x33] = 0xff; + Ok(()) + })?; + Ok(Self { aliases, entries, graph, job_list, firmware: FirmwareDataView::new(dev)? }) + } + + pub(super) fn queue_address(stage: usize) -> Result { + Ok(HIGH + *QUEUE_IDS.get(stage).ok_or(EINVAL)? as u64 * 0xc0) + } + + fn prepare_entry(job: &M5GraphicsJob, stage: usize, generation: u32) + -> Result { + if !(1..=MAX_GRAPHICS_GENERATION).contains(&generation) { return Err(EINVAL); } + let id = *QUEUE_IDS.get(stage).ok_or(EINVAL)?; + let [descriptor, descriptor_low] = job.descriptor_addresses(stage)?; + let stamp = generation as u64; + let barrier = [sksm::M5SksmDependency { queue_id: QUEUE_IDS[0], stamp, kind: 1 }]; + let mut rce = [sksm::M5SksmRce { address: 0, tag: 0 }; 4]; + if stage == 0 { + rce[0] = sksm::M5SksmRce { address: descriptor_low + 0x60, tag: 79 }; + } else { + for (index, (offset, count)) in [(0xa0, 87), (0x7c0, 18), + (0xee0, 25), (0x1600, 12)].into_iter().enumerate() { + rce[index] = sksm::M5SksmRce { address: descriptor_low + offset, tag: count }; + } + } + sksm::prepare_m5_sksm_entry(sksm::M5SksmQueue { + id, priority: 2, current_stamp: stamp, submitted: 0, + previous_stamp: if generation == 1 { None } else { Some(stamp - 1) }, + }, sksm::M5SksmOperands { + barriers: if stage == 0 { &[] } else { &barrier }, first_predecessor: 0, + implicit_dependency_type: 1, mcache: None, flag_bit1: false, + flag_bit61: false, flag_bit63: false, + payload: [descriptor, Self::queue_address(stage)?], + qos_byte_32: 3, qos_class_40: if stage == 0 { 12 } else { 24 }, + qos_word_48: 0xffff, event_mask: [0; 4], rce_kind: 0, rce, + auxiliary: 0x3f_ffff_ffff_ffff, + }).map_err(|_| EINVAL) + } + + pub(super) fn publish_next_draw(&mut self, job: &M5GraphicsJob, generation: u32) -> Result { + if !(2..=MAX_GRAPHICS_GENERATION).contains(&generation) { return Err(EINVAL); } + let previous_head = graphics_pointer_head(generation - 1); + if self.counters()? != [[previous_head; 3]; 2] || !self.installed()? + || self.completion_list()? != [0, JOB_LIST] { return Err(EBUSY); } + for stage in 0..2 { + let prepared = Self::prepare_entry(job, stage, generation)?; + self.entries[stage].with_bytes_mut(|out| { + let offset = prepared.offset as usize; + let slot = &mut out[offset..offset + prepared.bytes.len()]; + // Every preceding job has retired, including the prior user + // of this 256-entry SKSM slot. Preserve the first-use check. + if generation < 256 && slot.iter().any(|byte| *byte != 0) { + return Err(EBUSY); + } + slot.copy_from_slice(&prepared.bytes); + Ok(()) + })?; + let dm = if stage == 0 { sksm::M5DataMaster::Tiling } + else { sksm::M5DataMaster::Fragment }; + let kick = sksm::encode_m5_sksm_add_kicks_for(dm, QUEUE_IDS[stage], + 2, generation as u64, 1).map_err(|_| EINVAL)?; + self.graph.with_bytes_mut(|out| { + out[CONFIG[stage] + 0x200..CONFIG[stage] + 0x200 + kick.len()] + .copy_from_slice(&kick); + let addresses = [job.descriptor_addresses(stage)?[0], + HIGH + CONFIG[stage] as u64 + 0x100, + HIGH + CONFIG[stage] as u64 + 0x200]; + for (index, address) in addresses.into_iter().enumerate() { + let absolute = 1 + (generation as usize - 1) * 3 + index; + let offset = ITEMS[stage] + (absolute % GRAPHICS_POINTER_COUNT as usize) * 8; + if absolute < GRAPHICS_POINTER_COUNT as usize + && out[offset..offset + 8].iter().any(|byte| *byte != 0) { + return Err(EBUSY); + } + put64(out, offset, address); + } + Ok(()) + })?; + } + for pointers in POINTERS { + self.graph.write_u32(HIGH + pointers as u64 + 0x40, + graphics_pointer_head(generation))?; + } + Ok(()) + } + + pub(super) fn counters(&mut self) -> Result<[[u32; 3]; 2]> { + let mut result = [[0; 3]; 2]; + for stage in 0..2 { + for (index, offset) in [0, 0x30, 0x40].into_iter().enumerate() { + result[stage][index] = self.graph.read_u32(HIGH + (POINTERS[stage] + offset) as u64)?; + } + } + Ok(result) + } + + pub(super) fn completion_list(&mut self) -> Result<[u64; 2]> { + Ok([self.job_list.read_u64(JOB_LIST)?, self.job_list.read_u64(JOB_LIST + 8)?]) + } + + pub(super) fn installation_status(&mut self) -> Result<([[u64; 5]; 2], [u64; 2], [u64; 2])> { + let mut slots = [[0; 5]; 2]; + let mut pointers = [0; 2]; + for stage in 0..2 { + (slots[stage], pointers[stage]) = self.firmware.queue_registration(QUEUE_IDS[stage])?; + } + Ok((slots, pointers, [u64::from(self.graph.read_u32(HIGH + CONTROL as u64)?), + self.graph.read_u64(HIGH + CONTROL as u64 + 0x12)?])) + } + + pub(super) fn installed(&mut self) -> Result { + let (slots, pointers, control) = self.installation_status()?; + for stage in 0..2 { + let slot = slots[stage]; + let offset = (stage * ENTRY_BYTES) as u64; + // GFX 0x12240/0x1241c copies tag15 +0x22 to slot +0x20: + // this word is the TA/fragment stage, not the outer channel. + if slot[0] & 1 == 0 || slot[1] != ENTRY_HIGH + offset + || slot[2] != ENTRY_LOW + offset || slot[3] != 4u64 << 32 + || slot[4] as u32 != stage as u32 || pointers[stage] != HIGH + CONTROL as u64 { + return Ok(false); + } + } + Ok(control[0] & 0xff != 0xff && (control[0] >> 8) & 0xff != 0xff + && (control[0] >> 16) & 0xff == 4 + && control[1] == ((1u64 << QUEUE_IDS[0]) | (1u64 << QUEUE_IDS[1]))) + } + + pub(super) fn publish_draw(&mut self) -> Result { + if self.counters()? != [[1; 3]; 2] || !self.installed()? { return Err(EBUSY); } + for pointers in POINTERS { + self.graph.write_u32(HIGH + pointers as u64 + 0x40, 4)?; + } + Ok(()) + } +} + +fn put32(out: &mut [u8], offset: usize, value: u32) { + out[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} +fn put64(out: &mut [u8], offset: usize, value: u64) { + out[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs new file mode 100644 index 0000000000000..1d5bd727ee719 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Retained USC backing in an M5 application's reserved driver VA region. +//! +//! Firmware records are encoded from the owned mappings, never fixed test +//! addresses. Guard pages belong to each mapping's allocator reservation. +//! No root or firmware table is published here. + +use super::MappedObject; +use crate::{driver::AsahiDrmDevice, mmu}; +use kernel::prelude::*; + +pub(super) const HARDWARE_ID: u32 = 1; +const DIRECTORY_ENTRIES: usize = 0x80000; +const BLOCK_BYTES: usize = 0x20_0000; +const BLOCK_COUNT: usize = 19; +const UNIT_BYTES: usize = 0x1000; +const UNIT_COUNT: usize = BLOCK_COUNT * BLOCK_BYTES / UNIT_BYTES; +pub(super) const CAPACITY_BYTES: u64 = (BLOCK_COUNT * BLOCK_BYTES) as u64; + +pub(super) struct M5GraphicsUsc { + directory: MappedObject, + freelist: MappedObject, + blocks: KVec, +} + +impl M5GraphicsUsc { + pub(super) fn new(dev: &AsahiDrmDevice, vm: &mmu::Vm) -> Result { + Self::new_in_range(dev, vm, vm.kernel_range()) + } + + pub(super) fn new_application(dev: &AsahiDrmDevice, vm: &mmu::Vm) -> Result { + let range = crate::m5::vm_layout::auxiliary_range(&vm.kernel_range()).ok_or(EINVAL)?; + Self::new_in_range(dev, vm, range) + } + + fn new_in_range( + dev: &AsahiDrmDevice, vm: &mmu::Vm, range: core::ops::Range, + ) -> Result { + let allocate = |size, guard_pages| MappedObject::new_wc_in_range_with_guards( + dev, vm, range.clone(), size, 0x8000, mmu::PROT_GPU_SHARED_RW, guard_pages, + ); + let mut directory = allocate(DIRECTORY_ENTRIES * 8, 2)?; + let mut freelist = allocate(mmu::UAT_PGSZ, 1)?; + let mut blocks = KVec::new(); + for _ in 0..BLOCK_COUNT { + blocks.push(allocate(BLOCK_BYTES, 2)?, GFP_KERNEL)?; + } + directory.with_bytes_mut(|out| { + for unit in 0..UNIT_COUNT { + let address = Self::unit_address(&blocks, unit).ok_or(EINVAL)?; + out[unit * 8..unit * 8 + 8].copy_from_slice(&address.to_le_bytes()); + } + Ok(()) + })?; + freelist.with_bytes_mut(|out| { + // Same initial free-block format as the qualified M5 compute + // pool. Every allocation here is free; no native growth history + // or in-use allocator contents are imported. + for block in 0..BLOCK_COUNT { + let address = blocks[block].iova(); + out[block * 0x40..block * 0x40 + 8] + .copy_from_slice(&(address | (1u64 << 61)).to_le_bytes()); + } + Ok(()) + })?; + let mut result = Self { directory, freelist, blocks }; + result.validate(vm)?; + dev_dbg!(dev.as_ref(), + "M5_GRAPHICS_USC reserved={:#x}..{:#x} directory={:#x} freelist={:#x} blocks={} capacity={:#x}; guard pages reserved\n", + range.start, range.end, result.directory.iova(), result.freelist.iova(), + BLOCK_COUNT, CAPACITY_BYTES); + Ok(result) + } + + fn unit_address(blocks: &[MappedObject], unit: usize) -> Option { + if unit >= UNIT_COUNT { return None; } + let units_per_block = BLOCK_BYTES / UNIT_BYTES; + Some(blocks.get(unit / units_per_block)?.iova() + + (unit % units_per_block * UNIT_BYTES) as u64) + } + + pub(super) fn descriptor(&self) -> [u64; 4] { + // M5 halLoadUMADesc: 4-KiB population, not 16-KiB CPU page count. + [self.directory.iova() >> 7, (UNIT_COUNT as u64) << 32, + (DIRECTORY_ENTRIES as u64) << 32 | UNIT_COUNT as u64, 0] + } + + /// Initialize a fresh owner using the qualified M5 initial-state recipe. + /// Native graphics snapshots include later growth generations; copying + /// their seeds/disabled flag would disagree with these all-free blocks. + pub(super) fn encode_initial_owner(&self, inner: u64, out: &mut [u8]) -> Result { + if out.len() < 0x70 || inner < 0xffff_fc00_0000_0000 || inner & 7 != 0 { + return Err(EINVAL); + } + out[..0x70].fill(0); + for (offset, value) in [(0, 1u32), (8, HARDWARE_ID), (0x10, 2), + (0x1c, DIRECTORY_ENTRIES as u32), (0x24, UNIT_COUNT as u32), + (0x2c, UNIT_COUNT as u32), (0x40, 4), (0x48, (BLOCK_COUNT * 8) as u32), + (0x5c, 1), (0x60, 2)] { + out[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + for (offset, address) in [(0x14, self.directory.iova()), + (0x30, self.freelist.iova()), (0x4c, inner)] { + out[offset..offset + 8].copy_from_slice(&address.to_le_bytes()); + } + Ok(()) + } + + /// Map the retained pool into another application VM at the same + /// addresses, reproducing each allocation's guard reservation, so every + /// firmware record naming the directory, free list or blocks stays valid + /// across a render client handoff. The returned aliases must be kept for + /// as long as that VM may submit. + pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { + let range = crate::m5::vm_layout::auxiliary_range(&vm.kernel_range()).ok_or(EINVAL)?; + let mut aliases = KVec::new(); + let alias = |object: &mut MappedObject, size: usize, guards: usize, + aliases: &mut KVec| -> Result { + let end = object.iova().checked_add((size + guards * mmu::UAT_PGSZ) as u64) + .ok_or(EOVERFLOW)?; + if object.iova() < range.start || end > range.end { return Err(ERANGE); } + if let Some(mapping) = object.map_alias_at_with_guards( + vm, object.iova(), mmu::PROT_GPU_SHARED_RW, guards)? { + aliases.push(mapping, GFP_KERNEL)?; + } + Ok(()) + }; + alias(&mut self.directory, DIRECTORY_ENTRIES * 8, 2, &mut aliases)?; + alias(&mut self.freelist, mmu::UAT_PGSZ, 1, &mut aliases)?; + for block in self.blocks.iter_mut() { + alias(block, BLOCK_BYTES, 2, &mut aliases)?; + } + // Only the mappings are checked here: the firmware has been + // advancing the free-ring cursors and returning directory units + // while the pool was in use, so the construction-time contents no + // longer hold and must not be re-asserted on handoff. + self.validate_mappings(vm)?; + Ok(aliases) + } + + /// Verify every CPU page named by the populated 4-KiB directory and the + /// free-block heads. The allocator keeps the underlying mappings alive. + pub(super) fn validate(&mut self, vm: &mmu::Vm) -> Result { + self.validate_mappings(vm)?; + self.validate_contents() + } + + /// Range, alignment, guard-gap and translation checks for every pool + /// object in `vm`; valid before and after firmware use of the pool. + fn validate_mappings(&self, vm: &mmu::Vm) -> Result { + if self.blocks.len() != BLOCK_COUNT { return Err(EFAULT); } + let range = vm.kernel_range(); + let validate_guards = |object: &MappedObject, size: usize, guards: usize| -> Result { + let end = object.iova().checked_add((size + guards * mmu::UAT_PGSZ) as u64) + .ok_or(EOVERFLOW)?; + if object.iova() < range.start || end > range.end + || object.iova() & 0x7fff != 0 { return Err(EFAULT); } + // Check after every allocation has completed: a later neighbor + // must not have consumed either reserved 16-KiB guard page. + for guard in 0..guards { + if vm.translate_iova(object.iova() + (size + guard * mmu::UAT_PGSZ) as u64).is_ok() { + return Err(EFAULT); + } + } + Ok(()) + }; + validate_guards(&self.directory, DIRECTORY_ENTRIES * 8, 2)?; + validate_guards(&self.freelist, mmu::UAT_PGSZ, 1)?; + for block in &self.blocks { validate_guards(block, BLOCK_BYTES, 2)?; } + let translate_all = |object: &MappedObject| -> Result { + for offset in (0..object.logical_size).step_by(mmu::UAT_PGSZ) { + vm.translate_iova(object.iova() + offset as u64)?; + } + Ok(()) + }; + translate_all(&self.directory)?; + translate_all(&self.freelist)?; + for block in &self.blocks { translate_all(block)?; } + Ok(()) + } + + /// Construction-time contents: an all-free block list and a directory + /// that names every unit in order. Firmware use changes both. + fn validate_contents(&mut self) -> Result { + for block in 0..BLOCK_COUNT { + let base = self.blocks[block].iova(); + if self.freelist.read_u64(self.freelist.iova() + (block * 0x40) as u64)? + != (base | (1u64 << 61)) { + return Err(EFAULT); + } + } + for unit in 0..UNIT_COUNT { + if self.directory.read_u64(self.directory.iova() + (unit * 8) as u64)? + != Self::unit_address(&self.blocks, unit).ok_or(EFAULT)? { + return Err(EFAULT); + } + } + if self.directory.read_u64(self.directory.iova() + (UNIT_COUNT * 8) as u64)? != 0 { + return Err(EFAULT); + } + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs new file mode 100644 index 0000000000000..3c6b955b6c799 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! VM-owned parameter buffer for the qualified 256x256 M5 render profile. +//! +//! The allocation addresses are dynamic. Capacity and scene layout remain +//! the witnessed native profile; larger renders and pool growth are separate. + +use super::{graphics_memory::M5GraphicsMemory, MappedObject}; +use crate::{driver::AsahiDrmDevice, mmu, m5::vm_layout}; +use kernel::prelude::*; + +pub(super) const BLOCK_BYTES: usize = 0x80000; +pub(super) const PAGE_LIST_BYTES: usize = 0x1c000; +pub(super) const PAGE_COUNT: u32 = 48; + +pub(super) struct M5ParameterBuffer { + blocks: [MappedObject; 3], + page_list: MappedObject, + metrics: MappedObject, + scene_scratch: MappedObject, + discard: MappedObject, +} + +impl M5ParameterBuffer { + pub(super) fn new_reference(dev: &AsahiDrmDevice, memory: &M5GraphicsMemory) -> Result { + let allocate = |size| memory.allocate_compact( + dev, size, 0x8000, mmu::PROT_GPU_SHARED_RW, + ); + let mut owner = Self { + blocks: [allocate(BLOCK_BYTES)?, allocate(BLOCK_BYTES)?, allocate(BLOCK_BYTES)?], + page_list: allocate(PAGE_LIST_BYTES)?, + metrics: allocate(0x4000)?, + scene_scratch: allocate(0x4000)?, + discard: allocate(0x8000)?, + }; + let block_bases = owner.block_page_bases()?; + owner.page_list.with_bytes_mut(|out| { + for (block, first) in block_bases.into_iter().enumerate() { + for page in 0..16 { + let offset = (block * 16 + page) * 4; + out[offset..offset + 4].copy_from_slice(&(first + page as u32).to_le_bytes()); + } + } + Ok(()) + })?; + owner.validate(memory.vm())?; + dev_dbg!(dev.as_ref(), + "M5_PARAMETER_BUFFER blocks={:x?} page_list={:#x} metrics={:#x} scene={:#x} discard={:#x}; compact mappings owned\n", + owner.blocks.each_ref().map(|b| b.iova()), owner.page_list(), owner.metrics(), + owner.scene_scratch.iova(), owner.discard.iova()); + Ok(owner) + } + + pub(super) fn block_page_bases(&self) -> Result<[u32; 3]> { + let mut bases = [0; 3]; + for (base, block) in bases.iter_mut().zip(self.blocks.iter()) { + let offset = block.iova().checked_sub(vm_layout::DRIVER_BASE).ok_or(ERANGE)?; + if offset & 0x7fff != 0 { return Err(EINVAL); } + *base = u32::try_from(offset >> 15).map_err(|_| ERANGE)?; + } + Ok(bases) + } + + pub(super) fn page_list(&self) -> u64 { self.page_list.iova() } + pub(super) fn metrics(&self) -> u64 { self.metrics.iova() } + pub(super) fn scene_cycle(&self) -> u64 { + self.scene_scratch.iova() - vm_layout::DRIVER_BASE + 0x40 + } + pub(super) fn discard_offset(&self) -> u64 { + self.discard.iova() - vm_layout::DRIVER_BASE + } + + /// Firmware and application views must reference the same backing. + pub(super) fn firmware_aliases( + &mut self, uat: &mmu::Uat, vm: &mmu::Vm, page_list_high: u64, metrics_high: u64, + ) -> Result> { + let mut aliases = KVec::new(); + for (object, high) in [(&mut self.page_list, page_list_high), (&mut self.metrics, metrics_high)] { + let alias = object.map_alias_at(uat.kernel_vm(), high, mmu::PROT_FW_SHARED_RW)?; + for offset in (0..object.logical_size).step_by(mmu::UAT_PGSZ) { + if uat.kernel_vm().translate_iova(high + offset as u64)? + != vm.translate_iova(object.iova() + offset as u64)? { + return Err(EFAULT); + } + } + aliases.push(alias, GFP_KERNEL)?; + } + Ok(aliases) + } + + /// Map the retained pool into another application VM at the same compact + /// addresses with the original two-page guard reservations, so the + /// firmware's parameter-manager records keep naming valid pages after a + /// render client handoff. + pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { + let range = vm_layout::compact_range(&vm.kernel_range()).ok_or(EINVAL)?; + let mut aliases = KVec::new(); + let alias = |object: &mut MappedObject, aliases: &mut KVec| -> Result { + let end = object.iova() + .checked_add((object.logical_size + 2 * mmu::UAT_PGSZ) as u64) + .ok_or(EOVERFLOW)?; + if object.iova() < range.start || end > range.end { return Err(ERANGE); } + if let Some(mapping) = object.map_alias_at_with_guards( + vm, object.iova(), mmu::PROT_GPU_SHARED_RW, 2)? { + aliases.push(mapping, GFP_KERNEL)?; + } + Ok(()) + }; + for block in self.blocks.iter_mut() { alias(block, &mut aliases)?; } + alias(&mut self.page_list, &mut aliases)?; + alias(&mut self.metrics, &mut aliases)?; + alias(&mut self.scene_scratch, &mut aliases)?; + alias(&mut self.discard, &mut aliases)?; + self.validate(vm)?; + Ok(aliases) + } + + fn validate(&self, vm: &mmu::Vm) -> Result { + let check = |object: &MappedObject| -> Result { + let start = object.iova(); + let end = start.checked_add(object.logical_size as u64).ok_or(EOVERFLOW)?; + if start < vm_layout::DRIVER_BASE || end > vm_layout::COMPACT_END + || start & 0x7fff != 0 { return Err(ERANGE); } + for offset in (0..object.logical_size).step_by(mmu::UAT_PGSZ) { + vm.translate_iova(start + offset as u64)?; + } + for page in 0..2 { + if vm.translate_iova(end + page * mmu::UAT_PGSZ as u64).is_ok() { + return Err(EFAULT); + } + } + Ok(()) + }; + for block in &self.blocks { check(block)?; } + for object in [&self.page_list, &self.metrics, &self.scene_scratch, &self.discard] { + check(object)?; + } + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/m5/resources/target_memory.rs b/drivers/gpu/drm/asahi/m5/resources/target_memory.rs new file mode 100644 index 0000000000000..f0f2c5176018d --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/resources/target_memory.rs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Driver-owned render targets in the actual submitting VM. + +use super::{graphics_memory::M5GraphicsMemory, MappedObject}; +use crate::{driver::AsahiDrmDevice, m5::render_desc::G17pRenderParameters, mmu, m5::vm_layout, + m5::render_target::{self, M5RenderTargetLayout, PAGE_BYTES, AUX_BYTES}}; +use kernel::prelude::*; + +pub(super) struct M5TargetMemory { + target: MappedObject, + tpc: MappedObject, + deflake: MappedObject, + ta_status: MappedObject, + fragment_status: MappedObject, + auxiliary: MappedObject, + layout: M5RenderTargetLayout, +} + +impl M5TargetMemory { + pub(super) fn new( + dev: &AsahiDrmDevice, memory: &M5GraphicsMemory, p: &G17pRenderParameters, + clusters: u32, + ) -> Result { + let layout = M5RenderTargetLayout::new(p.width, p.height, p.layers, + p.utile_width, p.utile_height, clusters).ok_or(EINVAL)?; + let allocate = |size| memory.allocate_compact( + dev, size, 0x8000, mmu::PROT_GPU_SHARED_RW, + ); + let mut owner = Self { + target: allocate(layout.target_bytes)?, tpc: allocate(layout.tpc_bytes)?, + deflake: allocate(PAGE_BYTES)?, ta_status: allocate(PAGE_BYTES)?, + fragment_status: allocate(PAGE_BYTES)?, auxiliary: allocate(AUX_BYTES)?, layout, + }; + owner.deflake.with_bytes_mut(|bytes| { + render_target::initialize_deflake(bytes, p.width, p.height).ok_or(EINVAL) + })?; + owner.validate(memory.vm())?; + dev_dbg!(dev.as_ref(), + "M5_RENDER_TARGET target={:#x}/{:#x} heapmeta={:#x} tpc={:#x}/{:#x} deflake={:#x} status={:x?} auxiliary={:#x}; VM-owned\n", + owner.target.iova(), layout.target_bytes, owner.target.iova() + layout.heapmeta_offset as u64, + owner.tpc.iova(), layout.tpc_bytes, owner.deflake.iova(), + [owner.ta_status.iova(), owner.fragment_status.iova()], owner.auxiliary.iova()); + Ok(owner) + } + + pub(super) fn apply(&self, p: &mut G17pRenderParameters) { + p.context_base = vm_layout::DRIVER_BASE; + p.tilemap = self.target.iova(); + p.heapmeta = self.target.iova() + self.layout.heapmeta_offset as u64; + p.tpc = self.tpc.iova(); + p.deflake_3 = self.deflake.iova(); + p.deflake_2 = self.deflake.iova() + 0x40; + p.deflake_1 = self.deflake.iova() + 0x340; + p.ta_status = self.ta_status.iova(); + p.fragment_status = self.fragment_status.iova(); + p.aux_fb = self.auxiliary.iova(); + } + + fn validate(&self, vm: &mmu::Vm) -> Result { + for object in [&self.target, &self.tpc, &self.deflake, &self.ta_status, + &self.fragment_status, &self.auxiliary] { + let start = object.iova(); + let end = start.checked_add(object.logical_size as u64).ok_or(EOVERFLOW)?; + if start < vm_layout::DRIVER_BASE || end > vm_layout::COMPACT_END + || start & 0x7fff != 0 { return Err(ERANGE); } + for offset in (0..object.logical_size).step_by(PAGE_BYTES) { + vm.translate_iova(start + offset as u64)?; + } + for page in 0..2 { + if vm.translate_iova(end + page * PAGE_BYTES as u64).is_ok() { return Err(EFAULT); } + } + } + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/m5/sksm.rs b/drivers/gpu/drm/asahi/m5/sksm.rs new file mode 100644 index 0000000000000..826f1def2c9b4 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/sksm.rs @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +#![cfg_attr(not(test), allow(dead_code))] + +//! T8142/25G76 HAL300 SKSM entry and tag-14 serialization. +//! +//! The M5 host clears 0x200 bytes and writes two-bit dependency types at +//! +0x180. Neo's 0x180-byte entry cannot represent this data. These pure +//! builders do not register queues, publish producers or ring a doorbell. +//! Callers must retain every referenced object and implement the M5 lifetime +//! and completion protocol before any generated bytes reach firmware. + +pub(crate) const M5_SKSM_ENTRY_BYTES: usize = 0x200; +pub(crate) const M5_SKSM_ENTRY_COUNT: u32 = 256; + +/// Logical channel selector measured in native TA, 3D and CL tag-14 records. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u32)] +pub(crate) enum M5DataMaster { + Tiling = 0, + Fragment = 1, + Compute = 2, +} +const STAMP_MASK: u64 = (1 << 40) - 1; +const PACKED_ADDRESS_MASK: u64 = (1 << 38) - 1; + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum M5SksmError { + QueueId, + Priority, + Stamp, + QueueFull, + Dependencies, + DependencyType, + Address, + Mcache, + Rce, + Qos, + AddCount, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5SksmDependency { + pub(crate) queue_id: u8, + /// Already converted to the hardware's 32-bit generation / 8-bit index. + pub(crate) stamp: u64, + pub(crate) kind: u8, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5SksmRce { + pub(crate) address: u64, + pub(crate) tag: u8, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5SksmMcache { + pub(crate) address: u64, + pub(crate) index: u8, + pub(crate) count: u8, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5SksmQueue { + pub(crate) id: u8, + /// Host queue +0x1c, not the outer firmware channel's priority. + pub(crate) priority: u8, + pub(crate) current_stamp: u64, + pub(crate) submitted: u32, + pub(crate) previous_stamp: Option, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5SksmOperands<'a> { + /// Explicit dependencies already resolved by their owning event machine. + pub(crate) barriers: &'a [M5SksmDependency], + /// Native convertEventMachineTSToHWTS(command) - 1, for first publication. + /// This must be grounded in the queue's initialized completion state. + pub(crate) first_predecessor: u64, + pub(crate) implicit_dependency_type: u8, + pub(crate) mcache: Option, + pub(crate) flag_bit1: bool, + pub(crate) flag_bit61: bool, + pub(crate) flag_bit63: bool, + pub(crate) payload: [u64; 2], + pub(crate) qos_byte_32: u8, + pub(crate) qos_class_40: u8, + pub(crate) qos_word_48: u16, + pub(crate) event_mask: [u64; 4], + pub(crate) rce_kind: u8, + pub(crate) rce: [M5SksmRce; 4], + /// Native encoder's scalar x5 argument, copied unmodified to +0x178. + pub(crate) auxiliary: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct PreparedM5SksmEntry { + pub(crate) bytes: [u8; M5_SKSM_ENTRY_BYTES], + pub(crate) offset: u32, + /// May only replace host state after entry storage and a dmb ish. + pub(crate) queue_after: M5SksmQueue, +} + +fn check_queue(id: u8, priority: u8, stamp: u64) -> Result<(), M5SksmError> { + if id > 0x7f { + return Err(M5SksmError::QueueId); + } + if priority > 3 { + return Err(M5SksmError::Priority); + } + if stamp & !STAMP_MASK != 0 { + return Err(M5SksmError::Stamp); + } + Ok(()) +} + +fn packed_address(address: u64) -> Result { + if address & 31 != 0 || address >> 5 > PACKED_ADDRESS_MASK { + return Err(M5SksmError::Address); + } + Ok(address >> 5) +} + +fn put(bytes: &mut [u8], offset: usize, value: u64) { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +/// Recovered from M5 encodeKickEntry at 25G76 0xfffffe00089e750c and its +/// encodeDependencyList at 0xfffffe00089e781c. Geometry is deliberately fixed +/// to the independently captured 256 x 512-byte M5 queues. +pub(crate) fn prepare_m5_sksm_entry( + queue: M5SksmQueue, + operands: M5SksmOperands<'_>, +) -> Result { + check_queue(queue.id, queue.priority, queue.current_stamp)?; + if queue.submitted >= M5_SKSM_ENTRY_COUNT { + return Err(M5SksmError::QueueFull); + } + // Native always appends one implicit predecessor after explicit barriers. + if operands.barriers.len() >= 32 { + return Err(M5SksmError::Dependencies); + } + if operands.qos_class_40 > 31 { + return Err(M5SksmError::Qos); + } + if operands.rce_kind > 3 || operands.rce.iter().any(|r| r.tag > 0x7f) { + return Err(M5SksmError::Rce); + } + let mut bytes = [0; M5_SKSM_ENTRY_BYTES]; + let mut header = (queue.current_stamp << 2) + | ((queue.id as u64) << 42) + | ((queue.priority as u64) << 59) + | ((operands.flag_bit1 as u64) << 1) + | ((operands.flag_bit61 as u64) << 61) + | ((operands.flag_bit63 as u64) << 63); + if let Some(mcache) = operands.mcache { + if mcache.index > 63 || mcache.count == 0 || mcache.count > 64 { + return Err(M5SksmError::Mcache); + } + let packed = packed_address(mcache.address)?; + put( + &mut bytes, + 8, + (mcache.index as u64) | (packed << 6) | ((mcache.count as u64 - 1) << 54), + ); + header |= 1 << 58; + } + put(&mut bytes, 0, header); + put(&mut bytes, 0x10, operands.payload[0]); + put(&mut bytes, 0x18, operands.payload[1]); + let predecessor = M5SksmDependency { + queue_id: queue.id, + stamp: queue.previous_stamp.unwrap_or(operands.first_predecessor), + kind: operands.implicit_dependency_type, + }; + let mut kinds = 0; + for (i, dependency) in operands + .barriers + .iter() + .chain(core::iter::once(&predecessor)) + .enumerate() + { + check_queue(dependency.queue_id, 0, dependency.stamp)?; + if dependency.kind > 3 { + return Err(M5SksmError::DependencyType); + } + put( + &mut bytes, + 0x28 + i * 8, + dependency.stamp | ((dependency.queue_id as u64) << 40), + ); + kinds |= (dependency.kind as u64) << (i * 2); + } + let count = operands.barriers.len() + 1; + let valid = if count == 32 { + u32::MAX + } else { + (1u32 << count) - 1 + }; + put( + &mut bytes, + 0x20, + valid as u64 + | ((operands.qos_byte_32 as u64) << 32) + | ((operands.qos_class_40 as u64) << 40) + | ((operands.qos_word_48 as u64) << 48), + ); + put(&mut bytes, 0x180, kinds); + for (i, mask) in operands.event_mask.into_iter().enumerate() { + put(&mut bytes, 0x128 + i * 8, mask); + } + bytes[0x148] = operands.rce_kind; + for (i, rce) in operands.rce.into_iter().enumerate() { + put( + &mut bytes, + 0x150 + i * 8, + packed_address(rce.address)? | ((rce.tag as u64) << 43), + ); + } + put(&mut bytes, 0x178, operands.auxiliary); + Ok(PreparedM5SksmEntry { + bytes, + offset: (queue.current_stamp as u32 & 255) * M5_SKSM_ENTRY_BYTES as u32, + queue_after: M5SksmQueue { + current_stamp: (queue.current_stamp + 1) & STAMP_MASK, + submitted: queue.submitted + 1, + previous_stamp: Some(queue.current_stamp), + ..queue + }, + }) +} + +/// Native CL add-kicks record at the captured submitBuffer publication site. +/// This is a packed 21-byte command, unrelated to the outer 24-byte entry. +pub(crate) fn encode_m5_sksm_add_kicks( + queue_id: u8, + priority: u8, + first_stamp: u64, + count: u16, +) -> Result<[u8; 21], M5SksmError> { + encode_m5_sksm_add_kicks_for( + M5DataMaster::Compute, + queue_id, + priority, + first_stamp, + count, + ) +} + +/// Encode a retained queue's stage explicitly; graphics never uses CL's DM2. +pub(crate) fn encode_m5_sksm_add_kicks_for( + data_master: M5DataMaster, + queue_id: u8, + priority: u8, + first_stamp: u64, + count: u16, +) -> Result<[u8; 21], M5SksmError> { + check_queue(queue_id, priority, first_stamp)?; + if count == 0 || count > 256 { + return Err(M5SksmError::AddCount); + } + let mut bytes = [0; 21]; + bytes[..4].copy_from_slice(&14u32.to_le_bytes()); + bytes[4..6].copy_from_slice(&(queue_id as u16).to_le_bytes()); + bytes[6..8].copy_from_slice(&count.to_le_bytes()); + bytes[8] = priority; + bytes[9..17].copy_from_slice(&first_stamp.to_le_bytes()); + bytes[17..21].copy_from_slice(&(data_master as u32).to_le_bytes()); + Ok(bytes) +} + diff --git a/drivers/gpu/drm/asahi/m5/submission.rs b/drivers/gpu/drm/asahi/m5/submission.rs new file mode 100644 index 0000000000000..c5414cea1ae2d --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/submission.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +fn put_u32_le(raw: &mut [u8], offset: usize, value: u32) { + raw[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u64_le(raw: &mut [u8], offset: usize, value: u64) { + raw[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +/// M5 G17G / macOS 25G76 resets six pairs of 128-bit vectors, covering 0xc0 +/// bytes. Its firmware consumes through +0xa7. The common 0x80-byte reset +/// would omit the moved fields and the firmware-visible tail. +pub(crate) const M5_25G76_CHANNEL_STATE_RESET_SIZE: usize = 0xc0; + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5ChannelStateResetValues { + pub(crate) uncached_state: u64, + pub(crate) command_pointer_ring: u64, + pub(crate) gpu_va_10: u64, + pub(crate) word_48: u32, + /// Opaque host field +0xf8 copied to the unaligned firmware field +0x9c. + pub(crate) gpu_va_9c: u64, +} + +/// Exact reset stores from M5 AGXChannel::resetChannelState at +/// 0xfffffe000897d36c..0xfffffe000897d410 (AGXG17G 353.14, 25G76). +/// Uncached stores are separately shared with apply_g17_uncached_channel_reset. +/// This codec alone does not admit M5 submission or a Linux GPU runtime. +pub(crate) fn encode_m5_25g76_channel_state_reset( + values: M5ChannelStateResetValues, +) -> [u8; M5_25G76_CHANNEL_STATE_RESET_SIZE] { + let mut raw = [0u8; M5_25G76_CHANNEL_STATE_RESET_SIZE]; + put_u64_le(&mut raw, 0x00, values.uncached_state); + put_u64_le(&mut raw, 0x08, values.command_pointer_ring); + put_u64_le(&mut raw, 0x10, values.gpu_va_10); + put_u32_le(&mut raw, 0x24, u32::MAX); + put_u32_le(&mut raw, 0x28, 4); + put_u32_le(&mut raw, 0x44, u32::MAX); + put_u32_le(&mut raw, 0x48, values.word_48); + put_u64_le(&mut raw, 0x9c, values.gpu_va_9c); + raw +} + +/// Logical render prefix, resolved at ioctl admission before asynchronous work. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] +pub(crate) struct G17PRenderOrder { + pub(crate) sequence: u64, + pub(crate) wait_through: Option, +} + diff --git a/drivers/gpu/drm/asahi/m5/vm_layout.rs b/drivers/gpu/drm/asahi/m5/vm_layout.rs new file mode 100644 index 0000000000000..19a6593736112 --- /dev/null +++ b/drivers/gpu/drm/asahi/m5/vm_layout.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Application VA contract shared with Mesa's agx_m5_va.h. + +use core::ops::Range; + +pub(crate) const DRIVER_BASE: u64 = 0x10_0000_0000; +pub(crate) const COMPACT_END: u64 = DRIVER_BASE + (1u64 << 32); +pub(crate) const DATA_START: u64 = 0x40_0000_0000; + +/// TA deflake fields encode an unsigned 32-bit offset from DRIVER_BASE. +/// Keep the private render arena inside that aperture and the USC backing +/// after it, within the same VM_CREATE reservation. A client may leave a +/// prefix of the compact aperture for its own command data. Mesa's default +/// reservation still begins at DRIVER_BASE and data begins at DATA_START. +pub(crate) fn compact_range(reserved: &Range) -> Option> { + if reserved.start < DRIVER_BASE || reserved.start >= COMPACT_END + || reserved.start & 0x3fff != 0 || reserved.end <= COMPACT_END + || reserved.end > DATA_START || reserved.end & 0x3fff != 0 { + return None; + } + Some(reserved.start..COMPACT_END) +} + +pub(crate) fn auxiliary_range(reserved: &Range) -> Option> { + compact_range(reserved)?; + Some(COMPACT_END..reserved.end) +} + +/// Command pointers must not reach driver-owned mappings, including when +/// the client leaves application data below its private arena reservation. +pub(crate) fn user_range_contains( + reserved: &Range, address: u64, size: u64, user_end: u64, +) -> bool { + let Some(end) = address.checked_add(size) else { return false; }; + size != 0 && address >= DRIVER_BASE && end <= user_end + && (end <= reserved.start || address >= reserved.end) +} + diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 5641384b51bfe..75c4d684b219f 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -209,7 +209,8 @@ struct drm_asahi_params_global { * * G13-G15 on 14.x report DRM_ASAHI_GPU_HAL_LEGACY. * The exact J613 25G83 runtime and the G17P runtime report - * DRM_ASAHI_GPU_HAL_200. + * DRM_ASAHI_GPU_HAL_200, the M5 (T8142) runtime + * DRM_ASAHI_GPU_HAL_300. */ __u32 gpu_hal_generation; @@ -241,7 +242,7 @@ enum drm_asahi_gpu_hal_generation { */ DRM_ASAHI_GPU_HAL_200 = 200, - /** @DRM_ASAHI_GPU_HAL_300: HAL300 command stream. Never reported by this kernel. */ + /** @DRM_ASAHI_GPU_HAL_300: HAL300 command stream, reported by the M5 (T8142) runtime. */ DRM_ASAHI_GPU_HAL_300 = 300, }; From f4dadb0fdbe066053bb441a761aa5c04b341fbbd Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 5 Nov 2026 20:12:36 +0100 Subject: [PATCH 7/7] drm/asahi: m5: Take the device binder and the queue's usage client integration/aurora added a bound-device owner to the platform driver data and a usage client to Gpu::new_queue. Create the owner in the M5 probe path like the other backends and accept the usage client on the M5 queue. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/driver.rs | 4 ++++ drivers/gpu/drm/asahi/m5/drm.rs | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 554a82285c865..003ec58b2f5da 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -464,6 +464,9 @@ impl AsahiPlatformDriver { let resources = regs::Resources::new(pdev)?; let res = regs::G17Resources::new(pdev)?; 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. + let binding = unsafe { crate::binding::Owner::new(pdev.as_ref(), &drm)? }; let gpu = crate::m5::probe(pdev, &drm, res)?; let data = try_pin_init!(AsahiDrmRegistrationData { gpu: gpu as Arc, @@ -473,6 +476,7 @@ impl AsahiPlatformDriver { // The M5 firmware session retains its firmware-visible state until reboot. let reg = unsafe { drm::Registration::new(pdev.as_ref(), drm, data, 0)? }; Ok(AsahiPlatformDriverData { + binding, _device: reg.device().into(), _reg: reg, g17: None, diff --git a/drivers/gpu/drm/asahi/m5/drm.rs b/drivers/gpu/drm/asahi/m5/drm.rs index a2a7b9d2679ac..981a8531b71a5 100644 --- a/drivers/gpu/drm/asahi/m5/drm.rs +++ b/drivers/gpu/drm/asahi/m5/drm.rs @@ -167,7 +167,8 @@ impl gpu::Gpu for M5DrmGpu { fn new_queue(&self, vm: mmu::Vm, _ualloc: Arc>, _ualloc_priv: Arc>, - priority: u32, usc_exec_base: u64) -> Result> { + priority: u32, usc_exec_base: u64, + _usage: Arc) -> Result> { if priority > 3 { return Err(EINVAL); } let window = command::QueueUscWindow { base: usc_exec_base, user_start: vm_layout::DRIVER_BASE, user_end: USER_END,