From 45b05cdbf811c6fdfee92bdb0b5aa85f2aba2ce2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 13:01:05 -0500 Subject: [PATCH 01/19] soc: apple: pmp: detect retained T8132 PMP bridge from the device tree Rename the retained-session predicate to apple_pmp_t8132_retained_board() and detect the retained T8132 PMP power-vote bridge from the device tree's own `pmp` node (`apple,t8132-pmp-v2`, available, `apple,tunable-soc-device` present) rather than gating on a board list, root SoC compatible, or OS firmware version string. Keep apple_pmp_j713_board() as an inline alias for existing callers. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/glue.c | 4 ++-- drivers/soc/apple/pmp-telemetry.c | 3 ++- drivers/soc/apple/pmp.rs | 4 ++-- include/linux/soc/apple/pmp-display.h | 21 ++++++++++++++++++--- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 368b56149acc7..5adb19bb3d820 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -200,10 +200,10 @@ int asahi_g16_tvm_enable(struct device *dev) return ret; } -/* Whether this is a qualified J713/T8132 board. */ +/* Whether this T8132 board's retained PMP carries the GPU's AGX vote. */ bool asahi_g16_board(void) { - return apple_pmp_j713_board(); + return apple_pmp_t8132_retained_board(); } /* diff --git a/drivers/soc/apple/pmp-telemetry.c b/drivers/soc/apple/pmp-telemetry.c index 529f9826e1635..9e39f1e63b474 100644 --- a/drivers/soc/apple/pmp-telemetry.c +++ b/drivers/soc/apple/pmp-telemetry.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -19,7 +20,7 @@ bool apple_pmp_telemetry_retained_board(void) { - return apple_t8132_firmware_path(); + return apple_pmp_t8132_retained_board(); } static LIST_HEAD(apple_pmp_telemetry_list); diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index afc8a973f7713..aab0cb7da8963 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -857,7 +857,7 @@ struct PmpHwConfig { enum Ep7 { /// Never started. No, - /// Only on the retained J713 board. + /// Only on T8132 boards with a retained, qualified PMP session. RetainedBoard, /// On every board with this SoC. Always, @@ -989,7 +989,7 @@ impl platform::Driver for PmpDriver { } data.patch_bootargs(&pmp_mmio, &patches, cfg.check_bootargs_uuid)?; // EP7 is a startup dependency on every T6041 PMP, and on the - // retained J713 PMP among the T8132 boards. + // retained, qualified PMP session among the T8132 boards. let needs_coreanalytics = match cfg.coreanalytics { Ep7::No => false, Ep7::Always => true, diff --git a/include/linux/soc/apple/pmp-display.h b/include/linux/soc/apple/pmp-display.h index e65effb337aa8..a532b1c25864e 100644 --- a/include/linux/soc/apple/pmp-display.h +++ b/include/linux/soc/apple/pmp-display.h @@ -3,13 +3,28 @@ #define _LINUX_SOC_APPLE_PMP_DISPLAY_H #include -#include #include -/* The retained M4 bridge and raw thermal records: the M4 firmware path. */ +/* + * Detect the retained T8132 PMP power-vote bridge from the device tree's own + * `pmp` node and tunable table property rather than a board list, SoC machine + * compatible, or OS firmware version string. + */ +static inline bool apple_pmp_t8132_retained_board(void) +{ + struct device_node *np = of_find_node_by_path("pmp"); + bool match = np && of_device_is_available(np) && + of_device_is_compatible(np, "apple,t8132-pmp-v2") && + of_property_present(np, "apple,tunable-soc-device"); + + of_node_put(np); + return match; +} + +/* The retained M4 bridge and raw thermal records. */ static inline bool apple_pmp_j713_board(void) { - return apple_t8132_firmware_path() && of_machine_is_compatible("apple,t8132"); + return apple_pmp_t8132_retained_board(); } struct device; From 9717482bed54a72ef74fae44d1816dbe54f3e19c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 13:01:06 -0500 Subject: [PATCH 02/19] drm/asahi: g16: admit J773g 25G83 images, derive DVFS table from ADT, and run to top p-state Admit the J773g 25G83 firmware images, including the boot-filled B000 ranges zeroed before digest verification, and cover them in fwid.rs unit tests. Derive the firmware DVFS table row count (10-row 6-pair vs 11-row 5-pair+top) directly from the preserved ADT performance-state table rather than gating on a board compatible, and let the utilization governor, cooling ceiling, and reported p-state bound run up to the board table's top state (S10 on 11-row tables). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/fwid.rs | 43 ++++++ drivers/gpu/drm/asahi/g16/board.rs | 19 ++- drivers/gpu/drm/asahi/g16/board/data.rs | 41 +++--- drivers/gpu/drm/asahi/g16/boot.rs | 17 ++- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 25 +++- drivers/gpu/drm/asahi/g16/hw.rs | 87 +++++++++++- drivers/gpu/drm/asahi/g16/initdata.rs | 18 ++- drivers/gpu/drm/asahi/g16/power.rs | 24 +++- drivers/gpu/drm/asahi/g16/power/policy.rs | 131 +++++++++++++----- .../drivers/gpu/asahi-m4/test-perf.py | 107 ++++++++++++-- 10 files changed, 419 insertions(+), 93 deletions(-) diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index f9525c0c08f30..62dc0452e7818 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -571,6 +571,49 @@ mod tests { assert!(measured(builds, 0x13c000, &[[0x5c8df, 0x5c9c2]], [0; 32]).is_none()); } + #[cfg(CONFIG_DRM_ASAHI_G16)] + #[test] + fn j773g_accepts_its_loaded_image() { + let builds = crate::g16::hw::t8132::CONFIG.firmware; + let digest = [ + 0x91, 0x54, 0xc7, 0xf8, 0x4b, 0xce, 0x32, 0x15, 0x1e, 0x8a, 0x97, 0x41, 0x7d, 0x6a, + 0x20, 0x7a, 0x9e, 0xaf, 0x03, 0x54, 0xb4, 0xb8, 0xd6, 0xf0, 0x2a, 0xf5, 0x29, 0x95, + 0x40, 0xd3, 0xe8, 0x5a, + ]; + let found = measured(builds, 0x13c000, &[[0x5c8df, 0x5c9c2]], digest).unwrap(); + assert_eq!(found.name, "Apple GFX 25G83 (normalized loaded image, J773g)"); + assert_eq!(found.boot_filled, &[(0x224, 4), (0x5c917, 8)]); + assert!(measured(builds, 0x138000, &[[0x5c8df, 0x5c9c2]], digest).is_none()); + } + + #[cfg(CONFIG_DRM_ASAHI_G16)] + #[test] + fn t8132_25g83_b000_zeroes_what_iboot_fills() { + let builds = crate::g16::hw::t8132::CONFIG.firmware; + let filled = crate::g16::hw::t8132::BOOT_FILLED_25G83_B000; + let build = builds.iter().find(|b| b.boot_filled == filled).unwrap(); + let [gkts, ecap] = build.entropy[0]; + // The header's per-boot word and DATA address, then one value per parameter record: + // each follows its 8-byte tag and length, back to back from the GKTS record. + assert_eq!(filled[..2], [(0x224, 4), (0x23c, 8)]); + let mut next = gkts; + for &(off, len) in &filled[2..filled.len() - 4] { + assert_eq!(off, next + 8); + next = off + len; + } + assert_eq!(next, 0x5c8df + 0x231); + assert!(filled.contains(&(gkts + 8, 8))); + assert!(filled.contains(&(ecap + 8, 8))); + // Then each tunable table's count byte and body, 0x350 bytes from its header. + for (i, table) in [next, next + 0x350].into_iter().enumerate() { + let at = filled.len() - 4 + 2 * i; + assert_eq!(filled[at..at + 2], [(table + 3, 1), (table + 4, 0x34c)]); + } + let found = measured(builds, 0x13c000, &[[gkts, ecap]], build.text_sha256).unwrap(); + assert!(core::ptr::eq(found, build)); + assert!(measured(builds, 0x138000, &[[gkts, ecap]], build.text_sha256).is_none()); + } + #[test] fn t6050_admits_only_its_pinned_image() { for cfg in [ diff --git a/drivers/gpu/drm/asahi/g16/board.rs b/drivers/gpu/drm/asahi/g16/board.rs index 9d005164e6de8..cdc4f27d19528 100644 --- a/drivers/gpu/drm/asahi/g16/board.rs +++ b/drivers/gpu/drm/asahi/g16/board.rs @@ -2,17 +2,20 @@ //! M4 board admission for the qualified firmware graph. //! -//! M4 uses ten firmware rows selected from sixteen source states, including off, and sixteen -//! voltage lanes. The source values belong to this machine's preserved original ADT. +//! M4 uses ten (J713, J604) or eleven (J773g) firmware rows selected from sixteen source +//! states, including off, and sixteen voltage lanes. The source values belong to this +//! machine's preserved original ADT. pub(crate) mod data; use super::adt::GpuAdt; -use super::fw::initdata::{Performance, PERF_STATES}; +use super::fw::initdata::Performance; use kernel::{device, prelude::*}; /// Admit the qualified table layout while preserving every machine-specific source value. -/// Differently shaped tables and inconsistent voltage pairs fail before publication. +/// The firmware DVFS row count is derived directly from the preserved ADT table shape rather +/// than from a board compatible check; differently shaped tables or inconsistent voltage pairs +/// fail before publication. pub(crate) fn qualify(dev: &device::Device, adt: &GpuAdt) -> Result { let (performance, layout) = data::select_named(&adt.performance).map_err(|error| { dev_err!( @@ -24,11 +27,13 @@ pub(crate) fn qualify(dev: &device::Device, adt: &GpuAdt) -> Result })?; dev_info!( dev, - "M4 ADT DVFS: 16 source states -> 10 firmware rows ({} layout), top {} MHz\n", + "M4 ADT DVFS: {} source states -> {} firmware rows ({} layout), top {} MHz\n", + adt.performance.count, + performance.count, layout, - performance.frequency[PERF_STATES - 1] + performance.frequency[performance.count - 1] ); - for i in 0..PERF_STATES { + for i in 0..performance.count { dev_info!( dev, "M4 ADT DVFS S{}: main={} MHz auxiliary={} MHz core={} mV SRAM={} mV\n", diff --git a/drivers/gpu/drm/asahi/g16/board/data.rs b/drivers/gpu/drm/asahi/g16/board/data.rs index 6d18386727a7f..fe5a7f2404a86 100644 --- a/drivers/gpu/drm/asahi/g16/board/data.rs +++ b/drivers/gpu/drm/asahi/g16/board/data.rs @@ -2,36 +2,40 @@ //! Qualified selections of the original ADT's sixteen performance states for 25G83. //! -//! The firmware takes ten rows, each a main and an auxiliary frequency at one voltage. Every -//! qualified layout maps the sixteen ADT states onto those rows by index; the values are always -//! this machine's own, never frequencies or voltages copied from a reference machine. +//! The firmware takes ten or eleven rows, each a main and an auxiliary frequency at one voltage. +//! Every qualified layout maps the sixteen ADT states onto those rows by index; the values are +//! always this machine's own, never frequencies or voltages copied from a reference machine. pub(crate) const SOURCE_STATES: usize = 16; -/// One qualified mapping of the ADT states onto the firmware rows. +/// One qualified mapping of the ADT states onto the first `rows` firmware rows. pub(crate) struct Layout { pub(crate) name: &'static str, + pub(crate) rows: usize, pub(crate) main: [usize; PERF_STATES], pub(crate) auxiliary: [usize; PERF_STATES], } /// Tried in order; a layout matches only when each row's two states share frequency, SRAM -/// frequency and both voltages, so the shapes below cannot be mistaken for each other. +/// frequency and both voltages. The 10-row (6 equal-voltage pairs) and 11-row (5 equal-voltage +/// pairs plus a single top state) ADT shapes are mutually exclusive, so the row count is +/// derived directly from the ADT table without any board check. pub(crate) const LAYOUTS: [Layout; 2] = [ - // J713: four common low states followed by six equal-voltage pairs. + // 10-row ADT shape (e.g. J713/J715): four common low states followed by six equal-voltage + // pairs (4/5 through 14/15). Layout { - name: "J713", - main: [0, 1, 2, 3, 5, 7, 9, 11, 13, 15], - auxiliary: [0, 1, 2, 3, 4, 6, 8, 10, 12, 14], + name: "10-row", + rows: 10, + main: [0, 1, 2, 3, 5, 7, 9, 11, 13, 15, 0], + auxiliary: [0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 0], }, - // J604 (MacBook Pro 14-inch, M4): five low states, five equal-voltage pairs (5/6 to - // 13/14) and a single top state 15. Eleven distinct rows do not fit in ten, so the fifth - // low state (4) is left out; the four lowest states, every pair and the top state keep - // their own ADT values. + // 11-row ADT shape (e.g. J604/J773g): five low states, five equal-voltage pairs (5/6 + // through 13/14) and a single top state 15, with every distinct state kept. Layout { - name: "J604", - main: [0, 1, 2, 3, 6, 8, 10, 12, 14, 15], - auxiliary: [0, 1, 2, 3, 5, 7, 9, 11, 13, 15], + name: "11-row", + rows: 11, + main: [0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 15], + auxiliary: [0, 1, 2, 3, 4, 5, 7, 9, 11, 13, 15], }, ]; @@ -44,7 +48,7 @@ pub(crate) fn select( select_named(source).map(|(performance, _)| performance) } -/// As [`select`], with the name of the layout that matched. +/// As [`select`], with the name of the ADT shape that matched. pub(crate) fn select_named( source: &super::super::adt::perf::Source, ) -> core::result::Result<(Performance, &'static str), super::super::adt::perf::Error> { @@ -68,12 +72,13 @@ fn select_layout( ) -> core::result::Result { use super::super::adt::perf::Error; let mut performance = Performance { + count: layout.rows, frequency: [0; PERF_STATES], auxiliary: [0; PERF_STATES], voltage: [0; PERF_STATES], sram: [0; PERF_STATES], }; - for i in 0..PERF_STATES { + for i in 0..layout.rows { let (main, aux) = (layout.main[i], layout.auxiliary[i]); if source.frequency_mhz[main] != source.sram_frequency_mhz[main] || source.frequency_mhz[aux] != source.sram_frequency_mhz[aux] diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index f7f2cb25c56ea..91de8189abd8a 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -43,6 +43,7 @@ pub(crate) mod glue { extern "C" { fn asahi_g16_board() -> bool; fn asahi_g16_display_prepare(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_g16_perf_rows() -> core::ffi::c_uint; fn asahi_g16_hold_power(dev: *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_g16_ram_disjoint(start: u64, size: u64) -> bool; fn asahi_g16_ioremap_wc(start: u64, size: usize) -> *mut core::ffi::c_void; @@ -60,7 +61,7 @@ pub(crate) mod glue { ) -> core::ffi::c_int; } - /// A qualified J713/T8132 board. + /// A qualified T8132 board (J713, J773g). pub(crate) fn board() -> bool { // SAFETY: Reads the machine compatible strings only. unsafe { asahi_g16_board() } @@ -72,6 +73,12 @@ pub(crate) mod glue { kernel::error::to_result(unsafe { asahi_g16_display_prepare(dev.as_raw().cast()) }) } + /// The firmware DVFS row count qualified for this board, or zero. + pub(crate) fn perf_rows() -> usize { + // SAFETY: Reads the machine compatible strings only. + unsafe { asahi_g16_perf_rows() as usize } + } + /// Holds the GFX power domain for the retained session. pub(crate) fn hold_power(dev: &device::Device) -> Result { // SAFETY: `dev` is a valid device; runtime-PM accounting on it has no other requirement. @@ -409,7 +416,7 @@ impl Session { self.shared.check()?; if !self.rtkit.running() || self.regs.asc_control()? & regs::ASC_RUN == 0 - || self.regs.pstate()? > 9 + || self.regs.pstate()? > self.regs.top() { return Err(EIO); } @@ -730,7 +737,7 @@ pub(crate) fn start( "M4 G16G: {} cores enabled\n", id.core_masks[0].count_ones() ); - if regs.pstate()? > 9 { + if regs.pstate()? > regs.top() { return Err(eproto()); } // Cold only: ASC RUN clear and an all-zero TTBAT before ownership. @@ -779,6 +786,10 @@ pub(crate) fn start( events.reserve()?; // Every host object and every context-0 alias is prepared before RUN is set. built = Some(initdata::build(&d, &session.adt, &mut objects)?); + if let Some((init, _, _)) = built.as_ref() { + // The running firmware may report any state of the board's table, up to S10 on J773g. + session.regs.set_table(init.rows); + } objects.window.lock().bootstrap(&d, &session.uat)?; uat::tlbi_all(); if session.regs.asc_control()? & regs::ASC_RUN != 0 { diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 9acbb4ac763a5..0083f5cad939e 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -324,12 +324,15 @@ pub(crate) fn loader_encode(slot: usize, va: u64, record: &mut [u8]) -> Result<( put64(out, 0x20, u64::from(e.mode)) } -pub(crate) const PERF_STATES: usize = 10; +/// Capacity for the largest qualified table: J713 has ten rows, J773g eleven. +pub(crate) const PERF_STATES: usize = 11; /// Machine-specific values selected from the original ADT before firmware publication. /// Frequencies are exact MHz, voltages are millivolts. No reference-bin defaults exist. +/// Only the first `count` rows are used; the rest are zero. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Performance { + pub(crate) count: usize, pub(crate) frequency: [u32; PERF_STATES], pub(crate) auxiliary: [u32; PERF_STATES], pub(crate) voltage: [u32; PERF_STATES], @@ -338,7 +341,19 @@ pub(crate) struct Performance { impl Performance { pub(crate) fn valid(&self) -> bool { - for i in 0..PERF_STATES { + if !(2..=PERF_STATES).contains(&self.count) { + return false; + } + for i in self.count..PERF_STATES { + if self.frequency[i] != 0 + || self.auxiliary[i] != 0 + || self.voltage[i] != 0 + || self.sram[i] != 0 + { + return false; + } + } + for i in 0..self.count { if self.frequency[i] > 3000 || self.auxiliary[i] > self.frequency[i] || ((i == 0) != (self.frequency[i] == 0)) @@ -445,8 +460,8 @@ pub(crate) fn encode( input: &Input, ceiling: u32, ) -> Result<(), ()> { - if !(1..=9).contains(&ceiling) - || !input.performance.valid() + if !input.performance.valid() + || !(1..input.performance.count as u32).contains(&ceiling) || !object_va(input.scratch, 0x8000) || !bootstrap_alias(input.lower_uma) || !bootstrap_alias(input.lower_parameter) @@ -542,7 +557,7 @@ pub(crate) fn encode( (0xed0, 24000), (0xed4, 1), (0xed8, 8), - (0xfc0, 10), + (0xfc0, input.performance.count as u32), (0x259c, 1), (0x2544, 4), (0x2548, 6), diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 353199dea75a1..a55d7c9bd0308 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -20,7 +20,7 @@ pub(crate) struct HwId { pub(crate) use crate::fwid::FirmwareBuild; -/// The J713/T8132 configuration. Hardware admission also checks the exact TEXT image. +/// The J713/J773g T8132 configuration. Hardware admission also checks the exact TEXT image. pub(crate) mod t8132 { use super::super::Config; use super::{FirmwareBuild, HwId}; @@ -79,8 +79,93 @@ pub(crate) mod t8132 { 0xc8, 0x29, 0x86, 0x8b, 0xc9, 0xcf, ], }, + FirmwareBuild { + // The 25G83 image as loaded by iBoot on a J773g (Mac mini). iBoot rewrites + // the header word at 0x224 and the 8-byte DILS payload at 0x5c917 on every + // boot there; they are zeroed before hashing. + name: "Apple GFX 25G83 (normalized loaded image, J773g)", + text_size: 0x60000, + data_size: 0x13c000, + entropy: &[[0x5c8df, 0x5c9c2]], + boot_filled: &[(0x224, 4), (0x5c917, 8)], + text_sha256: [ + 0x91, 0x54, 0xc7, 0xf8, 0x4b, 0xce, 0x32, 0x15, 0x1e, 0x8a, 0x97, 0x41, 0x7d, + 0x6a, 0x20, 0x7a, 0x9e, 0xaf, 0x03, 0x54, 0xb4, 0xb8, 0xd6, 0xf0, 0x2a, 0xf5, + 0x29, 0x95, 0x40, 0xd3, 0xe8, 0x5a, + ], + }, + FirmwareBuild { + // Build b000 (G16G B0) of armfw_g16g.im4p in 25G83, as iBoot loads it on any + // machine: the boot-filled ranges below are zeroed, which gives the digest of + // the shipped image with the same ranges zeroed. + name: "Apple GFX 25G83 (build b000, iBoot-filled ranges zeroed)", + text_size: 0x60000, + data_size: 0x13c000, + entropy: &[[0x5c8df, 0x5c9c2]], + boot_filled: BOOT_FILLED_25G83_B000, + text_sha256: [ + 0xb9, 0xea, 0x7e, 0x6b, 0x2a, 0xca, 0x70, 0xa2, 0x75, 0xa0, 0xb0, 0x68, 0xee, + 0x79, 0x1e, 0xd5, 0x05, 0x27, 0xe8, 0xdb, 0x76, 0x19, 0x64, 0xd2, 0x73, 0x3f, + 0xa4, 0x07, 0xa6, 0xf2, 0x22, 0x6c, + ], + }, ], }; + + /// What iBoot writes into the 25G83 build b000 TEXT it loads, in TEXT order: + /// - the header word at 0x224, which changes from boot to boot, and the DATA address at 0x23c; + /// - the value of each of the 39 boot parameter records the header at 0x22c places from + /// 0x5c8df to 0x5cb10 (a tag, a 32-bit length and the value: carveout addresses below the + /// top of DRAM, a per-boot slide, the entropy); + /// - the entry count and the 0x34c-byte body of the two tunable tables at 0x5cb10 and 0x5ce60 + /// (headers 01/03 03 2a), which the shipped image leaves empty. + pub(crate) const BOOT_FILLED_25G83_B000: &[(u32, u32)] = &[ + (0x224, 4), + (0x23c, 8), + (0x5c8e7, 8), + (0x5c8f7, 8), + (0x5c907, 8), + (0x5c917, 8), + (0x5c927, 8), + (0x5c937, 8), + (0x5c947, 8), + (0x5c957, 4), + (0x5c963, 1), + (0x5c96c, 8), + (0x5c97c, 8), + (0x5c98c, 4), + (0x5c998, 8), + (0x5c9a8, 1), + (0x5c9b1, 1), + (0x5c9ba, 8), + (0x5c9ca, 8), + (0x5c9da, 8), + (0x5c9ea, 8), + (0x5c9fa, 8), + (0x5ca0a, 8), + (0x5ca1a, 8), + (0x5ca2a, 8), + (0x5ca3a, 8), + (0x5ca4a, 8), + (0x5ca5a, 8), + (0x5ca6a, 8), + (0x5ca7a, 4), + (0x5ca86, 8), + (0x5ca96, 4), + (0x5caa2, 4), + (0x5caae, 8), + (0x5cabe, 8), + (0x5cace, 1), + (0x5cad7, 8), + (0x5cae7, 8), + (0x5caf7, 4), + (0x5cb03, 1), + (0x5cb0c, 4), + (0x5cb13, 1), + (0x5cb14, 0x34c), + (0x5ce63, 1), + (0x5ce64, 0x34c), + ]; } /// User VA range reported as `vm_start..vm_end`: 42 bits with the final two pages excluded. diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index ecdde0579133a..f022689ad0878 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -38,6 +38,8 @@ pub(crate) struct InitData { #[allow(dead_code)] pub(crate) parameter: Arc, root: Arc, + /// Rows of the board's firmware performance table, including off. + pub(crate) rows: u32, loader: [u8; wire::LOADER_BYTES], /// The complete inventory, including firmware-only log and retention data. _graph: KVec>, @@ -83,7 +85,10 @@ pub(crate) fn build( objects: &mut Objects, ) -> Result<(InitData, Channels, u32)> { let performance = board::qualify(dev, adt)?; - let max_khz = performance.frequency[wire::PERF_STATES - 1] * 1000; + // The top row: S9 on J713, S10 on J773g. + let ceiling = performance.count as u32 - 1; + let rows = performance.count as u32; + let max_khz = performance.frequency[ceiling as usize] * 1000; let mut graph = KVec::with_capacity(wire::OBJECT_COUNT, GFP_KERNEL)?; for (i, size) in wire::OBJECT_SIZE.iter().copied().enumerate() { let lower = match i { @@ -184,11 +189,11 @@ pub(crate) fn build( } let array: &mut [&mut [u8]; wire::OBJECT_COUNT] = (&mut slices[..]).try_into().map_err(|_| EINVAL)?; - wire::encode(array, &input, 9).map_err(|()| EINVAL)?; + wire::encode(array, &input, ceiling).map_err(|()| EINVAL)?; } let mut loader = [0u8; wire::LOADER_BYTES]; loader.copy_from_slice(&images[id::MAIN][0x640..0x640 + wire::LOADER_BYTES]); - // Host startup policy: Main and PowerPerformance contain S9, but the + // Host startup policy: Main and PowerPerformance contain the top row, but the // published selectors remain S1 until the thermal owner admits a raise. for at in globals::PSTATE_SELECTORS { images[id::GLOBALS][at..at + 4].copy_from_slice(&100u32.to_le_bytes()); @@ -197,7 +202,11 @@ pub(crate) fn build( graph[i].write(0, &images[i])?; } - dev_info!(dev, "M4 initdata: 31 objects, 12 submit channel pairs, 42 loader records, S1 startup (S9 tables)\n"); + dev_info!( + dev, + "M4 initdata: 31 objects, 12 submit channel pairs, 42 loader records, S1 startup (S{} tables)\n", + ceiling + ); Ok(( InitData { globals: Some(graph[id::GLOBALS].clone()), @@ -213,6 +222,7 @@ pub(crate) fn build( uma: graph[id::UMA].clone(), parameter: graph[id::PARAMETER].clone(), root: graph[id::ROOT].clone(), + rows, loader, _graph: graph, }, diff --git a/drivers/gpu/drm/asahi/g16/power.rs b/drivers/gpu/drm/asahi/g16/power.rs index 5e3346e3cf1e2..ae07876b3b45b 100644 --- a/drivers/gpu/drm/asahi/g16/power.rs +++ b/drivers/gpu/drm/asahi/g16/power.rs @@ -24,7 +24,7 @@ use super::fw::initdata::globals; use super::recovery::now_ns; use super::regs::wmb; use super::Firmware; -use policy::{COOLING_MAX, PSTATE_MAX}; +use policy::{COOLING_MAX, TOP_DEFAULT}; static_assert!(globals::PSTATE_SELECTORS[0] == 0x88); static_assert!(globals::PSTATE_SELECTORS[1] == 0x8c); @@ -155,6 +155,8 @@ pub(crate) struct Power { cooling: Cooling, sample: Sample, last_sample_ns: Option, + /// The board's top state: S9 on the ten-row tables, S10 on the J773g table. + pub(crate) top: u32, pub(crate) configured: u32, pub(crate) user: u32, pub(crate) effective: u32, @@ -170,7 +172,7 @@ pub(crate) struct Power { } impl Power { - /// The Main image initializes all nine active states. Initdata publishes + /// The Main image initializes every active state of the board's table. Initdata publishes /// startup S1 before INIT; this object starts with that same effective state. pub(crate) fn new(dev: &device::Device) -> Result { Ok(Self { @@ -185,8 +187,9 @@ impl Power { backstop: COOLING_MAX, }, last_sample_ns: None, - configured: PSTATE_MAX, - user: PSTATE_MAX, + top: TOP_DEFAULT, + configured: TOP_DEFAULT, + user: TOP_DEFAULT, effective: 1, temperature_mc: 0, governor: COOLING_MAX, @@ -200,6 +203,17 @@ impl Power { }) } + /// Adopts the board's firmware table, `rows` rows including off, before the first + /// governed publication: its top row is the governor's top state and configured + /// ceiling. The J773g table has eleven rows, so its top state is S10. + pub(crate) fn set_table(&mut self, rows: u32) { + let top = policy::top_of(rows); + self.top = top; + self.configured = top; + self.user = top; + self.utilization.top = top; + } + /// Reports a change of work in flight to the CLPC: the memory and fabric /// floor follows it, not the GFX power state. pub(crate) fn report_work(&mut self, in_flight: bool) { @@ -221,7 +235,7 @@ impl Power { self.budget = self.sample.budget; } let level = self.governor.max(self.budget).max(self.sample.backstop); - let ceiling = PSTATE_MAX - level.min(COOLING_MAX); + let ceiling = policy::cooling_ceiling(self.top, level); let limit = policy::limit(self.configured, ceiling, self.user); let decision = ( limit, diff --git a/drivers/gpu/drm/asahi/g16/power/policy.rs b/drivers/gpu/drm/asahi/g16/power/policy.rs index 0d127b8a5f817..d1d34b6245f52 100644 --- a/drivers/gpu/drm/asahi/g16/power/policy.rs +++ b/drivers/gpu/drm/asahi/g16/power/policy.rs @@ -6,7 +6,11 @@ //! Temperature decoding and regulation belong to the PMP provider and the //! shared C cooling policy. This module defines no temperature thresholds. -pub(crate) const PSTATE_MAX: u32 = 9; +/// Highest selector any M4 table can have: S9 on the ten-row J713/J604 tables, S10 on the +/// eleven-row J773g table. The board's own top state (`top`) bounds every request. +pub(crate) const PSTATE_MAX: u32 = 10; +/// Top state of the ten-row tables, used until the board's table is known. +pub(crate) const TOP_DEFAULT: u32 = 9; pub(crate) const COOLING_MAX: u32 = 8; pub(crate) const SAMPLE_NS: u64 = 5_000_000; /// Utilization window of the governor. @@ -21,11 +25,26 @@ pub(crate) fn read_due(last: Option, now: u64) -> bool { } /// Zero is not an unlimited selector in the firmware. Every published state -/// is 1..=9, bounded by the initialized Main table and the user ceiling. +/// is 1..=top, bounded by the initialized Main table and the user ceiling. pub(crate) fn limit(configured: u32, ceiling: u32, user: u32) -> u32 { ceiling.min(PSTATE_MAX).min(configured).min(user).max(1) } +/// The board's top state, from its firmware table's row count (row 0 is off). +pub(crate) fn top_of(rows: u32) -> u32 { + rows.saturating_sub(1).clamp(FLOOR, PSTATE_MAX) +} + +/// The cooling ceiling for a cooling `level` (0..=COOLING_MAX) under the board's `top` +/// state: one state per level below the top, and S1 at full cooling on every table. +pub(crate) fn cooling_ceiling(top: u32, level: u32) -> u32 { + if level >= COOLING_MAX { + 1 + } else { + top.saturating_sub(level).max(1) + } +} + /// Percentage of `window` ns the GPU was busy for. pub(crate) fn utilization(busy: u64, window: u64) -> u32 { if window == 0 { @@ -53,9 +72,10 @@ pub(crate) fn smooth(average: u32, util: u32, window: u64) -> u32 { /// The state to request from the `current` published one: up on the last /// window's utilization `util`, to the top state under heavy load, and down /// on the smoothed `average`, to the floor when idle. -pub(crate) fn demand(current: u32, util: u32, average: u32) -> u32 { +pub(crate) fn demand(current: u32, util: u32, average: u32, top: u32) -> u32 { + let top = top.clamp(FLOOR, PSTATE_MAX); let next = if util >= 70 { - PSTATE_MAX + top } else if util >= 40 { current.saturating_add(1) } else if average < 10 { @@ -65,7 +85,7 @@ pub(crate) fn demand(current: u32, util: u32, average: u32) -> u32 { } else { current }; - next.clamp(FLOOR, PSTATE_MAX) + next.clamp(FLOOR, top) } /// Busy-time accounting over the governor's windows. The engine reports each @@ -74,6 +94,8 @@ pub(crate) struct Governor { /// The requested state and the smoothed utilization. pub(crate) demand: u32, pub(crate) average: u32, + /// The board's top state. + pub(crate) top: u32, window_ns: u64, busy_since: Option, busy_ns: u64, @@ -84,6 +106,7 @@ impl Governor { Self { demand: FLOOR, average: 0, + top: TOP_DEFAULT, window_ns: 0, busy_since: None, busy_ns: 0, @@ -123,7 +146,7 @@ impl Governor { } let util = utilization(self.busy_ns, window); self.average = smooth(self.average, util, window); - self.demand = demand(self.demand.min(limit), util, self.average); + self.demand = demand(self.demand.min(limit), util, self.average, self.top); self.window_ns = now; self.busy_ns = 0; } @@ -135,6 +158,9 @@ impl Governor { mod tests { use super::*; + /// The ten-row tables' top state; the J773g cases name theirs. + const TOP: u32 = TOP_DEFAULT; + #[test] fn provider_sampling_is_independent_of_completion_polling() { assert!(read_due(None, 0)); @@ -146,7 +172,7 @@ mod tests { #[test] fn initialized_selectors_and_user_caps_bound_every_request() { - assert_eq!(COOLING_MAX, PSTATE_MAX - 1); + assert_eq!(COOLING_MAX, TOP_DEFAULT - 1); for configured in [0, 1, 7, 9, 10, u32::MAX] { for ceiling in [0, 1, 5, 9, 10, u32::MAX] { for user in [0, 1, 3, 9, 10, u32::MAX] { @@ -180,7 +206,7 @@ mod tests { assert_eq!(smooth(u32::MAX, u32::MAX, w), 100); let mut average = 100; let mut windows = 0; - while demand(PSTATE_MAX, 0, average) != FLOOR { + while demand(TOP, 0, average, TOP) != FLOOR { average = smooth(average, 0, w); windows += 1; } @@ -189,23 +215,23 @@ mod tests { #[test] fn demand_rises_fast_and_falls_on_the_average() { - assert_eq!(demand(FLOOR, 100, 0), PSTATE_MAX); - assert_eq!(demand(FLOOR, 70, 0), PSTATE_MAX); - assert_eq!(demand(4, 50, 0), 5); - assert_eq!(demand(PSTATE_MAX, 50, 0), PSTATE_MAX); + assert_eq!(demand(FLOOR, 100, 0, TOP), TOP); + assert_eq!(demand(FLOOR, 70, 0, TOP), TOP); + assert_eq!(demand(4, 50, 0, TOP), 5); + assert_eq!(demand(TOP, 50, 0, TOP), TOP); // A short dip under a busy average holds the state. - assert_eq!(demand(PSTATE_MAX, 5, 80), PSTATE_MAX); - assert_eq!(demand(6, 30, 30), 6); - assert_eq!(demand(6, 20, 20), 5); - assert_eq!(demand(PSTATE_MAX, 0, 5), FLOOR); + assert_eq!(demand(TOP, 5, 80, TOP), TOP); + assert_eq!(demand(6, 30, 30, TOP), 6); + assert_eq!(demand(6, 20, 20, TOP), 5); + assert_eq!(demand(TOP, 0, 5, TOP), FLOOR); // A light 60 fps load near 25% busy settles on the floor. - assert_eq!(demand(FLOOR, 25, 24), FLOOR); - assert_eq!(demand(1, 30, 30), FLOOR); - for current in [0, 1, FLOOR, 7, PSTATE_MAX, u32::MAX] { + assert_eq!(demand(FLOOR, 25, 24, TOP), FLOOR); + assert_eq!(demand(1, 30, 30, TOP), FLOOR); + for current in [0, 1, FLOOR, 7, TOP, u32::MAX] { for util in [0, 20, 50, 70, 100, u32::MAX] { for average in [0, 9, 20, 30, 100, u32::MAX] { - let next = demand(current, util, average); - assert!((FLOOR..=PSTATE_MAX).contains(&next)); + let next = demand(current, util, average, TOP); + assert!((FLOOR..=TOP).contains(&next)); } } } @@ -216,7 +242,7 @@ mod tests { /// A governor whose first window closed idle at `T`. fn started() -> Governor { let mut governor = Governor::new(); - assert_eq!(governor.govern(T, PSTATE_MAX, false), FLOOR); + assert_eq!(governor.govern(T, TOP, false), FLOOR); assert_eq!(governor.average, 0); governor } @@ -232,10 +258,10 @@ mod tests { // A drain without a publication adds nothing. g.idle(T + 9_000_000); // A service before the window is due changes nothing. - assert_eq!(g.govern(T + w - 1, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + w - 1, TOP, false), FLOOR); assert_eq!(g.average, 0); // 5 ms of 20 ms: 25%, a quarter of it in the average. - assert_eq!(g.govern(T + w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + w, TOP, false), FLOOR); assert_eq!(g.average, 6); } @@ -246,13 +272,13 @@ mod tests { g.busy(T); assert!(!g.decaying()); // Busy through the window: all of it counts, and the load gets the top state. - assert_eq!(g.govern(T + w, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + w, TOP, true), TOP); assert_eq!(g.average, 25); // Busy above the floor: the engine's own polls govern it, not the idle re-arm. assert!(!g.decaying()); // The span carries on from the window's end, not from its publication. g.idle(T + w + w / 2); - assert_eq!(g.govern(T + 2 * w, PSTATE_MAX, false), PSTATE_MAX); + assert_eq!(g.govern(T + 2 * w, TOP, false), TOP); assert_eq!(g.average, (3 * 25 + 50) / 4); } @@ -263,15 +289,15 @@ mod tests { g.busy(T); // Recovery dropped the flights and reported no drain: the next service, // finding none outstanding, ends the span there. - assert_eq!(g.govern(T + w / 2, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + w / 2, TOP, false), FLOOR); assert!(!g.decaying()); - assert_eq!(g.govern(T + w, PSTATE_MAX, false), FLOOR + 1); + assert_eq!(g.govern(T + w, TOP, false), FLOOR + 1); assert_eq!(g.average, 50 / 4); // Idle above the floor: the poll keeps coming back. assert!(g.decaying()); // A late drain report counts nothing more. g.idle(T + w + 1); - assert_eq!(g.govern(T + 2 * w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + 2 * w, TOP, false), FLOOR); assert!(!g.decaying()); } @@ -281,7 +307,7 @@ mod tests { let mut g = started(); g.busy(T); for n in 1..=8 { - assert_eq!(g.govern(T + n * w, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + n * w, TOP, true), TOP); } let mut now = T + 8 * w; g.idle(now); @@ -289,21 +315,21 @@ mod tests { let mut passes = 0; while g.decaying() { now += w; - g.govern(now, PSTATE_MAX, false); + g.govern(now, TOP, false); passes += 1; assert!(passes <= 10); } assert_eq!(g.demand, FLOOR); assert!(passes > 1); // At the floor nothing re-arms, and a later service holds it there. - assert_eq!(g.govern(now + 10 * w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(now + 10 * w, TOP, false), FLOOR); assert!(!g.decaying()); // A long sleep between passes restarts the average and drops at once. let mut g = started(); g.busy(T); - assert_eq!(g.govern(T + w, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + w, TOP, true), TOP); g.idle(T + w); - assert_eq!(g.govern(T + 6 * w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + 6 * w, TOP, false), FLOOR); assert!(!g.decaying()); } @@ -318,7 +344,7 @@ mod tests { assert_eq!(g.govern(T + 2 * w, 1, true), 1); assert_eq!(g.govern(T + 2 * w + 1, 2, true), 2); // Released, the load's request applies at once. - assert_eq!(g.govern(T + 2 * w + 2, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + 2 * w + 2, TOP, true), TOP); // Idle under a ceiling below the floor: one window gives it all back. g.idle(T + 3 * w); assert!(g.decaying()); @@ -326,4 +352,39 @@ mod tests { assert_eq!(g.demand, FLOOR); assert!(!g.decaying()); } + + #[test] + fn the_board_table_sets_the_top_state() { + // J713/J604: ten rows, top S9. J773g: eleven rows, top S10 (1578 MHz on the Mac mini). + assert_eq!(top_of(10), 9); + assert_eq!(top_of(11), 10); + assert_eq!(top_of(12), PSTATE_MAX); + assert_eq!(top_of(0), FLOOR); + for top in [9, 10] { + assert_eq!(demand(FLOOR, 100, 0, top), top); + assert_eq!(demand(top, 50, 80, top), top); + assert_eq!(demand(top, 0, 5, top), FLOOR); + let mut g = Governor::new(); + g.top = top; + assert_eq!(g.govern(T, top, false), FLOOR); + g.busy(T); + assert_eq!(g.govern(T + WINDOW_NS, top, true), top); + // A ceiling still bounds the request. + assert_eq!(g.govern(T + 2 * WINDOW_NS, top - 1, true), top - 1); + } + } + + #[test] + fn cooling_keeps_one_state_per_level_and_s1_at_full_cooling() { + // Ten-row tables: unchanged, 9 - level, S1 at level 8. + for level in 0..=COOLING_MAX { + assert_eq!(cooling_ceiling(9, level), 9 - level); + } + // Eleven rows: S10..S3 for levels 0..7, S1 at full cooling. + assert_eq!(cooling_ceiling(10, 0), 10); + assert_eq!(cooling_ceiling(10, 7), 3); + assert_eq!(cooling_ceiling(10, COOLING_MAX), 1); + assert_eq!(cooling_ceiling(10, u32::MAX), 1); + assert_eq!(limit(10, cooling_ceiling(10, 0), 10), 10); + } } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py index 36574512d4298..0daa8ffdcd8d8 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py @@ -66,11 +66,74 @@ def node(props, children=()): fn get32(bytes: &[u8], at: usize) -> u32 { u32::from_le_bytes(bytes[at..at+4].try_into().unwrap()) } #[test] fn measured_original_adt_produces_qualified_tables() { let s=source(); assert_eq!(s.count,16); - let p=tables(); - assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470]); - assert_eq!(p.auxiliary,[0,338,618,796,836,952,1053,1152,1204,1326]); - assert_eq!(p.voltage,[125,610,645,680,725,780,825,865,895,970]); - assert_eq!(p.sram,[780,780,780,780,780,780,825,865,895,970]); + // Keep the original frequency layout but use synthetic voltage bins. + let mut s=s; + s.core_mv[..16].copy_from_slice(&[100,600,650,700,750,750,800,800,850,850,900,900,950,950,1000,1000]); + s.sram_mv[..16].copy_from_slice(&[800,800,800,800,800,800,800,800,850,850,900,900,950,950,1000,1000]); + let p=data::select(&s).unwrap(); assert_eq!(p.count,10); + assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,0]); + assert_eq!(p.auxiliary,[0,338,618,796,836,952,1053,1152,1204,1326,0]); + assert_eq!(p.voltage,[100,600,650,700,750,800,850,900,950,1000,0]); + assert_eq!(p.sram,[800,800,800,800,800,800,850,900,950,1000,0]); + assert_eq!(get32(&encode(p).unwrap()[wire::id::MAIN],0xfc0),10); +} +// J773g frequency layout with synthetic voltage bins, both with eleven groups. +fn j773g(core: [u32; 16], sram: [u32; 16]) -> perf::Source { + let mhz=[0,338,618,796,928,952,1056,1053,1170,1152,1278,1204,1338,1326,1470,1578]; + let mut s=source(); s.count=16; + s.frequency_mhz=[0;perf::MAX_STATES]; s.sram_frequency_mhz=[0;perf::MAX_STATES]; + s.core_mv=[0;perf::MAX_STATES]; s.sram_mv=[0;perf::MAX_STATES]; + s.frequency_mhz[..16].copy_from_slice(&mhz); s.sram_frequency_mhz[..16].copy_from_slice(&mhz); + s.core_mv[..16].copy_from_slice(&core); s.sram_mv[..16].copy_from_slice(&sram); + s +} +#[test] fn j773g_synthetic_bins_produce_eleven_rows_and_encode_all_of_them() { + for (core,sram,voltage,row_sram) in [ + ([100,600,620,660,700,750,750,800,800,850,850,900,900,950,950,1000], + [740,740,740,740,740,750,750,800,800,850,850,900,900,950,950,1000], + [100,600,620,660,700,750,800,850,900,950,1000], + [740,740,740,740,740,750,800,850,900,950,1000]), + ([100,590,630,650,690,730,730,790,790,840,840,890,890,940,940,990], + [760,760,760,760,760,760,760,790,790,840,840,890,890,940,940,990], + [100,590,630,650,690,730,790,840,890,940,990], + [760,760,760,760,760,760,790,840,890,940,990]), + ] { + let (p,name)=data::select_named(&j773g(core,sram),Some(11)).unwrap(); + assert_eq!(name,"J773g"); assert_eq!(p.count,11); + assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,1578]); + assert_eq!(p.auxiliary,[0,338,618,796,928,952,1053,1152,1204,1326,1578]); + assert_eq!(p.voltage,voltage); assert_eq!(p.sram,row_sram); + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),10).unwrap(); + let main=&buffers[wire::id::MAIN]; + assert_eq!(get32(main,0xfc0),11); assert_eq!(get32(main,0xfc4),10); + for i in 0..11 { + assert_eq!(get32(main,0xfc8+i*4),p.frequency[i]); + assert_eq!(get32(main,0x1808+i*4),p.auxiliary[i]); + assert_eq!(get32(main,0x1008+i*16*4),p.voltage[i]); + assert_eq!(get32(main,0x1408+(i*16+15)*4),p.sram[i]); + } + } +} +#[test] fn the_row_count_bounds_the_encoded_ceiling() { + let j713=tables(); let j773g=data::select_named(&j773g( + [100,600,620,660,700,750,750,800,800,850,850,900,900,950,950,1000], + [740,740,740,740,740,750,750,800,800,850,850,900,900,950,950,1000]),Some(11)).unwrap().0; + for (p,good,bad) in [(j713,[1,9],[0,10]),(j773g,[1,10],[0,11])] { + for ceiling in good { + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + assert!(wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),ceiling).is_ok()); + assert_eq!(get32(&buffers[wire::id::MAIN],0xfc0),p.count as u32); + } + for ceiling in bad { + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + assert!(wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),ceiling).is_err()); + assert!(buffers.iter().all(|buffer|buffer.iter().all(|&byte|byte==0xa5))); + } + } + // Rows past the count must stay zero, and the count must match the rows. + let mut p=tables(); p.frequency[10]=1500; assert!(!p.valid()); + let mut p=tables(); p.count=11; assert!(!p.valid()); } #[test] fn different_real_bin_values_reach_all_firmware_lanes() { let mut raw=MEASURED.to_vec(); @@ -134,9 +197,12 @@ def node(props, children=()): let mut s=source();s.frequency_mhz[4]=s.frequency_mhz[5]+1;s.sram_frequency_mhz[4]=s.frequency_mhz[4];assert!(data::select(&s).is_err()); let mut s=source();s.frequency_mhz[7]=s.frequency_mhz[5];s.sram_frequency_mhz[7]=s.frequency_mhz[7];assert!(data::select(&s).is_err()); let mut s=source();s.core_mv[14]=600;s.core_mv[15]=600;assert!(data::select(&s).is_err()); + // Three states at one voltage, and split pairs, match no layout. + let mut s=source();s.core_mv[6]=s.core_mv[5];s.sram_mv[6]=s.sram_mv[5];assert!(data::select(&s).is_err()); + let mut s=source();s.core_mv[4]-=1;s.core_mv[6]-=1;assert!(data::select(&s).is_err()); } #[test] fn j604_shape_selects_its_own_layout_and_the_j713_keeps_its_own() { - assert_eq!(data::select_named(&source()).unwrap().1,"J713"); + assert_eq!(data::select_named(&source(),None).unwrap().1,"J713"); // J604 shape: five low states, equal-voltage pairs 5/6 to 13/14, a single top state 15. // Rows 0-3 and 5-15 are the J604's selected values; state 4 (left out) is synthetic. let mhz=[0,338,618,796,928,952,1056,1053,1170,1152,1278,1204,1338,1326,1470,1578]; @@ -146,16 +212,27 @@ def node(props, children=()): s.frequency_mhz[i]=mhz[i];s.sram_frequency_mhz[i]=mhz[i]; s.core_mv[i]=mv[i];s.sram_mv[i]=mv[i].max(780); } - let (p,name)=data::select_named(&s).unwrap(); - assert_eq!(name,"J604"); - assert_eq!(p.frequency,[0,338,618,796,1056,1170,1278,1338,1470,1578]); - assert_eq!(p.auxiliary,[0,338,618,796,952,1053,1152,1204,1326,1578]); - assert_eq!(p.voltage,[125,625,640,680,780,825,865,895,970,1045]); - assert_eq!(p.sram,[780,780,780,780,780,825,865,895,970,1045]); - assert!(encode(p).is_ok()); - // A J604 shape with one unequal pair matches neither layout. + let (p,name)=data::select_named(&s,None).unwrap(); + assert_eq!(name,"J604"); assert_eq!(p.count,10); + assert_eq!(p.frequency,[0,338,618,796,1056,1170,1278,1338,1470,1578,0]); + assert_eq!(p.auxiliary,[0,338,618,796,952,1053,1152,1204,1326,1578,0]); + assert_eq!(p.voltage,[125,625,640,680,780,825,865,895,970,1045,0]); + assert_eq!(p.sram,[780,780,780,780,780,825,865,895,970,1045,0]); + assert!(encode(p.clone()).is_ok()); + // The board's row count picks between the two layouts of this shape. + assert_eq!(data::select_named(&s,Some(10)).unwrap(),(p,"J604")); + let (p,name)=data::select_named(&s,Some(11)).unwrap(); + assert_eq!(name,"J773g"); assert_eq!(p.count,11); + assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,1578]); + assert_eq!(p.auxiliary,[0,338,618,796,928,952,1053,1152,1204,1326,1578]); + // The J713 shape has no eleven-row layout, and no board has another row count. + assert_eq!(data::select_named(&source(),Some(10)).unwrap().1,"J713"); + assert_eq!(data::select_named(&source(),Some(11)),Err(perf::Error::Shape)); + for rows in [0,9,12] { assert_eq!(data::select_named(&s,Some(rows)),Err(perf::Error::Shape)); } + // A J604 shape with one unequal pair matches no layout. let mut bad=s;bad.core_mv[9]+=1;bad.sram_mv[9]+=1; assert_eq!(data::select(&bad),Err(perf::Error::Shape)); + assert_eq!(data::select_named(&bad,Some(11)),Err(perf::Error::Shape)); } #[test] fn invalid_encoder_input_is_refused_without_mutating_output() { for variant in 0..5 { @@ -177,7 +254,7 @@ def node(props, children=()): print(run.stdout, end='') print(run.stderr, end='') run.check_returncode() -report = {'passed': True, 'test_groups': 8, 'hardware_validated': False, +report = {'passed': True, 'test_groups': 10, 'hardware_validated': False, 'fixture_sha256': sha(fixture), 'original_adt_sha256': metadata['provenance']['source_sha256'], 'production_sha256': {str(p.relative_to(root)): sha(p) for p in [backend / 'adt.rs', backend / 'adt/perf.rs', backend / 'board.rs', backend / 'board/data.rs', backend / 'initdata.rs', backend / 'fw/initdata.rs']}} From 0fb26972a7d6a876e76372b0cf083d389c2c80a2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 13:01:07 -0500 Subject: [PATCH 03/19] drm/asahi: g16: reuse PB epochs, keep compute in flight, share 64 MiB PB heap, and close VM caches Carry the G16 parameter-buffer and compute-pipelining updates needed under the 26B123 runtime: - unconditionally reuse a pass slot's retired PB epoch for the same VM and binding (no runtime toggle or mutable debugfs); - keep compute commands in flight on dedicated per-unit UMA slots; - share one 64 MiB PB heap per VM across render allocators, sizing the PB manager descriptor fields to the actual backed heap_blocks rather than hardcoding 256 MiB, and recycle never-exposed spare epochs; - let closed VMs release arenas while slot leases retain only their own backing, and drain spare epochs in both Registry::prune() and Gpu::vm_closed() to break the Cache -> Arc cycle; - avoid redundant submit-path publication while a render is active. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 13 +- drivers/gpu/drm/asahi/g16/engine.rs | 277 ++++++++++++++---- drivers/gpu/drm/asahi/g16/fw/buffer.rs | 37 ++- drivers/gpu/drm/asahi/g16/job.rs | 15 +- drivers/gpu/drm/asahi/g16/mod.rs | 21 +- drivers/gpu/drm/asahi/g16/params.rs | 20 ++ drivers/gpu/drm/asahi/g16/poll.rs | 141 ++++++++- drivers/gpu/drm/asahi/g16/pools.rs | 138 +++++++-- drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 128 ++++++-- drivers/gpu/drm/asahi/g16/queue.rs | 5 + drivers/gpu/drm/asahi/g16/recovery.rs | 3 + drivers/gpu/drm/asahi/g16/resources.rs | 174 ++++++++++- drivers/gpu/drm/asahi/g16/slots.rs | 141 ++++++--- drivers/gpu/drm/asahi/g16/vm.rs | 13 +- .../drivers/gpu/asahi-m4/test-resources.py | 48 ++- .../drivers/gpu/asahi-m4/test-vm-registry.py | 25 +- 16 files changed, 995 insertions(+), 204 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index a2b329789444c..ea6f6882eff6a 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -112,12 +112,19 @@ impl Order { /// A same-engine command cannot jump a hole in its queue's completed frontier. /// Cross-engine historical dependencies end at the named prefix, even while later /// commands in that older submission remain pending. - pub(crate) fn ready(&self, completed: [u64; 2]) -> bool { - completed[self.engine].checked_add(1) == Some(self.sequence) + pub(crate) fn ready(&self, completed: [u64; 2], published: [u64; 2]) -> bool { + // Same-engine compute order and barriers are kept by the firmware compute queue, + // which finishes each command before it starts the next: its published frontier + // suffices. Renders, and every cross-engine dependency, need the completed one. + let mut frontier = completed; + if self.engine == COMPUTE { + frontier[COMPUTE] = published[COMPUTE].max(completed[COMPUTE]); + } + frontier[self.engine].checked_add(1) == Some(self.sequence) && self .wait_through .iter() - .zip(completed) + .zip(frontier) .all(|(prefix, observed)| prefix.is_none_or(|last| observed >= last)) } } diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 5ee33d71432d1..c431061332cec 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -3,10 +3,14 @@ //! Serialized M4 execution over the shared Asahi frontend. //! //! A userspace submission retains all commands, mappings and inputs through its final fence. -//! One command at a time is encoded into one of two retained units, then published to the -//! classic engine queues. Reuse requires a complete wire receipt followed by replacement -//! by the other retired unit in the same UMA slot. TA and FS remain a paired publication -//! with the native explicit TA dependency. This total order satisfies Mesa's command barriers. +//! Each command is encoded into a retained unit, then published to the classic engine queues. +//! A render is published only with nothing else in flight, and nothing is published behind +//! it. Compute commands queue behind in-flight compute commands (up to +//! [`params::compute_flights`]), each in its own unit of UMA slot 1: the firmware runs its +//! compute queue in publication order, each command to its Finalize, so publication order is +//! execution order. A unit is reused only after a later publication fully retired (it +//! displaced the unit). TA and FS remain a paired publication with the native explicit TA +//! dependency. This total order satisfies Mesa's command barriers. //! Firmware failure retains every possibly reachable owner. Completions are signalled only //! after dropping the device lock. @@ -17,10 +21,10 @@ use kernel::{prelude::*, sync::Arc}; use super::channel::Channel; use super::command::{Command, ComputeCommand, RenderCommand}; use super::encode::{self, ComputeRefs, Geometry, RenderRefs}; -use super::fw::channels::SubmitRecord; +use super::fw::channels::{SubmitRecord, RING_SLOTS}; use super::fw::graph::{notifier_page, qstate}; use super::fw::work::{self, BarrierType}; -use super::hw::sizes; +use super::hw::{engine as engine_ids, sizes}; use super::job::{Completions, Job}; use super::slots::Claims; use super::{params, Firmware, Shared}; @@ -54,8 +58,9 @@ pub(crate) fn now_ns() -> u64 { ::ktime_get() as u64 } -/// Counter value carried by a native 25G83 submit-pipe record. -fn counter_ticks() -> u64 { +/// Counter value carried by a native 25G83 submit-pipe record (the 24 MHz counter of the +/// firmware's internal timestamps). +pub(crate) fn counter_ticks() -> u64 { #[cfg(target_arch = "aarch64")] { let value: u64; @@ -180,6 +185,12 @@ pub(crate) struct Flight { pub(crate) recovery_started_ns: u64, /// Publication time, ns. pub(crate) published_ns: u64, + /// Published behind another flight. + pub(crate) behind: bool, + /// The PB epoch this render prefix uses (its own, or a reused one with `g16_pb_reuse`). + pub(crate) pb: Option>, + /// Its pass slot binding (`Pools::bind`). + pub(crate) pb_binding: u64, } impl Flight { @@ -209,6 +220,9 @@ impl Flight { recovery_suspect: false, recovery_started_ns: 0, published_ns: 0, + behind: false, + pb: None, + pb_binding: 0, } } } @@ -291,6 +305,10 @@ pub(crate) struct Stats { /// Why ready jobs stayed unpublished: both flights published, a channel record unconsumed, /// no free slot. pub(crate) hold: [u64; 3], + /// Compute commands published behind in-flight ones. + pub(crate) behind: u64, + /// Most flights in flight at once. + pub(crate) max_flights: u64, } /// Host-side phase timers of publication and polling, on with `debug_flags` bit 49 @@ -408,23 +426,21 @@ pub(crate) struct Engine { /// Progress tracking of the oldest prefix. pub(crate) progress_flight: u64, pub(crate) progress: [Option; 3], - pub(crate) stats: Stats, + /// Boxed with [`Self::prof`]: `Firmware` is built on the probe's stack. + pub(crate) stats: KBox, /// Phase timers (debug_flags bit 49). - pub(crate) prof: Prof, + pub(crate) prof: KBox, /// The `aurora-g16/stats` file. pub(crate) debugfs: Option>>>>, + /// The `aurora-g16/tune` file. + pub(crate) tune_file: Option>>>>, scratch: Option>, } impl Engine { pub(crate) fn new() -> Result { // Wrapped native stamps are safe only while pending references fit within the - // signed half-window. This backend publishes exactly one command at a time, - // retires its full wire/owner receipt, then builds the next command/barrier. - // Do not add submission-ahead without revisiting the dependency lifetime proof. - if sizes::FLIGHTS != 1 { - return Err(EINVAL); - } + // signed half-window: at most FLIGHTS commands are published at once, far inside it. Ok(Self { pending: KVec::new(), flights: KVec::with_capacity(sizes::FLIGHTS, GFP_KERNEL)?, @@ -448,9 +464,10 @@ impl Engine { chan_wait: false, progress_flight: 0, progress: [None; 3], - stats: Stats::default(), - prof: Prof::default(), + stats: KBox::new(Stats::default(), GFP_KERNEL)?, + prof: KBox::new(Prof::default(), GFP_KERNEL)?, debugfs: None, + tune_file: None, // Allocate host encoder buffers before any submitted fence can depend on // the device mutex. Publication must never enter direct reclaim here. scratch: Some(KBox::new(Scratch::new()?, GFP_KERNEL)?), @@ -631,14 +648,19 @@ impl Firmware { // owner, not the next command that happens to occupy the flight list. return Ok(()); } - let f = self.engine.flights.first_mut().ok_or(ENOENT)?; - let matches = match event { - 15 => f.computes != 0 && f.target == target, - 0x70 => f.renders != 0 && f.ta_target == target, - 0x71 => f.renders != 0 && f.fs_target == target, - _ => false, - }; - if !matches || flags & 1 == 0 { + // The named owner: the oldest flight, or with compute queued behind it a later one. + let f = self + .engine + .flights + .iter_mut() + .find(|f| match event { + 15 => f.computes != 0 && f.target == target, + 0x70 => f.renders != 0 && f.ta_target == target, + 0x71 => f.renders != 0 && f.fs_target == target, + _ => false, + }) + .ok_or(ENOENT)?; + if flags & 1 == 0 { return Err(ENOENT); } if flags & 9 == 9 @@ -668,19 +690,24 @@ impl Firmware { _event: u32, fault_asid: Option, ) -> Result { - let Some(f) = self.engine.flights.first_mut() else { - return Ok(()); - }; let reached = super::recovery::logic::stamp_reached; - let unfinished = (f.computes != 0 && !reached(stage[2], f.target, self.engine.target)) - || (f.renders != 0 - && (!reached(stage[0], f.ta_target, self.engine.ta_target) - || !reached(stage[1], f.fs_target, self.engine.fs_target))); - if unfinished { - f.recovery_suspect = true; - f.recovery_started_ns = now_ns(); - if fault_asid.is_some_and(|asid| asid >= 1 && asid == f.job.vm.slot) { - f.doomed = true; + let (target, ta_target, fs_target) = ( + self.engine.target, + self.engine.ta_target, + self.engine.fs_target, + ); + // Every unfinished flight, including compute queued behind the oldest. + for f in self.engine.flights.iter_mut() { + let unfinished = (f.computes != 0 && !reached(stage[2], f.target, target)) + || (f.renders != 0 + && (!reached(stage[0], f.ta_target, ta_target) + || !reached(stage[1], f.fs_target, fs_target))); + if unfinished { + f.recovery_suspect = true; + f.recovery_started_ns = now_ns(); + if fault_asid.is_some_and(|asid| asid >= 1 && asid == f.job.vm.slot) { + f.doomed = true; + } } } Ok(()) @@ -748,8 +775,10 @@ impl Firmware { }; let job = self.engine.pending[index].clone(); // Even a failed job may have an earlier command in flight. An aggregate - // error fence must not race that command's access to user buffers. - if !self.engine.flights.is_empty() { + // error fence must not race that command's access to user buffers: only a + // healthy compute command queues behind in-flight compute; everything else + // (and every failure path below) waits for the engine to drain. + if !self.engine.flights.is_empty() && !self.can_queue_behind(&job) { self.engine.stats.hold[0] += 1; break; } @@ -782,6 +811,20 @@ impl Firmware { } None => None, }; + // A VM whose own units were all quarantined (without the class being exhausted) + // cannot run compute again: cancel its queue like an exhausted class would. + if class_error.is_none() + && matches!(command(&job, job.progress.sent()), Some(Command::Compute(_))) + && job + .resources + .compute_units() + .is_ok_and(|n| self.slots.compute_exhausted_within(n)) + { + self.engine.unpend(&job); + let _ = job.mark_terminal_retired(); + complete(done, &job, Err(ECANCELED)); + continue; + } if let Some((class, error)) = class_error { self.mark_class_unavailable(class, error); self.engine.unpend(&job); @@ -811,6 +854,15 @@ impl Firmware { } continue; } + Err(PublicationError::Unpublished(e)) + if e == EAGAIN && !self.engine.flights.is_empty() => + { + // Waits for an in-flight command: its retirement repolls publication, + // and the flights' own deadlines apply. + let i = if self.engine.chan_wait { 1 } else { 2 }; + self.engine.stats.hold[i] += 1; + break; + } Err(PublicationError::Unpublished(e)) if e == EAGAIN => { let i = if self.engine.chan_wait { 1 } else { 2 }; self.engine.stats.hold[i] += 1; @@ -865,6 +917,52 @@ impl Firmware { result } + /// Whether `job`'s next command may be published behind the flights in flight: it is a + /// healthy compute command whose dependencies are met, every flight is a healthy + /// compute-only prefix of the same VM, and the compute depth is below + /// [`params::compute_flights`]. Renders, another VM's commands and every failure path + /// need an empty engine: under several clients, compute queued behind another VM's + /// lost its writes and stalled the firmware compute queue. + fn can_queue_behind(&self, job: &Arc) -> bool { + let e = &self.engine; + if e.flights.len() >= params::compute_flights() + || e.flights.iter().any(|f| { + f.renders != 0 + || f.doomed + || f.recovery_suspect + || !Arc::ptr_eq(&f.job.vm, &job.vm) + || Self::writes_timestamps(f) + }) + || job.vm.status.get() != 0 + || self.slots.compute_exhausted() + || super::recovery::logic::next_ordinal(e.ordinal).is_none() + || !job + .resources + .compute_units() + .is_ok_and(|units| self.slots.compute_available(units)) + { + return false; + } + let sent = job.progress.sent(); + matches!(command(job, sent), Some(Command::Compute(_))) + && job.check_command_dependencies(sent).is_ok() + } + + /// Whether a flight's commands have user timestamps. The host writes them when the + /// command retires, so a command queued behind it (a query copy, possibly waiting on + /// availability) could run before they exist; it waits for the retirement instead. + fn writes_timestamps(f: &Flight) -> bool { + f.job + .commands + .get(f.first..f.first + f.count) + .is_none_or(|commands| { + commands.iter().any(|command| match command { + Command::Compute(c) => !c.timestamp_outputs.is_empty(), + Command::Render(r) => !r.timestamp_outputs.is_empty(), + }) + }) + } + /// Whether some of `job`'s commands were published: such a job is retained after a /// fail-stop. pub(crate) fn job_partly_published(&self, job: &Job) -> bool { @@ -872,12 +970,30 @@ impl Firmware { } /// Addresses and cumulative allocator state of the selected retained render unit. - fn render_refs(&mut self, k: usize, job: &Job, draw: u64) -> Result<(RenderRefs, bool)> { + fn render_refs( + &mut self, + k: usize, + job: &Job, + draw: u64, + ) -> Result<(RenderRefs, bool, Arc, u64)> { let generation = job.vm.generation; let arena = job.resources.render()?; let mut a = arena.pools.prepare(k, draw)?; - let epoch = job.resources.pb(job.progress.sent() as usize)?; - epoch.prepare(k, arena.pools.heap_gva(k)?)?; + // g16_pb_reuse: reuse this VM's retired epoch of the slot: no reseed, no InitBM. + let (epoch, reused) = match self.pools.reusable(params::pb_reuse(), k, &job.vm) { + Some(e) => { + self.pools.stats.reused += 1; + a.init_buffer = false; + (e, true) + } + None => { + let e = job.resources.pb(job.progress.sent() as usize)?.clone(); + e.prepare(k, arena.pools.heap_gva(k)?, arena.pools.heap_blocks())?; + self.pools.stats.fresh += 1; + (e, false) + } + }; + let binding = self.pools.bind(k, reused); a.pb_mgr = epoch.manager.va; a.mgr_misc = epoch.misc.va; let r = &self.graph.render; @@ -908,6 +1024,8 @@ impl Firmware { usc_base: job.queue.usc_base, }, a.init_buffer, + epoch, + binding, )) } @@ -944,7 +1062,8 @@ impl Firmware { f: &mut Flight, visible: &mut bool, ) -> Result { - if !self.engine.flights.is_empty() { + let behind = !self.engine.flights.is_empty(); + if behind && !self.can_queue_behind(job) { return Err(EAGAIN); } let index = job.progress.sent(); @@ -968,10 +1087,16 @@ impl Firmware { for &channel in channels { let pipe = self.channels.channel(channel); let producer = self.channels.producer(channel); - if pipe.read()? != producer - || pipe.completion()? != producer - || pipe.write()? != producer - { + let busy = if behind { + // Behind in-flight compute: post after its unconsumed records, with room. + pipe.write()? != producer + || producer.wrapping_sub(pipe.read()?) % RING_SLOTS >= sizes::AHEAD_RECORDS + } else { + pipe.read()? != producer + || pipe.completion()? != producer + || pipe.write()? != producer + }; + if busy { self.engine.chan_wait = true; return Err(EAGAIN); } @@ -991,6 +1116,15 @@ impl Firmware { if prefix.c_head >= 256 || prefix.ta_head >= 256 || prefix.fs_head >= 256 { return Err(super::boot::eproto()); } + if behind { + // Room for one more compute entry behind the unconsumed ones. + let read = self.graph.compute.qstate.r32(qstate::READ)?; + if read >= 256 + || prefix.c_head.wrapping_sub(read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 2 + { + return Err(EAGAIN); + } + } f.c_start = prefix.c_head; f.ta_start = prefix.ta_head; f.fs_start = prefix.fs_head; @@ -1033,13 +1167,14 @@ impl Firmware { return Err(EAGAIN); } if render { - job.resources - .pb(index as usize)? + f.pb.as_ref() + .ok_or(EINVAL)? .check_assignment(f.claims.pass[0] as usize)?; } // Reserve lifetime ownership before any counter or producer becomes reachable. job.vm.vm.mark_binding_published()?; self.slots.hold_vm(&f.claims, &job.vm)?; + self.slots.hold_arenas(&f.claims, &job.resources); self.slots.publish(&f.claims)?; // Even a failed first store may have become visible. From this boundary preserve // every owner and return explicit uncertainty rather than guessing from errno. @@ -1047,7 +1182,7 @@ impl Firmware { let publication = (|| -> Result { if render { let k = f.claims.pass[0] as usize; - job.resources.pb(index as usize)?.expose(); + f.pb.as_ref().ok_or(EINVAL)?.expose(); job.resources.render()?.pools.publish(k, f.uma_submitted)?; // Notifier service dereferences u32 counters; the host ordering ledger // remains u64. Eight-byte spacing is retained allocation padding. @@ -1055,7 +1190,8 @@ impl Firmware { self.graph.render.threshold.w32(8, prefix.draw as u32)?; } else { let k = f.claims.slot[0] as usize; - job.resources.compute()?.compute[k] + job.resources + .compute_unit(k)? .counter .w64(0, f.uma_submitted)?; self.graph.compute.threshold.w32(0, prefix.n as u32)?; @@ -1076,6 +1212,8 @@ impl Firmware { )?; } wmb(); + // Every command posts its own record: the firmware does not pick up a WRITE + // advance without one, also while the queue is running. for &channel in channels { let (qinfo, head, event, fresh) = match channel { Channel::Compute => ( @@ -1105,7 +1243,11 @@ impl Firmware { event, new_queue: u8::from(fresh), }; - self.channels.post(channel, &record)?; + if behind { + self.channels.post_ahead(channel, &record)?; + } else { + self.channels.post(channel, &record)?; + } self.session.ring(channel)?; } Ok(()) @@ -1136,9 +1278,14 @@ impl Firmware { } self.engine.events = self.events.compute_events; self.engine.stage_seen = self.events.stage_events; + f.behind = behind; self.stat_publish(f); - self.renew_deadlines(); + if !behind { + // A command behind others keeps the oldest's deadline: it starts only after them. + self.renew_deadlines(); + } job.progress.set_sent(index + 1); + job.command_published(index); let mut flight = Flight::new(job.clone()); core::mem::swap(&mut flight, f); self.engine @@ -1150,6 +1297,8 @@ impl Firmware { core::mem::forget(flight); EIO })?; + let s = &mut self.engine.stats; + s.max_flights = s.max_flights.max(self.engine.flights.len() as u64); publication.map_err(|_| EIO) } @@ -1166,11 +1315,12 @@ impl Firmware { let target = encode::stamp(n); let index = self .slots - .claim_compute(job.resources.compute()?, &mut f.claims, 0)? + .claim_compute(&job.resources, &mut f.claims, 0)? .ok_or(EAGAIN)?; let generation = job.vm.generation; self.slots.hold_vm(&f.claims, &job.vm)?; - let s = &job.resources.compute()?.compute[index]; + self.slots.hold_arenas(&f.claims, &job.resources); + let s = job.resources.compute_unit(index)?; let g = &self.graph.compute; let before = s.counter.r64(0)?; let submitted = before.checked_add(1).ok_or(EOVERFLOW)?; @@ -1195,7 +1345,9 @@ impl Firmware { usc_base: job.queue.usc_base, record_fw: g.notifier.va + notifier_page::COMPUTE_RECORD as u64, binding_generation: generation, - uma_slot: 1, + // Each unit owns its UMA slot: the firmware starts a queued command while the + // one before it still runs, and two owners of one slot then corrupt each other. + uma_slot: engine_ids::COMPUTE_UMA_SLOT + index as u32, // Preserve the already qualified packet bytes while expressing the native // fields separately. This compatibility identifier is not proof of native // global command-ID allocation or uniqueness after compute-index wrap. @@ -1263,7 +1415,10 @@ impl Firmware { // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots.claim_pass(job.resources.render()?, k)?; self.slots.hold_vm(&f.claims, &job.vm)?; - let (refs, init_buffer) = self.render_refs(k, job, draw)?; + self.slots.hold_arenas(&f.claims, &job.resources); + let (refs, init_buffer, epoch, binding) = self.render_refs(k, job, draw)?; + f.pb = Some(epoch); + f.pb_binding = binding; let p = &job.resources.render()?.passes[k]; let pass = p.refs(); let geometry = Geometry::new(&cmd.cmd, pass.heap_gva); @@ -1322,7 +1477,7 @@ impl Firmware { if init_buffer { pf.initbm = true; let bm = encode::initbm(job.vm.slot, refs.parameter_id, refs.pb_mgr, target); - let epoch = job.resources.pb(job.progress.sent() as usize)?; + let epoch = f.pb.as_ref().ok_or(EINVAL)?; epoch.initbm.write(0, &bm)?; r.ring[0].w64(8 * pf.ta_head as usize, epoch.initbm.va)?; pf.ta_head = (pf.ta_head + 1) % cap; @@ -1356,6 +1511,10 @@ impl Firmware { let s = &mut self.engine.stats; s.pub_ns = now_ns(); f.published_ns = s.pub_ns; + if f.behind { + s.behind += 1; + s.overlaps += 1; + } s.prep_ns += s.pub_ns.wrapping_sub(s.prep_from_ns); if s.idle_from_ns != 0 { s.gap_ns += s.pub_ns.wrapping_sub(s.idle_from_ns); diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index 813e52d886fdc..07317ee4663dc 100644 --- a/drivers/gpu/drm/asahi/g16/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g16/fw/buffer.rs @@ -82,7 +82,8 @@ fn put64(x: &mut [u8], off: usize, v: u64) { x[off..off + 8].copy_from_slice(&v.to_le_bytes()); } -/// Literal fresh M4 PB manager. The firmware and GPU page-list aliases share backing. +/// Literal fresh M4 PB manager sized to `heap_blocks` (1..=[`MAX_BLOCKS`]). +/// The firmware and GPU page-list aliases share backing. #[allow(clippy::too_many_arguments)] pub(crate) fn pb_manager_image( id: u32, @@ -91,23 +92,26 @@ pub(crate) fn pb_manager_image( blocks_fw: u64, ring_fw: u64, count_fw: u64, + heap_blocks: u32, ) -> [u8; pb_manager::SIZE] { + let blocks = heap_blocks.clamp(1, MAX_BLOCKS); + let pages = blocks * PAGES_PER_BLOCK; let mut m = [0; pb_manager::SIZE]; put32(&mut m, 0xc, id); put32(&mut m, 0x10, id); put64(&mut m, 0x20, pages_fw); put64(&mut m, 0x28, pages_gpu); put32(&mut m, 0x30, PAGE_LIST_SIZE as u32); - put32(&mut m, 0x34, MAX_PAGES); + put32(&mut m, 0x34, pages); put32(&mut m, 0x38, BLOCK_LIST_RECORDS); - put32(&mut m, 0x3c, MAX_BLOCKS); + put32(&mut m, 0x3c, blocks); put64(&mut m, 0x44, blocks_fw); put64(&mut m, 0x4c, ring_fw); - put32(&mut m, 0x54, MAX_PAGES - 1); + put32(&mut m, 0x54, pages - 1); put32(&mut m, 0x58, BLOCK_BYTES as u32); put64(&mut m, 0x64, count_fw); - put32(&mut m, 0x7c, MAX_PAGES); - put32(&mut m, 0x80, MAX_PAGES); + put32(&mut m, 0x7c, pages); + put32(&mut m, 0x80, pages); m } @@ -156,6 +160,7 @@ mod tests { 0xfffffc2000500000, 0xfffffc2000600000, 0xfffffc2000700000, + MAX_BLOCKS, ); assert_eq!(m.len(), 0xc0); assert_eq!((r32(&m, 0xc), r32(&m, 0x10)), (1, 1)); @@ -169,6 +174,26 @@ mod tests { assert_eq!(r32(&m, 0x54), 8191); assert_eq!(r32(&m, 0x7c), 8192); assert_eq!(r32(&m, 0x80), 8192); + // A 64 MiB heap (512 blocks / 2048 pages) describes only its backed blocks and pages. + let small = pb_manager_image( + 0, + 0xfffffc2000400000, + 0x701a040000, + 0xfffffc2000500000, + 0xfffffc2000600000, + 0xfffffc2000700000, + 512, + ); + assert_eq!( + ( + r32(&small, 0x34), + r32(&small, 0x3c), + r32(&small, 0x54), + r32(&small, 0x7c), + r32(&small, 0x80), + ), + (2048, 512, 2047, 2048, 2048) + ); let written = [ (0xc, 8), (0x20, 16), diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 31f06c80ab8bf..d79d5892d31f4 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -290,7 +290,12 @@ impl Job { .completed .each_ref() .map(|value| value.load(Ordering::Acquire)); - if !order.ready(completed) { + let published = self + .queue + .published + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + if !order.ready(completed, published) { return Err(EAGAIN); } Ok(()) @@ -299,6 +304,14 @@ impl Job { /// Advances exactly one queue-local engine ordinal after a full successful wire receipt. /// Called under the device lock before another command is considered. No allocation, /// fence callback or aggregate-job completion occurs here. + /// Advances the queue's published frontier past command `index` (under the device + /// lock, when its first producer became visible). + pub(crate) fn command_published(&self, index: u32) { + if let Some(order) = self.orders.get(index as usize) { + self.queue.published[order.engine].fetch_max(order.sequence, Ordering::AcqRel); + } + } + pub(crate) fn command_retired(&self, index: u32) -> Result { let order = self.orders.get(index as usize).ok_or(EINVAL)?; let previous = order.sequence.checked_sub(1).ok_or(EINVAL)?; diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index f161b218a0d06..b3dbc6bd3c73b 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! G16 GPU support (T8132, M4: J713; the qualified 25G83 firmware). +//! G16 GPU support (T8132, M4: J713 and J773g; the qualified 25G83 firmware, and the 26B123 +//! firmware's ABI, whose start is refused until its remaining unknowns are known). //! //! G16 firmware is *classic*: one ring per engine (TA, FS, compute) and ordering expressed by //! in-ring barrier records that wait on another queue's stamp, unlike the G17 kick-ring/QID @@ -367,6 +368,9 @@ pub(crate) struct Gpu { pub(crate) shared: Arc, /// The adopted UAT, for creating and binding user VMs without the device lock. pub(crate) uat: Arc, + /// Live VM registry, kept directly on `Gpu` so `vm_closed()` still breaks resource-cache + /// cycles even if `shared.state` is absent (fail-stop or teardown). + vms: Arc, } impl Gpu { @@ -415,6 +419,7 @@ impl Gpu { let (id, max_frequency_khz) = (booted.id, booted.max_frequency_khz); // The backend: graphs, slots, pools, engine, recovery and VM registry. let firmware = Firmware::start_backend(dev, booted, &shared, power)?; + let vms = firmware.vms.clone(); *shared.state.lock() = Some(firmware); // The engine's statistics file (a debugfs failure does not fail the probe). if let Err(error) = shared.start_engine() { @@ -428,6 +433,7 @@ impl Gpu { ids: Default::default(), shared, uat, + vms, }, GFP_KERNEL, )?; @@ -456,7 +462,7 @@ impl Firmware { dev: &AsahiDrmDevice, booted: boot::Booted, shared: &Arc, - power: power::Power, + mut power: power::Power, ) -> Result> { let boot::Booted { session, @@ -470,6 +476,7 @@ impl Firmware { dev.as_ref(), "G16: firmware at READY, starting the backend\n" ); + power.set_table(init.rows); let orphan = |session: boot::Session, objects: object::Objects, channels: channel::Channels, @@ -623,15 +630,7 @@ impl gpu::Gpu for Gpu { vm::new_vm(self, kernel_range, file_id) } fn vm_closed(&self, vm: &mmu::Vm) { - let registry = self - .shared - .state - .lock() - .as_ref() - .map(|state| state.vms.clone()); - if let Some(registry) = registry { - registry.close(vm.id()); - } + self.vms.close(vm.id()); } fn new_queue( diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index d2ef01e26b3a3..bcf52a272ca92 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -28,6 +28,26 @@ pub(crate) fn compute_deadline_ms() -> u32 { module_parameters::g16_compute_deadline_ms.value() } +/// PB heap blocks of a new render arena (64 MiB in 128 KiB blocks). +pub(crate) fn pb_heap_blocks() -> u32 { + 64 * 8 +} + +/// PB blocks posted to a fresh epoch of a heap of `heap_blocks`. +pub(crate) fn pb_posted_blocks(heap_blocks: u32) -> u32 { + 2048u32.min(heap_blocks) +} + +/// Compute units of a VM that submits compute back to back. +pub(crate) fn compute_units() -> usize { + 6usize.clamp(2, hw::sizes::COMPUTE_UNITS) +} + +/// Compute commands in flight at most. +pub(crate) fn compute_flights() -> usize { + 16usize.clamp(1, hw::sizes::FLIGHTS) +} + /// Repoll while a ready prefix waits for record consumption, us. pub(crate) fn repoll_us() -> u32 { module_parameters::g16_repoll_us.value().clamp(5, 100) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 4e9bfaef02e12..e384e30a02411 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -56,6 +56,25 @@ impl HrTimerCallback for Shared { } } +/// The `aurora-g16/tune` debugfs file: current tunables. +fn tune_show(_shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { + super::params::tune::show(f) +} + +/// The `aurora-g16/tune` debugfs file: `name=value` lines. +fn tune_write(_shared: &Arc, reader: &mut kernel::uaccess::UserSliceReader) -> Result { + let mut buf = [0u8; 128]; + let len = reader.len().min(buf.len()); + reader.read_slice(&mut buf[..len])?; + let text = core::str::from_utf8(&buf[..len]).map_err(|_| EINVAL)?; + for line in text.split(|c| c == '\n' || c == ' ' || c == ',') { + if !line.trim().is_empty() { + super::params::tune::set(line)?; + } + } + Ok(()) +} + /// The `aurora-g16/stats` debugfs file contents. fn stats_show(shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { let state = shared.state.lock(); @@ -119,7 +138,11 @@ impl Shared { firmware.engine.shared = Some(self.clone()); } let accepted = firmware.enqueue(job); - if accepted.is_ok() { + // Nothing is published while a render is in flight: the poll pass after its + // retirement publishes this job. Skipping the pass here keeps queued submissions + // from holding the device lock (ring drains, health checks) on that path. + let render_busy = firmware.engine.flights.iter().any(|f| f.renders != 0); + if accepted.is_ok() && !render_busy { if let Err(error) = firmware.publish(&mut done) { firmware.fail_stop(error, &mut done); self.fail_stop(error); @@ -198,10 +221,15 @@ impl Shared { dir.read_callback_file(c_str!("stats"), self.clone(), &stats_show), GFP_KERNEL, )?; + let tune = KBox::pin_init( + dir.read_write_callback_file(c_str!("tune"), self.clone(), &tune_show, &tune_write), + GFP_KERNEL, + )?; let mut state = self.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; firmware.engine.shared = Some(self.clone()); firmware.engine.debugfs = Some(file); + firmware.engine.tune_file = Some(tune); Ok(()) } } @@ -212,7 +240,6 @@ pub(crate) fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { } /// Cursor `c` of a ring of `m` entries passed end `h` of entries from `b`, within tail `t`. -#[allow(dead_code)] pub(crate) fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { let d = |x: u32| x.wrapping_add(m).wrapping_sub(b) % m; let (dc, dh, dt) = (d(c), d(h), d(t)); @@ -341,6 +368,40 @@ impl Firmware { Ok(true) } + /// In-order receipt of compute flight `f` with later flights queued behind it: the NC + /// READ cursor (and with uncached queue info its consumers) passed its ring entries, + /// and the submit pipe's read and completion cursors passed its record. + fn queue_passed( + &self, + channel: Channel, + state: &super::object::FwObject, + info: &super::object::FwObject, + f: &Flight, + ) -> Result { + let cap = super::hw::sizes::QUEUE_CAP; + let tail = self.engine.head; + if f.head >= cap || f.c_start >= cap || tail >= cap { + return Err(EINVAL); + } + if !ring_passed(state.r32(qstate::READ)?, f.c_start, f.head, tail, cap) { + return Ok(false); + } + if !super::hw::tuning::FW_CACHED { + for offset in [0x20, 0x24, 0x28] { + if !ring_passed(info.r32(offset)?, f.c_start, f.head, tail, cap) { + return Ok(false); + } + } + } + let slots = super::fw::channels::RING_SLOTS; + let record = f.rec[2]; + let first = (record + slots - 1) % slots; + let producer = self.channels.producer(channel); + let pipe = self.channels.channel(channel); + Ok(ring_passed(pipe.read()?, first, record, producer, slots) + && ring_passed(pipe.completion()?, first, record, producer, slots)) + } + /// A full receipt includes stage and notifier stamps, every physical consumer, /// the private allocator completion and the internal timestamp pair. An aborted /// receipt omits only the writes firmware does not make for an aborted command, @@ -359,7 +420,33 @@ impl Firmware { }; rmb(); let mut full = true; - if f.computes != 0 { + // Later compute flights queued behind this one: the queue, pipe and stamp cells + // already moved on, so their receipt is "passed", in order; the newest flight keeps + // the exact receipt. + let behind = self.engine.flights.len() > 1; + if f.computes != 0 && behind { + let g = &self.graph.compute; + let e = &self.engine; + if !stamp_reached(g.fw_stamp.r32(0)?, f.target, e.target) + || !self.queue_passed(Channel::Compute, &g.qstate, &g.qinfo, f)? + { + return Ok(Retirement::Pending); + } + let k = f.claims.slot[0] as usize; + let unit = f.job.resources.compute_unit(k)?; + let submitted = unit.counter.r64(0)?; + let start = unit.its.r64(0)?; + let end = unit.its.r64(8)?; + let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; + full &= stamp_reached(stamp, f.target, e.target) + && (stamp != f.target + || g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot) + && submitted != 0 + && unit.work.r64(compute::DESCRIPTOR_COMPLETED)? == submitted + && unit.work.r64(compute::DESCRIPTOR_COUNTER)? == unit.counter.va + && start != 0 + && end > start; + } else if f.computes != 0 { let g = &self.graph.compute; if g.fw_stamp.r32(0)? != f.target || !self.queue_receipt(Channel::Compute, &g.qstate, &g.qinfo, f.head, f.rec[2])? @@ -367,7 +454,7 @@ impl Firmware { return Ok(Retirement::Pending); } let k = f.claims.slot[0] as usize; - let unit = f.job.resources.compute()?.compute.get(k).ok_or(EINVAL)?; + let unit = f.job.resources.compute_unit(k)?; let submitted = unit.counter.r64(0)?; let start = unit.its.r64(0)?; let end = unit.its.r64(8)?; @@ -494,9 +581,13 @@ impl Firmware { if f.renders != 0 { self.recovery.last_retired[1] = Some(f.ta_target); self.recovery.last_retired[2] = Some(f.fs_target); - let committed = f.job.resources.pb(f.first).and_then(|epoch| { + let committed = f.pb.as_ref().ok_or(EINVAL).and_then(|epoch| { + let k = timestamp_claims.pass[0] as usize; + self.pools.retire_binding(k, epoch)?; + let enabled = params::pb_reuse(); self.pools - .retire_binding(timestamp_claims.pass[0] as usize, epoch) + .retire_epoch(enabled, k, f.pb_binding, result.is_ok()); + Ok(()) }); if let Err(error) = committed { self.retain(&f.job); @@ -518,6 +609,10 @@ impl Firmware { } else { // Only an actual passed abort lacks the full owner receipt. An affected job // with a full normal receipt fails its fence without poisoning healthy storage. + if f.renders != 0 { + // The quarantined slot is not picked again, but keep no epoch of it for reuse. + self.pools.forget(timestamp_claims.pass[0] as usize); + } self.slots.quarantine(&mut f.claims); self.retain(&f.job); self.recovery.aborted_receipts = self.recovery.aborted_receipts.saturating_add(1); @@ -556,6 +651,15 @@ impl Firmware { let job = f.job.clone(); let p = &job.progress; p.next.store(p.next() + f.count as u32, Ordering::Relaxed); + if result.is_err() { + // Its queue's later commands queued behind it fail with it, as unpublished ones + // are cancelled: they never report a successful receipt after this hole. + for later in self.engine.flights.iter_mut() { + if Arc::ptr_eq(&later.job.queue, &job.queue) { + later.doomed = true; + } + } + } if let Err(error) = result { if p.is_pending() { // Drop its unpublished commands. @@ -654,13 +758,7 @@ impl Firmware { match command { super::command::Command::Compute(command) => { let index = *slots.get(compute).ok_or(EINVAL)? as usize; - let unit = flight - .job - .resources - .compute()? - .compute - .get(index) - .ok_or(EINVAL)?; + let unit = flight.job.resources.compute_unit(index)?; let ticks = [unit.its.r64(0)?, unit.its.r64(8)?, 0, 0]; command .timestamp_outputs @@ -750,10 +848,9 @@ impl Firmware { ); } for k in 0..(f.computes as usize).min(f.claims.slot_count as usize) { - let Some(arena) = f.job.resources.compute.as_ref() else { + let Ok(c) = f.job.resources.compute_unit(f.claims.slot[k] as usize) else { return; }; - let c = &arena.compute[f.claims.slot[k] as usize]; stage(&c.its, 0, &mut s.cdm_ticks, crate::usage::Engine::Compute); } if hi > lo { @@ -990,6 +1087,20 @@ impl Firmware { s.span_ticks / 24 )?; // The phase timers of debug_flags bit 49, and the scrub flush waits. + { + let s = &self.engine.stats; + writeln!( + f, + "pipeline: behind {} max_flights {} compute_published {} hold {}/{}/{}", + s.behind, + s.max_flights, + self.slots.compute_published(), + s.hold[0], + s.hold[1], + s.hold[2] + )?; + super::params::tune::show(f)?; + } let p = &self.engine.prof; writeln!( f, diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index d4a85cc6f3d36..739cfd1510de4 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -2,9 +2,13 @@ //! Private render UMA/heap backing and device-wide PB-slot leases. //! -//! Each VM keeps two persistent UMA/heap units. Each render command installs a fresh -//! PB manager with full InitBM and never reinitializes exposed cursors. The previous -//! PB-slot lease survives until the replacement's complete normal retirement. +//! Each VM keeps two persistent UMA units and one PB heap they share: a render is published +//! only while no other command is in flight and retires with its blocks returned, so the two +//! pass slots' PB managers never hand out heap blocks at the same time. A render reuses its +//! pass slot's lease, its VM's last successfully retired epoch of the slot, while the slot is +//! still bound to it, unchanged (the host writes nothing to it, no InitBM). Otherwise it +//! installs a fresh PB manager with full InitBM and never reinitializes exposed cursors. The +//! previous PB-slot lease survives until the replacement's complete normal retirement. #[path = "pools/lifetime.rs"] pub(crate) mod lifetime; @@ -67,10 +71,16 @@ pub(crate) struct PbStats { #[allow(dead_code)] pub(crate) refused: u64, pub(crate) bad: u64, + /// Pass slot bindings that reused a retired epoch / started a fresh one (a deferred + /// render counts again when it is retried). + pub(crate) reused: u64, + pub(crate) fresh: u64, } pub(crate) struct PoolSet { units: KVec, + /// Blocks of the shared heap (the PB managers' lists cover the whole 256 MiB window). + heap_blocks: u32, } fn alloc( @@ -122,7 +132,7 @@ fn write_records( Ok(()) } impl Allocator { - fn new(o: &mut Objects, k: u64) -> Result { + fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { let base = client::render_base(k); let nc = |va| Some((va, pte::LEAF_NC)); // Native UMA software metadata is ASC-owned and never needs a client GPU alias. @@ -146,13 +156,7 @@ impl Allocator { let state = alloc(o, 0x20000, Class::Shared, nc(client::render_state(k)), true)?; let list = alloc(o, 0x4000, Class::Shared, nc(client::render_list(k)), true)?; let submitted = alloc(o, 0x40, Class::Fw, None, true)?; - let heap = alloc( - o, - client::PB_HEAP_SIZE as usize, - Class::Shared, - nc(client::pb_heap(k)), - false, - )?; + let heap = heap.clone(); let scene_list = alloc( o, buffer::SCENE_LIST_SIZE, @@ -213,11 +217,21 @@ impl Allocator { } impl PoolSet { pub(crate) fn new(o: &mut Objects) -> Result { + // The firmware copes with a full PB without the host (its overflow counters move and + // the scene completes), so the heap is sized well below the 256 MiB window. + let heap_blocks = super::params::pb_heap_blocks().min(buffer::MAX_BLOCKS); + let heap = alloc( + o, + heap_blocks as usize * buffer::BLOCK_BYTES as usize, + Class::Shared, + Some((client::pb_heap(0), pte::LEAF_NC)), + false, + )?; let mut units = KVec::with_capacity(2, GFP_KERNEL)?; for k in 0..2 { - units.push(Allocator::new(o, k)?, GFP_KERNEL)?; + units.push(Allocator::new(o, k, &heap)?, GFP_KERNEL)?; } - Ok(Self { units }) + Ok(Self { units, heap_blocks }) } #[allow(dead_code)] pub(crate) fn allocator_refs_for(&self, k: usize) -> Result { @@ -252,6 +266,9 @@ impl PoolSet { pub(crate) fn heap_gva(&self, k: usize) -> Result { gva(&self.units.get(k).ok_or(EINVAL)?.heap) } + pub(crate) fn heap_blocks(&self) -> u32 { + self.heap_blocks + } } /// Device-wide physical PB-slot leases. Replacement requires a complete normal receipt. @@ -259,6 +276,11 @@ pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, owners: [Option>; 2], + /// Per pass slot, a binding count, bumped by each fresh epoch (its InitBM rebinds the + /// slot) and by a firmware recovery. It identifies a binding without holding the epoch. + binds: [u64; 2], + /// Per pass slot: `owners[k]` may serve the next render of its VM. + keep: [bool; 2], } impl Pools { pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { @@ -266,6 +288,59 @@ impl Pools { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), owners: [None, None], + binds: [0, 0], + keep: [false, false], + } + } + /// Slot `k`'s owner epoch, if its render retired normally while the slot was still bound to + /// it, it belongs to `vm` and was exposed (its InitBM ran). InitBM binds the device-wide + /// slot to one epoch and VM; a fresh epoch handed to the slot rebinds it, so the owner is + /// then stale and the render starts fresh. Adds no reference beyond the owner lease itself. + pub(crate) fn reusable(&self, k: usize, vm: &Arc) -> Option> { + if !*self.keep.get(k)? { + return None; + } + let owner = self.owners.get(k)?.as_ref()?; + (Arc::ptr_eq(&owner._vm, vm) && owner.exposed.load(Ordering::Acquire)) + .then(|| owner.clone()) + } + /// Slot `k` is handed to a render's epoch, `reused` or fresh (with InitBM). Returns the + /// binding the render retires with. + pub(crate) fn bind(&mut self, k: usize, reused: bool) -> u64 { + let (Some(binds), Some(keep)) = (self.binds.get_mut(k), self.keep.get_mut(k)) else { + return 0; + }; + if !reused { + *binds = binds.wrapping_add(1); + *keep = false; + } + *binds + } + /// A render on slot `k` with `binding` retired, after its `retire_binding`. If no other + /// epoch was bound and no recovery started since, the next render of the same VM may reuse + /// its epoch after a `completed` render; after a failed one it starts fresh. + /// Renders are bound, published and retired one at a time (`sizes::FLIGHTS` is 1, enforced + /// in `Engine::new`), so `keep[k]` always refers to the epoch the slot is bound to: + /// `owners[k]`. + pub(crate) fn retire_epoch(&mut self, k: usize, binding: u64, completed: bool) { + if self.binds.get(k) == Some(&binding) { + if let Some(keep) = self.keep.get_mut(k) { + *keep = completed; + } + } + } + /// Reuse nothing on slot `k` (its render was aborted). + pub(crate) fn forget(&mut self, k: usize) { + if let Some(keep) = self.keep.get_mut(k) { + *keep = false; + } + } + /// A firmware recovery started: no epoch bound so far is reused, also not by a render that + /// retires after it (its binding no longer matches); each slot's next render starts fresh. + pub(crate) fn invalidate(&mut self) { + for (binds, keep) in self.binds.iter_mut().zip(self.keep.iter_mut()) { + *binds = binds.wrapping_add(1); + *keep = false; } } pub(crate) fn retire_binding(&mut self, k: usize, epoch: &Arc) -> Result { @@ -275,16 +350,19 @@ impl Pools { pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { writeln!( f, - "pb: M4 private allocators blocks {} requests {} bad {}", + "pb: M4 private allocators blocks {} requests {} bad {} reused {} fresh {}", buffer::MAX_BLOCKS, self.stats.requests, - self.stats.bad + self.stats.bad, + self.stats.reused, + self.stats.fresh ) } } -/// One never-reinitialized PB manager installation. Even a same-VM command gets a fresh -/// manager and full InitBM; no host reset of exposed firmware cursors is required. +/// One never-reinitialized PB manager installation. Unless a same-VM command reuses its +/// slot's retired epoch, every command gets a fresh manager and full InitBM; no host reset of +/// exposed firmware cursors is required. pub(crate) struct PbEpoch(crate::cleanup::Deferred); impl core::ops::Deref for PbEpoch { type Target = PbEpochInner; @@ -339,18 +417,27 @@ impl PbEpoch { /// Seed only unpublished storage. A retry may choose another physical slot; after /// exposure neither the manager nor any of its firmware-mutated lists is reset. - pub(crate) fn prepare(&self, k: usize, heap: u64) -> Result { - if k >= 2 || self.exposed.load(Ordering::Acquire) { + pub(crate) fn prepare(&self, k: usize, heap: u64, heap_blocks: u32) -> Result { + if k >= 2 + || self.exposed.load(Ordering::Acquire) + || heap_blocks == 0 + || heap_blocks > buffer::MAX_BLOCKS + { return Err(EINVAL); } + // Only the backed part of the heap is named; the rest of the lists stays zero. + let pages = heap_blocks * buffer::PAGES_PER_BLOCK; write_records(&self.pages, buffer::MAX_PAGES as usize, |i| { - buffer::page_record(heap, i as u32).to_le_bytes() + let i = i as u32; + (if i < pages { buffer::page_record(heap, i) } else { 0 }).to_le_bytes() })?; write_records(&self.blocks, buffer::MAX_BLOCKS as usize, |i| { - u64::from(buffer::block_record(heap, i as u32)).to_le_bytes() + let b = i as u32; + u64::from(if b < heap_blocks { buffer::block_record(heap, b) } else { 0 }).to_le_bytes() })?; - self.ring.w32(0, buffer::MAX_BLOCKS)?; - self.ring.w32(4, buffer::MAX_BLOCKS)?; + let posted = super::params::pb_posted_blocks(heap_blocks); + self.ring.w32(0, posted)?; + self.ring.w32(4, posted)?; self.counter.w64(0, 1)?; self.manager.write( 0, @@ -361,6 +448,7 @@ impl PbEpoch { self.blocks.va, self.ring.va, self.counter.va, + heap_blocks, ), )?; self.assigned.store(k as u32, Ordering::Release); @@ -375,6 +463,10 @@ impl PbEpoch { pub(crate) fn expose(&self) { self.exposed.store(true, Ordering::Release); } + /// Never handed to the firmware: its storage may serve another render of its VM. + pub(crate) fn unexposed(&self) -> bool { + !self.exposed.load(Ordering::Acquire) + } } impl Firmware { diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index baf623b2722d7..2f156546ab307 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -1,7 +1,16 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Bounded two-owner displacement ledger. A completion alone never makes an M4 UMA owner -//! reusable: a distinct, fully retired owner must replace it in the same hardware slot. +//! Bounded displacement ledger of the retained owners of one hardware UMA slot. A completion +//! alone never makes an M4 UMA owner reusable: a later, fully retired publication must have +//! replaced it in the same hardware slot. +//! +//! The firmware runs one queue's commands strictly in order, each to its Finalize, so a +//! publication that retired started after every earlier one finished and displaced it. Owners +//! therefore retire in publication order and an owner is reusable once any owner published +//! after it retired. With `pipelined`, owners may be published while earlier ones are still +//! in flight (the compute queue); without it, publication stays serialized against every +//! owner (the render pass slots). +//! //! Core-only so the transition system is executable in host tests. #[derive(Copy, Clone, Debug, Eq, PartialEq)] @@ -33,13 +42,13 @@ pub(crate) struct Counts { } #[derive(Clone)] -pub(crate) struct Lifetime { - units: [Unit; 2], +pub(crate) struct Lifetime { + units: [Unit; N], sequence: u64, - last_owner: Option, + pipelined: bool, } -impl Lifetime { - pub(crate) const fn new() -> Self { +impl Lifetime { + pub(crate) const fn new(pipelined: bool) -> Self { let unit = Unit { state: State::Fresh, previous: State::Fresh, @@ -47,9 +56,9 @@ impl Lifetime { publication: 0, }; Self { - units: [unit; 2], + units: [unit; N], sequence: 0, - last_owner: None, + pipelined, } } #[allow(dead_code)] @@ -70,16 +79,23 @@ impl Lifetime { } counts } + /// Published owners. + pub(crate) fn published(&self) -> u32 { + self.units + .iter() + .filter(|u| u.state == State::Published) + .count() as u32 + } pub(crate) fn available(&self, k: usize) -> bool { let Some(u) = self.units.get(k) else { return false; }; match u.state { State::Fresh => true, - State::Retired => self.last_owner.is_some_and(|b| { - b != k - && self.units[b].state == State::Retired - && self.units[b].publication > u.publication + // A later publication retired: it started only after this owner finished, and + // its load displaced this owner from the hardware slot. + State::Retired => self.units.iter().enumerate().any(|(b, other)| { + b != k && other.state == State::Retired && other.publication > u.publication }), _ => false, } @@ -87,7 +103,11 @@ impl Lifetime { /// No amount of firmware progress can make a unit claimable. The caller must fail /// pending work rather than wait forever after abort/quarantine or sequence exhaustion. pub(crate) fn exhausted(&self) -> bool { - (0..2).all(|k| !self.available(k)) + self.exhausted_within(N) + } + /// [`Self::exhausted`] when only owners `0..n` exist. + pub(crate) fn exhausted_within(&self, n: usize) -> bool { + (0..n.min(N)).all(|k| !self.available(k)) && !self .units .iter() @@ -113,22 +133,30 @@ impl Lifetime { } } pub(crate) fn publish(&mut self, k: usize) -> bool { - if self.units[k].state != State::Preparing || self.sequence == u64::MAX { + if k >= N || self.units[k].state != State::Preparing || self.sequence == u64::MAX { return false; } - // Publication must be serialized against every owner of this hardware slot. - if self.units.iter().any(|u| u.state == State::Published) { + // Without pipelining, publication is serialized against every owner of the slot. + if !self.pipelined && self.units.iter().any(|u| u.state == State::Published) { return false; } self.sequence += 1; self.units[k].publication = self.sequence; self.units[k].state = State::Published; - self.last_owner = Some(k); true } - /// Called only after the caller has established complete, exact wire retirement. + /// Called only after the caller has established complete, exact wire retirement. Owners + /// retire in publication order: `k` must be the oldest published owner. pub(crate) fn retire(&mut self, k: usize) -> bool { - if self.units[k].state != State::Published || self.last_owner != Some(k) { + if k >= N || self.units[k].state != State::Published { + return false; + } + let publication = self.units[k].publication; + if self + .units + .iter() + .any(|u| u.state == State::Published && u.publication < publication) + { return false; } self.units[k].state = State::Retired; @@ -145,7 +173,7 @@ mod tests { use super::*; #[test] fn distinct_retired_displacement_is_required() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); assert!(l.publish(0)); assert!(!l.claim(0)); @@ -164,7 +192,7 @@ mod tests { } #[test] fn abort_does_not_recycle_or_authorize_displacement() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); assert!(l.publish(0)); assert!(l.retire(0)); @@ -185,7 +213,7 @@ mod tests { } #[test] fn preparation_cancel_preserves_retirement() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); l.cancel(0); assert_eq!(l.generation(0), 0); @@ -202,7 +230,7 @@ mod tests { } #[test] fn publication_is_serialized_and_command_count_is_not_binding_generation() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); assert!(l.publish(0)); assert!(l.claim(1)); @@ -219,4 +247,56 @@ mod tests { assert_eq!(l.generation(1), 1); assert!(l.claim(0)); } + #[test] + fn pipelined_owners_keep_n_minus_one_in_flight() { + let mut l = Lifetime::<4>::new(true); + // Fresh owners publish back to back. + for k in 0..4 { + assert!(l.claim(k)); + assert!(l.publish(k)); + } + assert_eq!(l.published(), 4); + // Out of order retirement is refused. + assert!(!l.retire(1)); + assert!(l.retire(0)); + // Owner 0 retired but nothing after it has: not displaced yet. + assert!(!l.claim(0)); + assert!(l.retire(1)); + assert!(l.claim(0)); // displaced by 1 + assert!(!l.claim(1)); // 2 still in flight + assert!(l.publish(0)); + assert!(l.retire(2)); + assert!(l.claim(1)); + assert!(l.publish(1)); + // Steady state: round robin with up to three in flight. + let mut next = 2; + for _ in 0..1000 { + let oldest = (0..4) + .filter(|&k| l.units[k].state == State::Published) + .min_by_key(|&k| l.units[k].publication) + .unwrap(); + assert!(l.retire(oldest)); + assert!(l.claim(next)); + assert!(l.publish(next)); + assert!(l.published() <= 3); + next = (next + 1) % 4; + } + } + #[test] + fn pipelined_newest_retired_owner_is_never_reusable() { + let mut l = Lifetime::<3>::new(true); + for k in 0..3 { + assert!(l.claim(k)); + assert!(l.publish(k)); + } + for k in 0..3 { + assert!(l.retire(k)); + } + assert!(l.available(0) && l.available(1)); + assert!(!l.available(2)); + assert!(l.claim(1)); + // 2 still proves 0 displaced although 1 is being prepared again. + assert!(l.available(0)); + assert!(!l.available(2)); + } } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 41da5b94c7c50..ada1946bb7983 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -55,6 +55,10 @@ pub(crate) struct QueueState { /// Exact successful firmware receipts, independently for render and compute. These /// survive aggregate-fence publication and never advance on aborted/failed commands. pub(crate) completed: [AtomicU64; 2], + /// Published command frontier per engine. The firmware runs the compute queue in + /// publication order, each command to its Finalize, so a compute command may follow its + /// published (not yet retired) compute predecessors. + pub(crate) published: [AtomicU64; 2], /// Owned-job counts at the queue's last 32 arrivals (compute horizon ahead), recorded by the /// engine when a job arrives. pub(crate) owned: [AtomicU32; 32], @@ -140,6 +144,7 @@ impl Queue { cancelled_at: [const { AtomicU64::new(0) }; 2], turn: AtomicU64::new(0), completed: [const { AtomicU64::new(0) }; 2], + published: [const { AtomicU64::new(0) }; 2], owned: [const { AtomicU32::new(0) }; 32], owned_index: AtomicU32::new(0), }, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index b0fc2ed96976c..18975b812e276 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -320,6 +320,9 @@ impl Firmware { } self.recovery.running = true; self.engine.frozen = true; + // A recovery may reset what the firmware keeps for a bound PB epoch, also one whose + // render was not affected: start the next render on each pass slot fresh. + self.pools.invalidate(); self.events.grow.clear(); // These frontiers must be captured before the host answers 2: the // firmware can force the stage target while aborting a work item. diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 77c47f0770492..63238572b27ee 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -13,13 +13,18 @@ use super::{ vm::VmState, }; use crate::mmu; -use core::sync::atomic::{AtomicU64, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ - new_mutex, + new_mutex, new_spinlock, prelude::*, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, SpinLock}, }; +/// Never-exposed PB epochs a VM keeps for its next renders. With PB epoch reuse most +/// renders never expose the epoch prepared for them; allocating and mapping a fresh one per +/// render submit costs far more than the render itself. +const SPARE_EPOCHS: usize = 4; + pub(crate) struct ComputeArena(crate::cleanup::Deferred); impl core::ops::Deref for ComputeArena { type Target = ComputeInner; @@ -34,17 +39,30 @@ pub(crate) struct ComputeInner { _bind: mmu::VmBind, _live: Arc, } +/// Compute units every VM gets with its first compute command; more are added +/// ([`Cache::prepare`]) once it submits compute back to back. +pub(crate) const BASE_COMPUTE_UNITS: usize = 2; + +/// Back-to-back compute submissions (each within [`BURST_GAP_NS`] of the previous) after +/// which a VM gets its extension units; a single submission with [`BURST_COMMANDS`] compute +/// commands qualifies at once. +const BURST_SUBMITS: u32 = 3; +const BURST_GAP_NS: u64 = 2_000_000; +const BURST_COMMANDS: usize = 3; + impl ComputeArena { + /// Units `units` (their index fixes their client addresses and hardware UMA slot). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + units: core::ops::Range, ) -> Result> { let mut objects = factory.objects(vm); - let mut compute = KVec::with_capacity(2, GFP_KERNEL)?; - for k in 0..2 { - compute.push(ComputeSlot::new(&mut objects, k)?, GFP_KERNEL)?; + let mut compute = KVec::with_capacity(units.len(), GFP_KERNEL)?; + for k in units { + compute.push(ComputeSlot::new(&mut objects, k as u64)?, GFP_KERNEL)?; } objects.finish_private()?; Ok(Arc::new( @@ -116,12 +134,23 @@ impl RenderArena { #[derive(Default)] struct Ready { compute: Option>, + /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. + compute_ext: Option>, render: Option>, + /// Last compute submission and the back-to-back run it continues. + last_compute_ns: u64, + burst: u32, } #[pin_data] pub(crate) struct Cache { #[pin] ready: Mutex, + /// Never-exposed epochs returned by retired jobs (at most [`SPARE_EPOCHS`]). Each holds + /// the VM, which holds this cache: [`Self::close`] breaks that cycle. + #[pin] + spares: SpinLock>>, + /// The VM's client closed: no arena or spare is kept here any more. + closed: AtomicBool, pub(crate) factory: Factory, bind: mmu::VmBind, live: Arc, @@ -134,24 +163,65 @@ impl Cache { live: Arc, ) -> Result> { let budget = super::budget::Budget::new()?; + let spares = KVec::with_capacity(SPARE_EPOCHS, GFP_KERNEL)?; Arc::pin_init( pin_init!(Self { ready <- new_mutex!(Ready::default(), "g16::resources"), + spares <- new_spinlock!(spares, "g16::spare_epochs"), + closed: AtomicBool::new(false), factory, bind, live, budget }), GFP_KERNEL, ) } - pub(crate) fn prepare(&self, vm: &Arc, commands: &[Command]) -> Result { - let compute = commands.iter().any(|c| matches!(c, Command::Compute(_))); + /// Returns a retired job's never-exposed epoch for the next renders. Any context. + fn give_back(&self, epoch: Arc) { + let mut spares = self.spares.lock(); + // Without room, or once the client closed, the epoch drops: its deferred cleanup + // unmaps it as before. + if !self.closed.load(Ordering::Acquire) { + let _ = spares.push_within_capacity(epoch); + } + } + + /// The VM's client closed. Lets go of the arenas and spare epochs: what jobs and the + /// hardware slots' last-owner leases still need, they hold themselves. + pub(crate) fn close(&self) { + let spares = { + let mut spares = self.spares.lock(); + self.closed.store(true, Ordering::Release); + core::mem::take(&mut *spares) + }; + drop(spares); + let ready = { + let mut ready = self.ready.lock(); + ( + ready.compute.take(), + ready.compute_ext.take(), + ready.render.take(), + ) + }; + drop(ready); + } + + pub(crate) fn prepare( + self: &Arc, + vm: &Arc, + commands: &[Command], + ) -> Result { + let computes = commands + .iter() + .filter(|c| matches!(c, Command::Compute(_))) + .count(); + let compute = computes != 0; let render_count = commands .iter() .filter(|c| matches!(c, Command::Render(_))) .count(); let render = render_count != 0; let mut epochs = super::budget::Budget::reserve(&self.budget, render_count.try_into()?)?; - let (compute, render) = { + let (compute, compute_ext, render) = { // Never held by publication, completion, recovery or fence signalling. let mut ready = self.ready.lock(); - if vm.status.get() != 0 || vm.vm.is_closed() { + if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { return Err(EIO); } if compute && ready.compute.is_none() { @@ -160,8 +230,34 @@ impl Cache { &self.bind, &vm.vm, &self.live, + 0..BASE_COMPUTE_UNITS, )?); } + if compute { + // SAFETY: ktime_get has no preconditions. + let now = unsafe { kernel::bindings::ktime_get() } as u64; + ready.burst = if now.wrapping_sub(ready.last_compute_ns) < BURST_GAP_NS { + ready.burst.saturating_add(1) + } else { + 0 + }; + ready.last_compute_ns = now; + let units = super::params::compute_units(); + if ready.compute_ext.is_none() + && units > BASE_COMPUTE_UNITS + && (ready.burst >= BURST_SUBMITS || computes >= BURST_COMMANDS) + { + // Best effort: without them the VM keeps one command in flight. + ready.compute_ext = ComputeArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + BASE_COMPUTE_UNITS..units, + ) + .ok(); + } + } if render && ready.render.is_none() { ready.render = Some(RenderArena::new( &self.factory, @@ -176,6 +272,7 @@ impl Cache { } ( if compute { ready.compute.clone() } else { None }, + if compute { ready.compute_ext.clone() } else { None }, if render { ready.render.clone() } else { None }, ) }; @@ -183,7 +280,13 @@ impl Cache { for command in commands { pb.push( if matches!(command, Command::Render(_)) { - Some(PbEpoch::new(&self.factory, vm, epochs.take()?)?) + // A spare keeps the budget permit it was created with; the reservation + // returns the unused credit when it drops. + let spare = self.spares.lock().pop(); + Some(match spare { + Some(epoch) if epoch.unexposed() => epoch, + _ => PbEpoch::new(&self.factory, vm, epochs.take()?)?, + }) } else { None }, @@ -195,8 +298,10 @@ impl Cache { } Ok(Prepared { compute, + compute_ext, render, pb, + cache: Some(self.clone()), }) } } @@ -204,13 +309,60 @@ impl Cache { /// Immutable references carried by an accepted job. No fallible lazy work in the engine. pub(crate) struct Prepared { pub(crate) compute: Option>, + /// The VM's extension compute units when the job was prepared. + pub(crate) compute_ext: Option>, pub(crate) render: Option>, pb: KVec>>, + /// The VM cache that unused epochs return to. + cache: Option>, +} + +impl Drop for Prepared { + fn drop(&mut self) { + let Some(cache) = self.cache.take() else { + return; + }; + for epoch in self.pb.iter_mut().filter_map(Option::take) { + if epoch.unexposed() { + cache.give_back(epoch); + } + } + } } impl Prepared { pub(crate) fn compute(&self) -> Result<&ComputeArena> { self.compute.as_deref().ok_or(EINVAL) } + /// Compute units this job can use. + pub(crate) fn compute_units(&self) -> Result { + Ok(self.compute()?.compute.len() + + self.compute_ext.as_deref().map_or(0, |e| e.compute.len())) + } + /// The arena holding compute unit `k`. + pub(crate) fn compute_arena(&self, k: usize) -> Option> { + let base = self.compute.as_ref()?; + if k < base.compute.len() { + Some(base.clone()) + } else { + self.compute_ext.clone() + } + } + /// The render arena. + pub(crate) fn render_arena(&self) -> Option> { + self.render.clone() + } + /// Compute unit `k`: the VM's base units, then its extension units. + pub(crate) fn compute_unit(&self, k: usize) -> Result<&ComputeSlot> { + let base = &self.compute()?.compute; + match base.get(k) { + Some(unit) => Ok(unit), + None => self + .compute_ext + .as_deref() + .and_then(|e| e.compute.get(k - base.len())) + .ok_or(EINVAL), + } + } pub(crate) fn render(&self) -> Result<&RenderArena> { self.render.as_deref().ok_or(EINVAL) } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index b4a48ed2907ae..f04d6add674f8 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -2,8 +2,9 @@ //! Per-VM M4 command storage and device-wide displacement lifetime tracking. //! -//! Both compute units alternate hardware UMA slot 1; both render units alternate slot 33. -//! Firmware retirement and a later distinct retired owner are both required before reuse. +//! Each compute unit owns its own hardware UMA slot (`COMPUTE_UMA_SLOT + index`) and may be in +//! flight together, in publication order; both render units alternate slot 33, one at a time. Firmware retirement and a later +//! distinct retired owner are both required before reuse. //! Private backing and old VM leases survive until a distinct replacement fully retires. //! Aborted storage remains mapped and quarantined. Pool cursors are never scrubbed. @@ -370,21 +371,35 @@ pub(crate) struct SlotStats { pub(crate) pass_scrubs: u64, } +/// Displacement ledger and VM leases of the compute units (see [`Slots`]). +pub(crate) struct ComputeOwners { + lifetime: Lifetime<{ sizes::COMPUTE_UNITS }>, + owner: [Option>; sizes::COMPUTE_UNITS], + pending_retarget: [Option; sizes::COMPUTE_UNITS], + pending_owner: [Option>; sizes::COMPUTE_UNITS], + /// The arena holding each owner's unit: the firmware may still write the unit's + /// descriptor when a later owner displaces it, after its VM's client closed. + arena: [Option>; sizes::COMPUTE_UNITS], + pending_arena: [Option>; sizes::COMPUTE_UNITS], +} + pub(crate) struct Slots { pub(crate) cursor: u32, pub(crate) pass_busy: u32, pub(crate) pass_cursor: u32, pub(crate) stats: SlotStats, - compute_lifetime: Lifetime, - pass_lifetime: Lifetime, + /// The compute owners, on the heap: `Firmware` (and so `Slots`) is built on the probe's + /// stack, which has no room for it. + compute: KBox, + pass_lifetime: Lifetime<2>, // Last-owner leases remain bound through retirement and displacement. Replaced only // when the displaced unit is safely rebound to a new publication. - compute_owner: [Option>; 2], pass_owner: [Option>; 2], - pending_compute_retarget: [Option; 2], pending_pass_retarget: [Option; 2], - pending_compute_owner: [Option>; 2], pending_pass_owner: [Option>; 2], + /// The render arena of each pass slot's owner (see [`ComputeOwners::arena`]). + pass_arena: [Option>; 2], + pending_pass_arena: [Option>; 2], } impl Slots { pub(crate) fn new() -> Result { @@ -393,14 +408,23 @@ impl Slots { pass_busy: 0, pass_cursor: 0, stats: SlotStats::default(), - compute_lifetime: Lifetime::new(), - pass_lifetime: Lifetime::new(), - compute_owner: [None, None], + compute: KBox::new( + ComputeOwners { + lifetime: Lifetime::new(true), + owner: [const { None }; sizes::COMPUTE_UNITS], + pending_retarget: [None; sizes::COMPUTE_UNITS], + pending_owner: [const { None }; sizes::COMPUTE_UNITS], + arena: [const { None }; sizes::COMPUTE_UNITS], + pending_arena: [const { None }; sizes::COMPUTE_UNITS], + }, + GFP_KERNEL, + )?, + pass_lifetime: Lifetime::new(false), pass_owner: [None, None], - pending_compute_retarget: [None, None], pending_pass_retarget: [None, None], - pending_compute_owner: [None, None], pending_pass_owner: [None, None], + pass_arena: [None, None], + pending_pass_arena: [None, None], }) } pub(crate) fn init(&self) -> Result { @@ -408,10 +432,10 @@ impl Slots { } #[allow(dead_code)] pub(crate) fn compute_generation(&self, k: usize) -> Result { - if k >= 2 { + if k >= sizes::COMPUTE_UNITS { return Err(EINVAL); } - Ok(self.compute_lifetime.generation(k)) + Ok(self.compute.lifetime.generation(k)) } #[allow(dead_code)] pub(crate) fn pass_generation(&self, k: usize) -> Result { @@ -421,39 +445,57 @@ impl Slots { Ok(self.pass_lifetime.generation(k)) } pub(crate) fn compute_exhausted(&self) -> bool { - self.compute_lifetime.exhausted() + // Ledger indices above the most units a VM gets never have an owner. + self.compute + .lifetime + .exhausted_within(super::params::compute_units()) + } + /// Whether none of the first `n` compute units (a VM's own) can ever be claimed again. + pub(crate) fn compute_exhausted_within(&self, n: usize) -> bool { + self.compute.lifetime.exhausted_within(n) } pub(crate) fn render_exhausted(&self) -> bool { self.pass_lifetime.exhausted() } pub(crate) fn lifetime_counts(&self) -> [super::pools::lifetime::Counts; 2] { - [self.compute_lifetime.counts(), self.pass_lifetime.counts()] + [self.compute.lifetime.counts(), self.pass_lifetime.counts()] + } + /// Whether one of the first `n` compute units can be claimed now. + pub(crate) fn compute_available(&self, n: usize) -> bool { + (0..n.min(sizes::COMPUTE_UNITS)).any(|k| self.compute.lifetime.available(k)) + } + /// Compute units published and not yet retired. + pub(crate) fn compute_published(&self) -> u32 { + self.compute.lifetime.published() } #[allow(dead_code)] pub(crate) fn free_compute(&self) -> u32 { - (0..2) - .filter(|&k| self.compute_lifetime.available(k)) + (0..super::params::compute_units()) + .filter(|&k| self.compute.lifetime.available(k)) .count() as u32 } pub(crate) fn claim_compute( &mut self, - arena: &super::resources::ComputeArena, + units: &super::resources::Prepared, f: &mut Claims, _j: u32, ) -> Result> { if f.slot_count != 0 { return Ok(None); } - for i in 0..2 { - let k = (self.cursor as usize + i) % 2; - if self.compute_lifetime.claim(k) { - if let Err(e) = arena.compute[k].scrub() { - self.compute_lifetime.cancel(k); + // Round robin over this VM's units: the next one in publication order is the + // oldest, the first to be displaced by a later retired publication. + let n = units.compute_units()?.min(sizes::COMPUTE_UNITS); + for i in 0..n { + let k = (self.cursor as usize + i) % n; + if self.compute.lifetime.claim(k) { + if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub()) { + self.compute.lifetime.cancel(k); return Err(e); } f.slot[0] = k as u32; f.slot_count = 1; - self.cursor = (1 - k) as u32; + self.cursor = ((k + 1) % n) as u32; return Ok(Some(k)); } } @@ -522,7 +564,7 @@ impl Slots { /// Full wire retirement is a separate condition for hardware qualification. pub(crate) fn note_published(&mut self, f: &Claims) { for &k in &f.slot[..f.slot_count as usize] { - if let Some(proof) = self.pending_compute_retarget[k as usize].take() { + if let Some(proof) = self.compute.pending_retarget[k as usize].take() { self.stats.cross_vm_retargets[0] = self.stats.cross_vm_retargets[0].saturating_add(1); self.stats.last_retarget[0] = proof; @@ -543,17 +585,19 @@ impl Slots { /// A previous lease is replaced only after the new publication fully retires. pub(crate) fn hold_vm(&mut self, f: &Claims, vm: &Arc) -> Result { if f.slot_count > 2 - || f.slot[..f.slot_count as usize].iter().any(|&k| k >= 2) + || f.slot[..f.slot_count as usize] + .iter() + .any(|&k| k as usize >= sizes::COMPUTE_UNITS) || f.pass_mask & !3 != 0 { return Err(EINVAL); } for &k in &f.slot[..f.slot_count as usize] { let k = k as usize; - self.pending_compute_retarget[k] = self.compute_owner[k] + self.compute.pending_retarget[k] = self.compute.owner[k] .as_ref() .and_then(|old| Self::vm_retarget(k, old, vm)); - self.pending_compute_owner[k] = Some(vm.clone()); + self.compute.pending_owner[k] = Some(vm.clone()); } for k in 0..2 { if f.pass_mask & (1 << k) != 0 { @@ -566,10 +610,25 @@ impl Slots { Ok(()) } + /// With [`Self::hold_vm`]: the claimed units' arenas, held with their VM leases. The VM's + /// own cache lets go of its arenas when its client closes. + pub(crate) fn hold_arenas(&mut self, f: &Claims, resources: &super::resources::Prepared) { + for &k in &f.slot[..(f.slot_count as usize).min(f.slot.len())] { + if let Some(cell) = self.compute.pending_arena.get_mut(k as usize) { + *cell = resources.compute_arena(k as usize); + } + } + for k in 0..2 { + if f.pass_mask & (1 << k) != 0 { + self.pending_pass_arena[k] = resources.render_arena(); + } + } + } + /// Reserve the actual same-slot publication. Call before producers become visible. pub(crate) fn publish(&mut self, f: &Claims) -> Result { // Validate on a private copy so a failure changes no ownership. - let mut c = self.compute_lifetime.clone(); + let mut c = self.compute.lifetime.clone(); let mut p = self.pass_lifetime.clone(); for &k in &f.slot[..f.slot_count as usize] { if !c.publish(k as usize) { @@ -581,13 +640,13 @@ impl Slots { return Err(EBUSY); } } - self.compute_lifetime = c; + self.compute.lifetime = c; self.pass_lifetime = p; Ok(()) } /// Full wire retirement is a precondition; completion fences alone are insufficient. pub(crate) fn retire(&mut self, f: &mut Claims) -> Result { - let mut c = self.compute_lifetime.clone(); + let mut c = self.compute.lifetime.clone(); let mut p = self.pass_lifetime.clone(); for &k in &f.slot[..f.slot_count as usize] { if !c.retire(k as usize) { @@ -599,14 +658,16 @@ impl Slots { return Err(EINVAL); } } - self.compute_lifetime = c; + self.compute.lifetime = c; self.pass_lifetime = p; for &k in &f.slot[..f.slot_count as usize] { - self.compute_owner[k as usize] = self.pending_compute_owner[k as usize].take(); + self.compute.owner[k as usize] = self.compute.pending_owner[k as usize].take(); + self.compute.arena[k as usize] = self.compute.pending_arena[k as usize].take(); } for k in 0..2 { if f.pass_mask & (1 << k) != 0 { self.pass_owner[k] = self.pending_pass_owner[k].take(); + self.pass_arena[k] = self.pending_pass_arena[k].take(); } } self.pass_busy &= !f.pass_mask; @@ -617,8 +678,8 @@ impl Slots { } pub(crate) fn quarantine(&mut self, f: &mut Claims) { for &k in &f.slot[..f.slot_count as usize] { - self.compute_lifetime.quarantine(k as usize); - self.pending_compute_retarget[k as usize] = None; + self.compute.lifetime.quarantine(k as usize); + self.compute.pending_retarget[k as usize] = None; } for k in 0..2 { if f.pass_mask & (1 << k) != 0 { @@ -634,15 +695,17 @@ impl Slots { /// Cancels preparation only. Published units require retire() or quarantine(). pub(crate) fn release(&mut self, f: &mut Claims) { for &k in &f.slot[..f.slot_count as usize] { - self.compute_lifetime.cancel(k as usize); - self.pending_compute_retarget[k as usize] = None; - self.pending_compute_owner[k as usize] = None; + self.compute.lifetime.cancel(k as usize); + self.compute.pending_retarget[k as usize] = None; + self.compute.pending_owner[k as usize] = None; + self.compute.pending_arena[k as usize] = None; } for k in 0..2 { if f.pass_mask & (1 << k) != 0 { self.pass_lifetime.cancel(k); self.pending_pass_retarget[k] = None; self.pending_pass_owner[k] = None; + self.pending_pass_arena[k] = None; } } self.pass_busy &= !f.pass_mask; diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 5bb4f434454cc..0367a4421554c 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -254,6 +254,11 @@ impl Registry { let index = vms.iter().position(|state| state.id == id); index.and_then(|index| vms.remove(index).ok()) }; + // Arenas still reachable by firmware stay with the slot leases and jobs that hold + // them; the rest (and the spare epochs, which hold the VM) go now. + if let Some(cache) = state.as_ref().and_then(|state| state.resources.as_ref()) { + cache.close(); + } drop(state); } @@ -268,8 +273,12 @@ impl Registry { let Some(closed) = closed else { break; }; - // No allocation while holding the registry lock, which fail_all() also needs. - // Final VM destruction is deferred independently of this caller's locks. + // Break the spare-epoch cycle before releasing the registry reference, matching + // close(). No allocation while holding the registry lock, which fail_all() also + // needs. Final VM destruction is deferred independently of this caller's locks. + if let Some(cache) = closed.resources.as_ref() { + cache.close(); + } drop(closed); } } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index a048447b1436a..01e6176bdea5e 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -44,7 +44,11 @@ def module(text, name): pub const ETIMEDOUT:Error=Error(110);pub const ERESTARTSYS:Error=Error(512); pub const GFP_KERNEL:u32=0; pub type Result = std::result::Result; -pub mod prelude {pub use crate::{Result,KVec,GFP_KERNEL,EINVAL,EAGAIN,E2BIG,EBUSY,EOVERFLOW,EIO,ETIMEDOUT,ERESTARTSYS};} +pub mod prelude {pub use crate::{Result,KVec,KBox,GFP_KERNEL,EINVAL,EAGAIN,E2BIG,EBUSY,EOVERFLOW,EIO,ETIMEDOUT,ERESTARTSYS};} +pub struct KBox(Box); +implKBox{pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))}} +implstd::ops::Deref for KBox{type Target=T;fn deref(&self)->&T{&self.0}} +implstd::ops::DerefMut for KBox{fn deref_mut(&mut self)->&mut T{&mut self.0}} pub struct KVec(Vec); implKVec{pub fn new()->Self{Self(Vec::new())} pub fn with_capacity(n:usize,_:u32)->Result{Ok(Self(Vec::with_capacity(n)))} pub fn push(&mut self,x:T,_:u32)->Result{self.0.push(x);Ok(())}} implstd::ops::Deref for KVec{type Target=Vec;fn deref(&self)->&Vec{&self.0}} @@ -68,7 +72,7 @@ def module(text, name): } pub struct Arc{inner:std::sync::Arc} - implArc{pub fn new(v:T,_:u32)->crate::Result{Ok(Self{inner:std::sync::Arc::new(v)})}pub fn strong_count(v:&Self)->usize{std::sync::Arc::strong_count(&v.inner)}} + implArc{pub fn new(v:T,_:u32)->crate::Result{Ok(Self{inner:std::sync::Arc::new(v)})}pub fn strong_count(v:&Self)->usize{std::sync::Arc::strong_count(&v.inner)}pub fn ptr_eq(a:&Self,b:&Self)->bool{std::sync::Arc::ptr_eq(&a.inner,&b.inner)}} implClone for Arc{fn clone(&self)->Self{Self{inner:self.inner.clone()}}} implstd::ops::Deref for Arc{type Target=T;fn deref(&self)->&T{&self.inner}} pub mod aref {pub struct ARef(T);impl From<&crate::device::Device>for ARef{fn from(v:&crate::device::Device)->Self{Self(v.clone())}}} @@ -143,10 +147,20 @@ def module(text, name): pub mod resources { use core::sync::atomic::{AtomicU64,Ordering};use crate::*; pub struct ComputeArena{pub compute:KVec} + // A job's compute units; here one arena. + pub type Prepared=ComputeArena; + impl ComputeArena{ + pub fn compute_units(&self)->Result{Ok(self.compute.len())} + pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{self.compute.get(k).ok_or(EINVAL)} + pub fn compute_arena(&self,_k:usize)->Option>{None} + pub fn render_arena(&self)->Option>{None} + } pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;2],pub tilemap_dirty:[AtomicU64;2]} impl RenderArena{ __SET_DIRTY__ } } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} + // Arenas here have the two base units. + pub mod params {pub fn compute_units()->usize{2}pub fn pb_heap_blocks()->u32{2048}pub fn pb_posted_blocks(heap:u32)->u32{heap}} pub struct Events{pub grow:crate::KVec<[u32;18]>} pub struct Firmware{pub pools:pools::Pools,pub events:Events} pub mod budget{__BUDGET__} @@ -212,7 +226,8 @@ def module(text, name): aliases.push((0x1000000000,0x1000010000)); // Per-VM context store. aliases.sort();for a in aliases.windows(2){assert!(a[0].1<=a[1].0,"overlap {:x?} {:x?}",a[0],a[1]);} for (k,s) in arena.compute.compute.iter().enumerate(){assert_eq!(s.work.lower_gva.unwrap()&0x3fff,0);assert_eq!(s.work.size,0x2000);assert_eq!(s.pool.size,0x2000000);assert_eq!(s.pool_state.size,0x20000);assert_eq!(s.page_list.size,0x4000);assert_eq!(s.context_store.size,0x40000);assert_eq!(s.pool_state.r32(0).unwrap()as u64 |((s.pool_state.r32(4).unwrap()as u64)<<32),s.pool.gva.unwrap());assert_eq!(pools.allocator_refs_for(k).unwrap().parameter_id,k as u32);} - assert_eq!(aliases.len(),43); + // One PB heap per VM, shared by both render allocators. + assert_eq!(aliases.len(),42); } #[test]fn work_has_kernel_lower_alias_without_application_alias(){ let mut o=Objects::new();let slots=Slots::new().unwrap();let arena=arenas(&mut o); @@ -362,10 +377,10 @@ def module(text, name): #[test]fn pb_installations_are_fresh_and_exposed_records_cannot_be_reinitialized(){ let vm=vm(1);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); let a=g16::pools::PbEpoch::new(&factory,&vm,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); - a.prepare(0,0x70c0000000).unwrap();a.check_assignment(0).unwrap();a.expose(); + a.prepare(0,0x70c0000000,2048).unwrap();a.check_assignment(0).unwrap();a.expose(); a.manager.w64(0xb0,0x123456789abcdef0).unwrap();let saved=a.manager.snapshot(); - assert_eq!(a.prepare(0,0x70c0000000),Err(EINVAL));assert_eq!(saved,a.manager.snapshot()); - let b=g16::pools::PbEpoch::new(&factory,&vm,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap();b.prepare(0,0x70c0000000).unwrap(); + assert_eq!(a.prepare(0,0x70c0000000,2048),Err(EINVAL));assert_eq!(saved,a.manager.snapshot()); + let b=g16::pools::PbEpoch::new(&factory,&vm,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap();b.prepare(0,0x70c0000000,2048).unwrap(); assert!(!std::ptr::eq(&a.manager.data,&b.manager.data)); assert_eq!(b.manager.class,g16::object::Class::Fw);assert_eq!(b.manager.gva,None); let mut slots=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); @@ -373,6 +388,27 @@ def module(text, name): b.check_assignment(0).unwrap();b.expose();assert_eq!(sync::Arc::strong_count(&a),2); slots.retire_binding(0,&b).unwrap();assert_eq!(sync::Arc::strong_count(&a),1); } + #[test]fn pb_reuse_needs_the_same_binding_vm_and_a_completed_render_and_holds_nothing(){ + let one=vm(1);let two=vm(2);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let a=g16::pools::PbEpoch::new(&factory,&one,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + a.prepare(0,0x70c0000000,2048).unwrap();a.check_assignment(0).unwrap();a.expose(); + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let n=p.bind(0,false);p.retire_binding(0,&a).unwrap();p.retire_epoch(0,n,true); + assert_eq!(sync::Arc::strong_count(&a),2,"only the owner lease"); + let r=p.reusable(0,&one).unwrap();assert!(sync::Arc::ptr_eq(&r,&a));drop(r); + assert_eq!(sync::Arc::strong_count(&a),2); + assert!(p.reusable(0,&two).is_none(),"another VM");assert!(p.reusable(1,&one).is_none(),"another slot"); + assert_eq!(p.bind(0,true),n);p.retire_epoch(0,n,true);assert!(p.reusable(0,&one).is_some()); + p.retire_epoch(0,n,false);assert!(p.reusable(0,&one).is_none(),"failed render"); + p.retire_epoch(0,n,true);p.forget(0);assert!(p.reusable(0,&one).is_none(),"aborted render"); + let m=p.bind(0,false);assert_ne!(m,n);p.retire_epoch(0,n,true); + assert!(p.reusable(0,&one).is_none(),"a stale binding after a fresh one"); + p.retire_epoch(0,m,true);assert!(p.reusable(0,&one).is_some()); + p.invalidate();assert!(p.reusable(0,&one).is_none(),"recovery"); + p.retire_epoch(0,m,true);assert!(p.reusable(0,&one).is_none(),"a render retiring after recovery"); + assert_eq!(p.bind(0,true),m.wrapping_add(1)); + assert_eq!(sync::Arc::strong_count(&a),2); + } } ''' diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py index add96b48bb335..96d3238471635 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py @@ -22,8 +22,9 @@ def item(marker): mod hw{pub mod sizes{pub const MAX_VMS:u32=63;}} mod module_parameters{pub struct Param;impl Param{pub fn value(&self)->u32{0}}pub static robust_isolation:Param=Param;} mod types{pub struct ScopeGuard(Option);implScopeGuard{pub fn new(f:F)->Self{Self(Some(f))}pub fn dismiss(mut self){self.0.take();}}implDrop for ScopeGuard{fn drop(&mut self){if let Some(f)=self.0.take(){f()}}}} -struct Handle;impl Handle{fn is_closed(&self)->bool{false}} -struct VmState{id:u64,vm:Handle,drops:Arc}impl Drop for VmState{fn drop(&mut self){self.drops.fetch_add(1,Ordering::AcqRel);}} +struct Handle(std::sync::atomic::AtomicBool);impl Handle{fn open()->Self{Self(std::sync::atomic::AtomicBool::new(false))}fn mark_closed(&self){self.0.store(true,Ordering::Release);}fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)}} +struct Cache{closes:AtomicU32,spares:StdMutex>>}impl Cache{fn new()->Self{Self{closes:AtomicU32::new(0),spares:StdMutex::new(Vec::new())}}fn close(&self){self.closes.fetch_add(1,Ordering::AcqRel);let spares=std::mem::take(&mut *self.spares.lock().unwrap());drop(spares);}} +struct VmState{id:u64,vm:Handle,drops:Arc,resources:Option>}impl Drop for VmState{fn drop(&mut self){self.drops.fetch_add(1,Ordering::AcqRel);}} __REGISTRY__ struct Reservation<'a>(Option<&'a Registry>,u64); __RESERVATION_DROP__ @@ -46,12 +47,28 @@ def item(marker): } #[test]fn close_releases_registry_owner_without_another_vm_create(){ let r=Registry::new_test();let drops=Arc::new(AtomicU32::new(0)); - let state=Arc::new(VmState{id:1,vm:Handle,drops:drops.clone()});r.vms.lock().push(state.clone(),0).unwrap(); + let cache=Arc::new(Cache::new()); + let state=Arc::new(VmState{id:1,vm:Handle::open(),drops:drops.clone(),resources:Some(cache.clone())});r.vms.lock().push(state.clone(),0).unwrap(); r.close(1);assert!(r.vms.lock().is_empty());assert_eq!(drops.load(Ordering::Acquire),0); + // The client's close lets the VM's cache drop its arenas while other owners hold the VM. + assert_eq!(cache.closes.load(Ordering::Acquire),1); drop(state);assert_eq!(drops.load(Ordering::Acquire),1); - r.vms.lock().push(Arc::new(VmState{id:2,vm:Handle,drops:drops.clone()}),0).unwrap(); + r.vms.lock().push(Arc::new(VmState{id:2,vm:Handle::open(),drops:drops.clone(),resources:None}),0).unwrap(); r.close(2);assert_eq!(drops.load(Ordering::Acquire),2); } +#[test]fn prune_closes_cache_and_breaks_spare_epoch_cycle(){ + let r=Registry::new_test();let drops=Arc::new(AtomicU32::new(0)); + let cache=Arc::new(Cache::new()); + let state=Arc::new(VmState{id:1,vm:Handle::open(),drops:drops.clone(),resources:Some(cache.clone())}); + // Simulate a spare PB epoch inside Cache holding a strong reference back to VmState. + cache.spares.lock().unwrap().push(state.clone()); + state.vm.mark_closed(); + r.vms.lock().push(state,0).unwrap(); + r.prune(); + assert!(r.vms.lock().is_empty()); + assert_eq!(cache.closes.load(Ordering::Acquire),1); + assert_eq!(drops.load(Ordering::Acquire),1); +} ''' for tag,marker in [('REGISTRY','pub(crate) struct Registry'),('RESERVATION_DROP',"impl Drop for Reservation<'_>"),('RESERVE','fn reserve(&self, file_id:'),('RELEASE','fn release(&self, file_id:'),('CLOSE','pub(crate) fn close(&self, id:'),('PRUNE','fn prune(&self)')]: source=source.replace('__'+tag+'__',item(marker).replace(' #[pin]\n','')) From b0b5e93eb0660637b1165d8681354966c88ea656 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 13:01:08 -0500 Subject: [PATCH 04/19] drm/asahi: g16: run the M4 GPU on 26B123 firmware with ADT config and idle power-off Support the 26B123 G16 GPU firmware (also shipped in 26B131) while leaving 25G83 byte-for-byte unchanged. Firmware selection keys strictly on the boot loader's handoff fields and loaded TEXT digest, failing closed on unknown builds. Firmware layout, ABI, and ADT derivation: - Add V25G83/V26B123 layout tables for InitData, device-control opcodes, queue info, and TA/FS/compute work records, with compile-time layout_fits() bounds and collision checks. - Set POWER_PERFORMANCE +0xa4 = 1 (required power-up state selector) with no undocumented static InitData policy words. - Derive 26B123 power sampling (+4/+8, +0x2b48/+0x2bbc/+0x2c10) and the average-power IIR filter (+0x29e4..+0x29f8) from /arm-io/sgx gpu-pwr-sample-period-aic-clks, CNTFRQ_EL0, and /arm-io/pmgr/clpc cpu-avg-limiter-input-tc; derive the low-peak (PPM) limiter filter and PI gains (+0xa80..+0xae0) from cpu-lowpeak-limiter-{input-tc,ki,kp} and gpu-power-sample-period (65536.0 PI integrator clamp at +0xaa8). Fail closed with EINVAL when any required ADT property is missing or 0. - Read coredump-copy-buffer from /arm-io/gfx-asc/iop-gfx-nub in the preserved ADT to size InitData MAIN +0xfa8 and the 26B123 host crash-log buffer (failing closed when absent or invalid). Start, idle power-off, and runtime: - Admit 26B123 firmware-owned page tables and perform the PPL magic handshake, clearing handoff +8 before RUN and returning ETIMEDOUT if the firmware answer does not arrive. - Start 26B123 without a PMP AGX vote (enabling GFXCAXI2AF and leaving loaded DATA to the firmware), hand over the host crash-log buffer before AP power-on, and run the standard boot NOP + IMPORT_GLOBALS + START sequence while accepting a pending InitData scheduler request. - Publish the RETENTION table at RUNTIME +0x2c8 (leaving MAIN +0xfa0 zero) so 26B123 can power the GPU down when idle, and guard all SGX MMIO reads/writes (engine busy/fault state, pstate(), and runtime set_generation()) inside Session::while_powered() under the PPL lock. - Attempt all three Globals ceiling selectors without short-circuiting in floor_power() at fail-stop, drain all receive rings per pass, read the 26B123 queue-info busy flag at +0x54, read compute work ticks from compute::Layout::work_ticks with a tear-free hi/lo/hi loop, and check the session once per poll pass plus before publish_checked(). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/adt.rs | 45 +- drivers/gpu/drm/asahi/g16/adt/perf.rs | 77 ++ drivers/gpu/drm/asahi/g16/boot.rs | 413 +++++++-- drivers/gpu/drm/asahi/g16/channel.rs | 76 +- drivers/gpu/drm/asahi/g16/encode.rs | 10 +- drivers/gpu/drm/asahi/g16/encode/compute.rs | 59 +- drivers/gpu/drm/asahi/g16/encode/render.rs | 70 +- drivers/gpu/drm/asahi/g16/engine.rs | 36 +- drivers/gpu/drm/asahi/g16/fw/channels.rs | 30 +- drivers/gpu/drm/asahi/g16/fw/graph.rs | 63 +- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 893 +++++++++++++++++-- drivers/gpu/drm/asahi/g16/fw/mod.rs | 57 +- drivers/gpu/drm/asahi/g16/fw/work.rs | 74 ++ drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 48 + drivers/gpu/drm/asahi/g16/glue.c | 12 + drivers/gpu/drm/asahi/g16/glue.h | 7 + drivers/gpu/drm/asahi/g16/graph.rs | 15 +- drivers/gpu/drm/asahi/g16/hw.rs | 340 ++++++- drivers/gpu/drm/asahi/g16/initdata.rs | 127 ++- drivers/gpu/drm/asahi/g16/object.rs | 7 +- drivers/gpu/drm/asahi/g16/poll.rs | 84 +- drivers/gpu/drm/asahi/g16/power.rs | 15 +- drivers/gpu/drm/asahi/g16/recovery.rs | 91 +- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 10 +- drivers/gpu/drm/asahi/g16/regs.rs | 113 ++- drivers/gpu/drm/asahi/g16/uat.rs | 100 ++- drivers/gpu/drm/asahi/timestamp.rs | 8 + 27 files changed, 2510 insertions(+), 370 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g16/glue.h diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index 804703b19cecc..d885732c02194 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -24,6 +24,8 @@ pub(crate) struct GpuAdt { pub(crate) text: Range, pub(crate) data: Range, pub(crate) performance: perf::Source, + /// The firmware layout the boot loader's handoff describes. + pub(crate) layout: &'static hw::FwLayout, } /// Find the one original-ADT phram export, with explicit 64-bit reservation cells. @@ -118,18 +120,44 @@ fn performance_source(regions: &[Range]) -> Result<(KVVec, u64)> { Ok((copy?, start)) } -/// Validates the FDT contract and returns the reserved physical regions, read-only. -pub(crate) fn read(dev: &device::Device) -> Result { +/// The boot loader's handoff for the loaded firmware: its version, segment VAs and flags. +fn handoff(dev: &device::Device) -> Result<(u32, KVec, KVec)> { let node = dev.of_node().ok_or(EINVAL)?; let version: u32 = node.get_property(c_str!("apple,g16-handoff-version"))?; let vas: KVec = node.get_property(c_str!("apple,firmware-segment-vas"))?; let flags: KVec = node.get_property(c_str!("apple,firmware-segment-flags"))?; + Ok((version, vas, flags)) +} + +/// The firmware layout the boot loader's handoff describes, if it describes a known one. +pub(crate) fn layout(dev: &device::Device) -> Option<&'static hw::FwLayout> { + let (version, vas, flags) = handoff(dev).ok()?; + hw::FW_LAYOUTS + .iter() + .copied() + .find(|layout| layout.matches(version, &vas, &flags)) +} + +/// Validates the FDT contract and returns the reserved physical regions, read-only. +pub(crate) fn read(dev: &device::Device) -> Result { + let node = dev.of_node().ok_or(EINVAL)?; + let (version, vas, flags) = handoff(dev)?; let names: KVec = node.get_property(c_str!("memory-region-names"))?; let phandles: KVec = node.get_property(c_str!("memory-region"))?; - if version != 1 - || vas.as_slice() != [hw::UPPER, hw::UPPER + 0x60000] - || flags.as_slice() != [1, 0] - || phandles.len() != 6 + let layout = hw::FW_LAYOUTS + .iter() + .copied() + .find(|layout| layout.matches(version, &vas, &flags)); + let Some(layout) = layout else { + dev_err!( + dev, + "G16: unsupported boot-loader handoff (version {}, {} segments)\n", + version, + vas.len() + ); + return Err(EINVAL); + }; + if phandles.len() != 6 || names.as_slice() != b"ttbs\0pagetables\0handoff\0shared-l2\0fw-text\0fw-data\0" { dev_err!(dev, "G16: unsupported boot-loader handoff contract\n"); @@ -148,8 +176,8 @@ pub(crate) fn read(dev: &device::Device) -> Result { hw::TABLES_SIZE, hw::HANDOFF_SIZE, hw::SHARED_L2_SIZE, - 0x60000, - 0x13c000, + layout.text_size, + layout.data_size, ]; let mut regions: [Range; 6] = Default::default(); for (index, (name, expected)) in names.iter().zip(sizes).enumerate() { @@ -203,5 +231,6 @@ pub(crate) fn read(dev: &device::Device) -> Result { text, data, performance, + layout, }) } diff --git a/drivers/gpu/drm/asahi/g16/adt/perf.rs b/drivers/gpu/drm/asahi/g16/adt/perf.rs index 1824cd255358a..7c64913aa69bf 100644 --- a/drivers/gpu/drm/asahi/g16/adt/perf.rs +++ b/drivers/gpu/drm/asahi/g16/adt/perf.rs @@ -24,6 +24,27 @@ pub(crate) struct Source { pub(crate) core_mv: [u32; MAX_STATES], pub(crate) sram_frequency_mhz: [u32; MAX_STATES], pub(crate) sram_mv: [u32; MAX_STATES], + /// The sgx node's `gpu-pwr-sample-period-aic-clks`: exact GPU power sample period in ticks + /// of the system counter, where the tree has it. + pub(crate) power_sample_clks: Option, + /// The sgx node's `gpu-power-sample-period`: coarse integer millisecond GPU power sample + /// period, where the tree has it. + pub(crate) power_sample_period_ms: Option, + /// `/arm-io/pmgr/clpc` `cpu-avg-limiter-input-tc`: average-power filter time constant in + /// milliseconds, where the tree has it. + pub(crate) avg_power_filter_tc_ms: Option, + /// `/arm-io/pmgr/clpc` `cpu-lowpeak-limiter-input-tc`: low-peak power limiter filter time + /// constant in milliseconds, where the tree has it. + pub(crate) lowpeak_limiter_tc_ms: Option, + /// `/arm-io/pmgr/clpc` `cpu-lowpeak-limiter-ki`: low-peak power limiter integral gain in + /// Q16.16 fixed point, where the tree has it. + pub(crate) lowpeak_limiter_ki_q16: Option, + /// `/arm-io/pmgr/clpc` `cpu-lowpeak-limiter-kp`: low-peak power limiter proportional gain + /// in Q16.16 fixed point, where the tree has it. + pub(crate) lowpeak_limiter_kp_q16: Option, + /// `/arm-io/gfx-asc/iop-gfx-nub` `coredump-copy-buffer`: size in bytes of the host crash + /// copy buffer, where the tree has it. + pub(crate) coredump_copy_size: Option, } fn u32_at(data: &[u8], at: usize) -> Result { @@ -129,6 +150,15 @@ impl<'a> Tree<'a> { } u32_at(data, 0) } + + fn opt_nonzero_cell(&self, node: usize, name: &[u8]) -> Result, Error> { + match self.cell(node, name) { + Ok(0) => Err(Error::Range), + Ok(value) => Ok(Some(value)), + Err(Error::Missing) => Ok(None), + Err(error) => Err(error), + } + } } fn decode_record(data: &[u8], state: usize) -> Result<(u32, u32), Error> { @@ -174,12 +204,59 @@ pub(crate) fn parse(data: &[u8]) -> Result { if core.len() != count * 8 || sram.len() != count * 8 { return Err(Error::Shape); } + let power_sample_clks = tree.opt_nonzero_cell(sgx, b"gpu-pwr-sample-period-aic-clks")?; + let power_sample_period_ms = tree.opt_nonzero_cell(sgx, b"gpu-power-sample-period")?; + let clpc = match tree.child(armio, b"pmgr") { + Ok(pmgr) => match tree.child(pmgr, b"clpc") { + Ok(clpc) => Some(clpc), + Err(Error::Missing) => None, + Err(error) => return Err(error), + }, + Err(Error::Missing) => None, + Err(error) => return Err(error), + }; + let ( + avg_power_filter_tc_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16, + ) = if let Some(clpc) = clpc { + ( + tree.opt_nonzero_cell(clpc, b"cpu-avg-limiter-input-tc")?, + tree.opt_nonzero_cell(clpc, b"cpu-lowpeak-limiter-input-tc")?, + tree.opt_nonzero_cell(clpc, b"cpu-lowpeak-limiter-ki")?, + tree.opt_nonzero_cell(clpc, b"cpu-lowpeak-limiter-kp")?, + ) + } else { + (None, None, None, None) + }; + let coredump_copy_size = match tree.child(armio, b"gfx-asc") { + Ok(asc) => match tree.child(asc, b"iop-gfx-nub") { + Ok(nub) => match tree.opt_nonzero_cell(nub, b"coredump-copy-buffer")? { + Some(bytes) if bytes & 0xfff != 0 || bytes > 0x10_0000 => { + return Err(Error::Range); + } + other => other, + }, + Err(Error::Missing) => None, + Err(error) => return Err(error), + }, + Err(Error::Missing) => None, + Err(error) => return Err(error), + }; let mut source = Source { count, frequency_mhz: [0; MAX_STATES], core_mv: [0; MAX_STATES], sram_frequency_mhz: [0; MAX_STATES], sram_mv: [0; MAX_STATES], + power_sample_clks, + power_sample_period_ms, + avg_power_filter_tc_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16, + coredump_copy_size, }; for i in 0..count { (source.frequency_mhz[i], source.core_mv[i]) = decode_record(core, i)?; diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index 91de8189abd8a..fdef6c7c908da 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -1,12 +1,15 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4/J713 cold admission and the qualified 25G83 firmware start sequence. +//! M4/J713 cold admission and the firmware start sequence (25G83; 26B123 once its unknowns are +//! known). //! //! The Rust owner validates firmware identity and all inherited regions before publication, -//! holds the PMP AGX vote, prepares owned objects and publishes context0 while ASC RUN is clear. +//! holds the PMP AGX vote (25G83; 26B123 sends none), prepares owned objects and publishes +//! context0 while ASC RUN is clear. //! It negotiates RTKit protocol12, accepts only the inherited EP1 crash buffer, then submits -//! initdata plus NOP0x1a and policy0x34/0x0a. Control+0x14 and exact retired indices qualify -//! READY; no M3 firmware constants or device-control sequence are reused. +//! initdata plus the consume-only NOP and policy (re-import Globals, start; 0x1a, 0x34 and +//! 0x0a on 25G83, 0x19, 0x35 and 0x0a on 26B123). Control+0x14 and exact retired indices +//! qualify READY; no M3 firmware constants or device-control sequence are reused. //! Firmware-reachable backing and the RTKit cookie remain retained until reboot. use core::ffi::c_void; @@ -25,11 +28,10 @@ use kernel::{ use super::adt::{self, GpuAdt}; use super::channel::{self, Channel, Channels}; use super::event::Events; -use super::fw::channels::{devctl, DevCtl}; -use super::fw::initdata::control; -use super::hw; +use super::fw::channels::DevCtl; +use super::hw::{self, LoaderTable}; use super::initdata::{self, InitData}; -use super::object::Objects; +use super::object::{Class, Objects, Placement, Request}; use super::{regs, uat, Config, Shared}; use crate::driver::AsahiDrmDevice; use crate::{mmu, regs as shared_regs}; @@ -43,7 +45,7 @@ pub(crate) mod glue { extern "C" { fn asahi_g16_board() -> bool; fn asahi_g16_display_prepare(dev: *mut core::ffi::c_void) -> core::ffi::c_int; - fn asahi_g16_perf_rows() -> core::ffi::c_uint; + fn asahi_g16_timebase_hz() -> u32; fn asahi_g16_hold_power(dev: *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_g16_ram_disjoint(start: u64, size: u64) -> bool; fn asahi_g16_ioremap_wc(start: u64, size: usize) -> *mut core::ffi::c_void; @@ -73,10 +75,10 @@ pub(crate) mod glue { kernel::error::to_result(unsafe { asahi_g16_display_prepare(dev.as_raw().cast()) }) } - /// The firmware DVFS row count qualified for this board, or zero. - pub(crate) fn perf_rows() -> usize { - // SAFETY: Reads the machine compatible strings only. - unsafe { asahi_g16_perf_rows() as usize } + /// The system counter frequency in Hz, as the boot loader programmed it. + pub(crate) fn timebase_hz() -> u32 { + // SAFETY: Reads the system counter frequency register only. + unsafe { asahi_g16_timebase_hz() } } /// Holds the GFX power domain for the retained session. @@ -287,7 +289,7 @@ unsafe extern "C" fn rtkit_shmem_destroy( } /// The GPU's RTKit callbacks. -static RTKIT_OPS: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { +const RTKIT_OPS_BASE: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { flags: 0, crashed: Some(rtkit_crashed), recv_message: Some(rtkit_recv), @@ -300,6 +302,56 @@ static RTKIT_OPS: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { protocol_version: 12, }; +/// 25G83: the firmware's crash buffer is mapped without a reply. +static RTKIT_OPS: bindings::apple_rtkit_ops = RTKIT_OPS_BASE; + +/// 26B123: the crash-log endpoint starts while the endpoint map is handled, and the firmware's +/// request for its own crash buffer is sent back unchanged. +static RTKIT_OPS_27_2: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { + flags: bindings::APPLE_RTKIT_COPROC_PLACES_BUFFERS, + ..RTKIT_OPS_BASE +}; + +/// The host log buffer message the 26B123 start sends from RTKit's `before_ap` hook. +struct LogBuffer { + rtk: *mut bindings::apple_rtkit, + shared: *const Shared, + message: u64, + result: core::ffi::c_int, +} + +/// RTKit `before_ap` hook of the 26B123 start: once the firmware's own crash buffer has been +/// set up (and its request sent back), hands it the host log buffer before AP power-on. +/// +/// # Safety +/// +/// `data` must point to a live [`LogBuffer`] exclusively borrowed for this call, whose `rtk` +/// is the RTKit instance running the hook and whose `shared` outlives it. +unsafe extern "C" fn publish_log_buffer(data: *mut c_void) { + // SAFETY: By the function's contract. + let log = unsafe { &mut *data.cast::() }; + // SAFETY: By the function's contract. + let shared = unsafe { &*log.shared }; + let start = Instant::::now(); + while matches!(shared.rtkit_buffer.load(Ordering::Acquire), 0 | u64::MAX) { + if start.elapsed() > Delta::from_millis(1000) { + log.result = ETIMEDOUT.to_errno(); + return; + } + fsleep(Delta::from_millis(1)); + } + // SAFETY: `log.rtk` is the live RTKit instance running this hook. + log.result = unsafe { + bindings::apple_rtkit_send_message( + log.rtk, + hw::start_27_2::EP_CRASHLOG, + log.message, + core::ptr::null_mut(), + false, + ) + }; +} + /// The GPU's RTKit client. Never freed: the firmware session lasts until reboot. /// /// # Invariants @@ -316,11 +368,15 @@ unsafe impl Sync for Rtkit {} impl Rtkit { /// Initializes the sole RTKit owner on the default mailbox (retained). - fn new(dev: &device::Device, shared: &Arc) -> Result { + fn new( + dev: &device::Device, + shared: &Arc, + ops: &'static bindings::apple_rtkit_ops, + ) -> Result { let cookie = Arc::into_raw(shared.clone()) as *mut c_void; // SAFETY: `dev` is valid, the name is a NUL-terminated string and the ops are static. let rtk = from_err_ptr(unsafe { - bindings::apple_rtkit_init(dev.as_raw(), cookie, core::ptr::null(), 0, &RTKIT_OPS) + bindings::apple_rtkit_init(dev.as_raw(), cookie, core::ptr::null(), 0, ops) }); match rtk { // INVARIANT: The cookie stays leaked from here on. @@ -349,6 +405,21 @@ impl Rtkit { to_result(unsafe { bindings::apple_rtkit_warm_restart(self.rtk) }) } + /// Waits for the firmware to report in without an IOP power request, runs `before_ap`, then + /// sets the AP on. + /// + /// # Safety + /// + /// `before_ap` must be safe to call with `data`, from this thread, during this call. + unsafe fn boot_with( + &mut self, + before_ap: unsafe extern "C" fn(*mut c_void), + data: *mut c_void, + ) -> Result { + // SAFETY: `rtk` is live by the type invariant; the caller vouches for the hook. + to_result(unsafe { bindings::apple_rtkit_boot_with(self.rtk, Some(before_ap), data) }) + } + /// Waits for the firmware to report in, and sets the AP on. pub(crate) fn boot(&mut self) -> Result { // SAFETY: `rtk` is live by the type invariant. @@ -403,6 +474,11 @@ pub(crate) struct Session { pub(crate) regs: regs::Regs, pub(crate) adt: GpuAdt, uat: Arc, + /// The PPL handoff page, mapped here only to read the firmware's powered flag + /// ([`hw::FwLayout::powered`]); `None` when the firmware keeps the GPU powered. + handoff: Option, + /// True once cold boot (`START`) has completed and the firmware may idle-power-off the GPU. + booted: bool, } impl Session { @@ -413,16 +489,69 @@ impl Session { /// Live transport and powered-firmware health, plus any previously latched failure. pub(crate) fn check(&self) -> Result { - self.shared.check()?; - if !self.rtkit.running() - || self.regs.asc_control()? & regs::ASC_RUN == 0 - || self.regs.pstate()? > self.regs.top() - { + self.transport()?; + if self.regs.asc_control()? & regs::ASC_RUN == 0 { return Err(EIO); } + // Only read SGX pstate while the GPU is powered under the PPL handoff lock. + if let Some(pstate) = self.while_powered(regs::Regs::pstate)? { + if pstate > self.regs.top() { + return Err(EIO); + } + } self.uat.check_adopted_bindings() } + /// The transport alone: a latched failure, or RTKit stopped or crashed. No register or + /// UAT read, so the retirement loop can ask between its receipts. + pub(crate) fn transport(&self) -> Result { + self.shared.check()?; + if !self.rtkit.running() { + return Err(EIO); + } + Ok(()) + } + + /// Runs `read` with the GPU held powered, or returns `None` while it is powered down. A + /// firmware that powers the GPU down while idle changes GPU power only while it holds the + /// PPL handoff lock, and records the result on the handoff page before releasing it. The + /// AP side of the lock is held here across that record and `read`, so the GPU cannot go + /// down between them. Reading a GPU register while it is down takes an SError. + fn while_powered(&self, read: impl FnOnce(®s::Regs) -> Result) -> Result> { + let (Some(page), Some(offset)) = (&self.handoff, self.adt.layout.powered) else { + return read(&self.regs).map(Some); + }; + let _held = self.uat.lock_m4_handoff()?; + if page.io().try_read8(offset)? == 0 { + return Ok(None); + } + read(&self.regs).map(Some) + } + + /// The engine receipts of a running firmware, or `None` while the GPU is powered down. + pub(crate) fn engine_state(&self) -> Result> { + self.while_powered(regs::Regs::engine_state) + } + + /// The first engine fault bank holding a fault, for a firmware halted for recovery, or + /// `None` while the GPU is powered down. + pub(crate) fn fault_scan(&self) -> Result> { + self.while_powered(regs::Regs::fault_scan) + } + + /// Writes the host-owned device-control generation register (`sgx + 0xd60000`). Once cold + /// boot has completed and the firmware may idle-power-off the GPU, the access is guarded by + /// [`Self::while_powered`], returning `EAGAIN` if the GPU is currently powered down. + pub(crate) fn set_generation(&self, value: u32) -> Result { + if !self.booted { + return self.regs.set_generation(value); + } + match self.while_powered(|regs| regs.set_generation(value))? { + Some(()) => Ok(()), + None => Err(EAGAIN), + } + } + /// Sends a mailbox message. pub(crate) fn send(&mut self, endpoint: u8, message: u64) -> Result { self.rtkit.send(endpoint, message) @@ -475,7 +604,11 @@ pub(crate) fn admit( res: shared_regs::G16Resources, ) -> Result { let dev = pdev.as_ref(); - if !glue::board() { + // The board check guards the PMP AGX vote, which only the 25G83 start sends. A firmware + // whose handoff names the start without the vote (26B123) rests on the firmware identity + // checks below instead. + let votes = !matches!(adt::layout(dev), Some(layout) if layout.start == hw::Start::MacOs27_2); + if votes && !glue::board() { return Err(ENODEV); } // Retain the PMP supplier (and its AGX bridge) before any vote. @@ -502,7 +635,25 @@ pub(crate) fn admit( cfg.firmware, ) .inspect_err(|e| dev_err!(dev, "loaded GFX TEXT identity mismatch: {:?}\n", e))?; - dev_info!(dev, "M4: firmware identity accepted\n"); + dev_info!( + dev, + "M4: firmware identity accepted ({} layout)\n", + adt.layout.name + ); + // Refuse a firmware whose start needs something not known yet before anything is held. + let mut unknown = false; + for what in adt.layout.unknown() { + dev_err!( + dev, + "G16: the {} firmware cannot be started yet; not known: {}\n", + adt.layout.name, + what + ); + unknown = true; + } + if unknown { + return Err(ENOTSUPP); + } // Firmware objects are cleaned to the point of coherency by their DMA mapping: that needs // a device that is not DMA-coherent, as the synthesized node is. if glue::dma_unsupported(dev) { @@ -565,6 +716,7 @@ fn wait_boot_control( || done > target || write != target { + channels.log_stop(session, init, "unexpected boot-control indices"); return Err(eproto()); } if ready == 1 && read == target && done == target { @@ -576,30 +728,68 @@ fn wait_boot_control( stable = None; } if start.elapsed() > Delta::from_millis(timeout_ms) { - dev_err!( - session.dev, - "M4 boot control target{} ready{} indices{}/{}/{}\n", - target, - ready, - read, - done, - write - ); + channels.log_stop(session, init, "boot control not retired in time"); return Err(ETIMEDOUT); } fsleep(Delta::from_micros(1000)); } } +/// Writes the register-map records into the firmware's table in loaded DATA, which must be +/// empty on cold entry. This is the only host write to the loaded DATA segment. +fn publish_loader_table(session: &Session, init: &InitData, offset: u64) -> Result { + let table = init.loader_bytes(); + let loader = regs::Mapping::write_combined(session.adt.data.start + offset, table.len())?; + for _ in 0..2 { + for offset in (0..table.len()).step_by(4) { + if loader.io().try_read32(offset)? != 0 { + return Err(EBUSY); + } + } + regs::rmb(); + } + for (i, word) in table.chunks_exact(4).enumerate() { + loader + .io() + .try_write32(u32::from_le_bytes(word.try_into().unwrap()), i * 4)?; + } + regs::wmb(); + Ok(()) +} + /// Wake the sole firmware instance, publish its loader table, then qualify NOP and policy. fn run( session: &mut Session, events: &mut Events, built: &mut (InitData, Channels, u32), + log_buffer: Option<(u64, usize)>, ) -> Result { let dev = session.dev.clone(); let (init, channels, _) = built; - session.rtkit.wake()?; + let kind = session.adt.layout.start; + match kind { + hw::Start::Wake25G83 => session.rtkit.wake()?, + hw::Start::MacOs27_2 => { + use hw::start_27_2 as s; + let (va, log_size) = log_buffer.ok_or(EINVAL)?; + let mut log = LogBuffer { + rtk: session.rtkit.as_raw(), + shared: &*session.shared, + message: s::MSG_LOG_BUFFER + | (((log_size >> 12) as u64) << s::MSG_LOG_BUFFER_PAGES_SHIFT) + | (va & s::MSG_LOG_BUFFER_ADDR_MASK), + result: 0, + }; + // SAFETY: `log` lives on this stack frame across the call and nothing else + // borrows it; the hook runs on this thread before `boot_with` returns. + unsafe { + session + .rtkit + .boot_with(publish_log_buffer, (&raw mut log).cast())? + }; + to_result(log.result)?; + } + } let start = Instant::::now(); while matches!( session.shared.rtkit_buffer.load(Ordering::Acquire), @@ -619,32 +809,33 @@ fn run( { return Err(eproto()); } + if kind == hw::Start::MacOs27_2 { + let probe = session.regs.publish_host_block()?; + dev_info!( + dev, + "G16: 27.2 host block published, scratch {:#x}\n", + probe + ); + } session.rtkit.start_endpoint(hw::ep::FIRMWARE)?; session.rtkit.start_endpoint(hw::ep::DOORBELL)?; - for _ in 0..10 { - fsleep(Delta::from_millis(10)); - channels.drain_rings(&dev, events)?; - session.check()?; - } - session.regs.set_generation(0)?; - channels.stage_boot_nop(session)?; - // This table is the only host write to the loaded DATA segment. It is empty on cold entry. - let table = init.loader_bytes(); - let loader = regs::Mapping::write_combined(session.adt.data.start + 0x1332f0, table.len())?; - for _ in 0..2 { - for offset in (0..table.len()).step_by(4) { - if loader.io().try_read32(offset)? != 0 { - return Err(EBUSY); - } + let devctl = init.abi.devctl(); + if kind == hw::Start::Wake25G83 { + for _ in 0..10 { + fsleep(Delta::from_millis(10)); + channels.drain_rings(&dev, events)?; + session.check()?; } - regs::rmb(); + session.regs.set_generation(0)?; } - for (i, word) in table.chunks_exact(4).enumerate() { - loader - .io() - .try_write32(u32::from_le_bytes(word.try_into().unwrap()), i * 4)?; + channels.stage_boot_nop(session, devctl.nop)?; + match session.adt.layout.loader_table { + Some(LoaderTable::Host(offset)) => publish_loader_table(session, init, offset)?, + // The firmware copies the register map from HW data while it parses InitData. + Some(LoaderTable::Firmware) => {} + // Admission refuses such a layout; never guess here. + None => return Err(ENOTSUPP), } - regs::wmb(); let root = init.root_va()?; session.send( hw::ep::FIRMWARE, @@ -652,16 +843,37 @@ fn run( )?; session.send(hw::ep::DOORBELL, 0x0083000000000011)?; wait_boot_control(session, channels, events, init, 1, 5000)?; - devctl_op(session, channels, events, init, devctl::IMPORT_GLOBALS)?; - wait_boot_control(session, channels, events, init, 2, 2000)?; + let base = 1; let scheduler = init.control.as_ref().ok_or(EINVAL)?; - if scheduler.r32(control::SCHEDULER)? != 0 { - return Err(EBUSY); + let scheduler_word = init.firmware_data().scheduler; + devctl_op(session, channels, events, init, devctl.import_globals)?; + wait_boot_control(session, channels, events, init, base + 1, 5000)?; + let pending = scheduler.r32(scheduler_word)?; + if kind == hw::Start::MacOs27_2 { + // The InitData request (1) can still be pending here on 26B123: the firmware consumes it + // when it powers the GPU up or recovers, and the boot records need not power it up. Post + // START with it pending; never stack a second request. + if pending > 1 { + channels.log_stop( + session, + init, + "scheduler word unexpected after IMPORT_GLOBALS", + ); + return Err(EBUSY); + } + if pending == 0 { + scheduler.w32(scheduler_word, 1)?; + } + } else { + if pending != 0 { + channels.log_stop(session, init, "scheduler word set after IMPORT_GLOBALS"); + return Err(EBUSY); + } + scheduler.w32(scheduler_word, 1)?; } - scheduler.w32(control::SCHEDULER, 1)?; regs::wmb(); - devctl_op(session, channels, events, init, devctl::START)?; - wait_boot_control(session, channels, events, init, 3, 2000)?; + devctl_op(session, channels, events, init, devctl.start)?; + wait_boot_control(session, channels, events, init, base + 2, 2000)?; session.send(hw::ep::DOORBELL, 0x0083000000000010)?; for _ in 0..10 { fsleep(Delta::from_millis(10)); @@ -671,17 +883,19 @@ fn run( return Err(eproto()); } } - if channels.devctl.read()? != 3 - || channels.devctl.completion()? != 3 - || channels.devctl.write()? != 3 - || scheduler.r32(control::SCHEDULER)? != 0 + if channels.devctl.read()? != base + 2 + || channels.devctl.completion()? != base + 2 + || channels.devctl.write()? != base + 2 + || (kind == hw::Start::Wake25G83 && scheduler.r32(scheduler_word)? != 0) { + channels.log_stop(session, init, "boot controls not settled after START"); return Err(EBUSY); } dev_info!( dev, - "M4 firmware accepted owned initdata root{:#x}, NOP and policy; READY\n", - root + "M4 firmware accepted owned initdata root{:#x}, NOP and policy; READY (scheduler {})\n", + root, + scheduler.r32(scheduler_word)? ); Ok(()) } @@ -700,11 +914,19 @@ pub(crate) fn start( if regs.asc_control()? & regs::ASC_RUN != 0 { return Err(EBUSY); } - // SAFETY: `d` is the bound GPU device. - let ret = unsafe { bindings::apple_pmp_j713_gpu_get(d.as_raw()) }; - if ret != 0 { - dev_err!(d, "PMP AGX vote failed: {}\n", ret); - return Err(Error::from_errno(ret)); + let kind = adt.layout.start; + if kind == hw::Start::MacOs27_2 { + // 26B123 sends no PMP AGX vote: the firmware acknowledges its own IOP power-on once + // GFXCAXI2AF is enabled and RUN is raised. + dev_info!(d, "G16: 26B123: starting without PMP AGX vote\n"); + regs.enable_axi2af()?; + } else { + // SAFETY: `d` is the bound GPU device. + let ret = unsafe { bindings::apple_pmp_j713_gpu_get(d.as_raw()) }; + if ret != 0 { + dev_err!(d, "PMP AGX vote failed: {}\n", ret); + return Err(Error::from_errno(ret)); + } } let id = regs.identity()?; dev_info!( @@ -749,6 +971,13 @@ pub(crate) fn start( if !window.ttbat_is_clear()? { return Err(EBUSY); } + let handoff = match adt.layout.powered { + Some(_) => Some(regs::Mapping::write_combined( + adt.handoff.start, + hw::HANDOFF_SIZE as usize, + )?), + None => None, + }; // Adopt the UAT and prove the leaf words before anything firmware-visible is written: no // context names the shadow window or the lower root yet. let uat = uat::adopt(dev, cfg, &adt)?; @@ -765,7 +994,11 @@ pub(crate) fn start( core::mem::forget(objects); return Err(e); } - let rtkit = match Rtkit::new(&d, shared) { + let ops = match kind { + hw::Start::Wake25G83 => &RTKIT_OPS, + hw::Start::MacOs27_2 => &RTKIT_OPS_27_2, + }; + let rtkit = match Rtkit::new(&d, shared, ops) { Ok(rtkit) => rtkit, Err(e) => { core::mem::forget(objects); @@ -779,6 +1012,8 @@ pub(crate) fn start( regs, adt, uat, + handoff, + booted: false, }; let mut events = Events::new(); let mut built = None; @@ -790,6 +1025,28 @@ pub(crate) fn start( // The running firmware may report any state of the board's table, up to S10 on J773g. session.regs.set_table(init.rows); } + let log_buffer = match kind { + hw::Start::MacOs27_2 => { + let log_size = session + .adt + .performance + .coredump_copy_size + .ok_or(EINVAL)? as usize; + let va = objects + .alloc(Request { + size: log_size, + class: Class::Fw, + placement: Placement::Anywhere, + offset: 0, + client: None, + lower: None, + cpu: true, + })? + .va; + Some((va, log_size)) + } + hw::Start::Wake25G83 => None, + }; objects.window.lock().bootstrap(&d, &session.uat)?; uat::tlbi_all(); if session.regs.asc_control()? & regs::ASC_RUN != 0 { @@ -801,7 +1058,15 @@ pub(crate) fn start( if session.regs.asc_control()? & regs::ASC_RUN == 0 { return Err(EIO); } - run(&mut session, &mut events, built.as_mut().ok_or(EINVAL)?) + objects.window.lock().await_firmware_magic(&d)?; + run( + &mut session, + &mut events, + built.as_mut().ok_or(EINVAL)?, + log_buffer, + )?; + session.booted = true; + Ok(()) })(); if let Err(e) = result { dev_err!( diff --git a/drivers/gpu/drm/asahi/g16/channel.rs b/drivers/gpu/drm/asahi/g16/channel.rs index 7e67501a4c8c7..b01a419641a02 100644 --- a/drivers/gpu/drm/asahi/g16/channel.rs +++ b/drivers/gpu/drm/asahi/g16/channel.rs @@ -183,8 +183,9 @@ impl Channels { Ok(producer) } - /// Stage the boot NOP before the initdata root is handed to the firmware. - pub(crate) fn stage_boot_nop(&mut self, session: &Session) -> Result { + /// Stage the boot NOP (the firmware ABI's consume-only `nop` opcode) before the initdata + /// root is handed to the firmware. + pub(crate) fn stage_boot_nop(&mut self, session: &Session, nop: u32) -> Result { if self.devctl_producer != 0 || self.devctl.read()? != 0 || self.devctl.completion()? != 0 @@ -192,17 +193,35 @@ impl Channels { { return Err(super::boot::eproto()); } - self.devctl - .ring - .write(0, &DevCtl::op(super::fw::channels::devctl::NOP).to_bytes())?; + self.devctl.ring.write(0, &DevCtl::op(nop).to_bytes())?; wmb(); - session.regs.set_generation(1)?; + session.set_generation(1)?; self.devctl.state.w32(STATE_WRITE, 1)?; wmb(); self.devctl_producer = 1; Ok(()) } + /// The one error line for a stop during the boot sequence: why, the device-control indices + /// and the FirmwareData recovery words. Reads host RAM only, never a GPU register. + pub(crate) fn log_stop(&self, session: &Session, init: &InitData, why: &str) { + let ix = |r: Result| r.unwrap_or(u32::MAX); + let fd = init.firmware_data(); + let word = |o: usize| init.control.as_ref().map_or(u32::MAX, |c| ix(c.r32(o))); + dev_err!( + session.dev, + "G16 boot stopped: {}: devctl read {} completion {} write {} producer {}; phase {:#x} scheduler {:#x} ready {:#x}\n", + why, + ix(self.devctl.read()), + ix(self.devctl.completion()), + ix(self.devctl.write()), + self.devctl_producer, + word(fd.phase), + word(fd.scheduler), + ix(init.readiness()) + ); + } + /// Consumes a receive ring to its firmware producer. fn drain_one(ring: &Ring, offset: usize, capacity: u32) -> Result { let producer = ring.state.r32(offset + STATE_WRITE)?; @@ -218,28 +237,50 @@ impl Channels { } /// Drains every receive ring: events (decoded into `events`), the nine log sub-rings, trace - /// and stats. + /// and stats, on every pass, whatever another ring reported. The firmware waits while its + /// event ring is full, so one bad record must never leave a ring undrained. The first error + /// is returned once all are done. pub(crate) fn drain_rings(&self, dev: &kernel::device::Device, events: &mut Events) -> Result { - events.drain(dev, &self.event)?; + let mut result = events.drain(dev, &self.event); + let mut keep = |r: Result| { + if result.is_ok() { + result = r; + } + }; for i in 0..rings::LOG_RINGS { - Self::drain_one(&self.log, i * 0x30, 256)?; + keep(Self::drain_one(&self.log, i * 0x30, 256)); } - // Ktrace has twice the capacity of the other receive rings. + keep(self.drain_trace(dev)); + keep(events.drain_statistics(dev, &self.stats)); + result + } + + /// Ktrace has twice the capacity of the other receive rings. A record of another type than + /// the qualified one (5) is logged and consumed, then reported. + fn drain_trace(&self, dev: &kernel::device::Device) -> Result { let producer = self.trace.write()?; let mut consumer = self.trace.read()?; if producer >= 512 || consumer >= 512 { return Err(super::boot::eproto()); } rmb(); + let mut result = Ok(()); while consumer != producer { - if self.trace.ring.r32(consumer as usize * 0x48)? != 5 { - return Err(super::boot::eproto()); + let kind = self.trace.ring.r32(consumer as usize * 0x48)?; + if kind != 5 && result.is_ok() { + dev_err!( + dev, + "unexpected M4 firmware trace record type {} at {}\n", + kind, + consumer + ); + result = Err(super::boot::eproto()); } consumer = (consumer + 1) % 512; self.trace.state.w32(STATE_READ, consumer)?; wmb(); } - events.drain_statistics(dev, &self.stats) + result } } @@ -266,6 +307,7 @@ pub(crate) fn devctl_submit( channels.drain_rings(&dev, events)?; session.check()?; if init.halted()? { + channels.log_stop(session, init, "firmware halted before a control was posted"); return Err(EBUSY); } if expired() { @@ -285,7 +327,7 @@ pub(crate) fn devctl_submit( .ring .write(producer as usize * rings::DEVCTL_RECORD, &record.to_bytes())?; wmb(); - session.regs.set_generation(next)?; + session.set_generation(next)?; channels.devctl.state.w32(STATE_WRITE, next)?; wmb(); channels.devctl_producer = next; @@ -300,6 +342,7 @@ pub(crate) fn devctl_submit( return Ok(()); } if init.halted()? { + channels.log_stop(session, init, "firmware halted awaiting a control"); return Err(EBUSY); } if expired() { @@ -333,9 +376,10 @@ impl Firmware { ) } - /// The latched transport error: an RTKit crash or a refused RTKit buffer. + /// The latched transport error: an RTKit crash or a refused RTKit buffer. The register + /// and UAT checks of [`Session::check`] run once per pass, in its callers. pub(crate) fn transport_error(&self) -> Option { - self.session.check().err() + self.session.transport().err() } /// Drains the receive rings and decodes events. Called first in every poll pass. diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index a9bf84943b805..af7c52237c5cd 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4 25G83 HAL200 work-image and microsequence encoders. +//! M4 HAL200 work-image and microsequence encoders (25G83 and 26B123 work layouts). //! //! Pure byte builders over retained firmware/client addresses. Allocation, //! address-range admission, owner leases, cache visibility and publication are @@ -69,9 +69,11 @@ pub(crate) const fn compact(gva: u64) -> u64 { #[path = "encode/compute.rs"] mod compute_encoder; +use compute_encoder::put_generation; #[allow(unused_imports)] // Pure encoder utilities are exercised by the host ABI harness. pub(crate) use compute_encoder::{ - encode_compute, init_compute_pool, preserve_compute_descriptor, ComputeEncodeError, ComputeRefs, + encode_compute, encode_compute_for, init_compute_pool, preserve_compute_descriptor, + ComputeEncodeError, ComputeRefs, }; /// Tiling geometry and register words of a render (accelerator count 2). @@ -277,6 +279,6 @@ pub(crate) fn barrier( mod render_encoder; #[allow(unused_imports)] // Includes private-tail variants rejected by the shared Mesa UAPI. pub(crate) use render_encoder::{ - append_fs_timestamp_copies, encode_fs, encode_ta, fill_scene, initbm, render_attachments, - scene, scene_render, PassRefs, RenderRefs, + append_fs_timestamp_copies, encode_fs, encode_fs_for, encode_ta, encode_ta_for, fill_scene, + initbm, render_attachments, scene, scene_render, PassRefs, RenderRefs, }; diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 08a4f9ee9cefd..fe307dcfce52c 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -1,9 +1,19 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Pure G16G/25G83 compute encoding. Publication and lifetime proofs belong to the engine. +//! Pure G16G compute encoding (25G83 and 26B123 work layouts). Publication and lifetime proofs +//! belong to the engine. use super::{compute, manager, put16, put32, put64, put8, uapi}; +/// Stores the binding generation `v` as a little-endian integer of `bytes` (1 or 8) bytes. +pub(super) fn put_generation(b: &mut [u8], off: usize, bytes: usize, v: u8) { + if bytes == 1 { + put8(b, off, v); + } else { + put64(b, off, u64::from(v)); + } +} + /// A rejected detached image is never publishable; all validation precedes writes. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum ComputeEncodeError { @@ -134,14 +144,21 @@ pub(crate) fn preserve_compute_descriptor( Ok(submitted_before + 1) } -fn timestamp(q: &mut [u8], off: usize, end: bool, r: &ComputeRefs, requested: bool) { +fn timestamp( + q: &mut [u8], + off: usize, + end: bool, + r: &ComputeRefs, + requested: bool, + auxiliary: usize, +) { put32(q, off, if end { 3 } else { 0x80000003 }); put64(q, off + 4, r.work + 0x82c); put64(q, off + 0xc, r.work + 0x834); put64(q, off + 0x14, r.work + if end { 0x83c } else { 0x834 }); put64(q, off + 0x1c, r.qinfo); put64(q, off + 0x24, if requested { r.work + 0x844 } else { 0 }); - put64(q, off + 0x2c, r.work + 0x89c); + put64(q, off + 0x2c, r.work + auxiliary as u64); put64(q, off + 0x34, r.work + 0x7dc); put64(q, off + 0x44, 1); } @@ -150,8 +167,25 @@ fn timestamp(q: &mut [u8], off: usize, end: bool, r: &ComputeRefs, requested: bo /// `r` is authoritative; `n` is only the shared engine's software ordinal. The zeroed sequence /// is mirrored at work+0x900; its live pointer is `r.seq`, which may name that embedded copy or /// a separate retained object. Absolute references into the sequence use `r.seq` in both cases. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_compute( + r: &ComputeRefs, + c: &uapi::drm_asahi_cmd_compute, + att: &[uapi::drm_asahi_attachment], + ts_va: &[u64; 2], + ctx: u32, + n: u64, + fault_mask: u32, + w: &mut [u8; compute::WORK_SIZE], + q: &mut [u8; compute::SEQ_SIZE], +) -> Result<(), ComputeEncodeError> { + encode_compute_for(&compute::V25G83, r, c, att, ts_va, ctx, n, fault_mask, w, q) +} + +/// [`encode_compute`] for the work layout of another firmware ABI. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_compute_for( + layout: &compute::Layout, r: &ComputeRefs, c: &uapi::drm_asahi_cmd_compute, att: &[uapi::drm_asahi_attachment], @@ -307,7 +341,12 @@ pub(crate) fn encode_compute( put64(w, 0x873, 0x1588000); put64(w, 0x87b, 0xef8000); put64(w, 0x883, r.auxiliary_fw); - put8(w, 0x88b, r.binding_generation); + put_generation( + w, + compute::GENERATION, + layout.generation_bytes, + r.binding_generation, + ); put32(q, 0, 0xb); put64(q, 0x14, r.work + 0x20); @@ -335,12 +374,12 @@ pub(crate) fn encode_compute( put64(q, 0x190, r.context_store_gva + 0xf400); put64(q, 0x198, r.context_store_gva + 0x1e800); put64(q, 0x1a0, r.context_store_gva + 0x1f000); - put64(q, 0x1a8, r.work + 0x8ac); + put64(q, 0x1a8, r.work + layout.target as u64); put32(q, 0x1b8, compute::EVENT); let requested = ts_va[0] != 0 || ts_va[1] != 0; - timestamp(q, compute::TS_START, false, r, requested); + timestamp(q, compute::TS_START, false, r, requested, layout.auxiliary); put32(q, 0x208, 1); - timestamp(q, compute::TS_END, true, r, requested); + timestamp(q, compute::TS_END, true, r, requested, layout.auxiliary); let f = compute::FINALIZE; put32(q, f, 0xc); put64(q, f + 4, r.stats_fw); @@ -353,8 +392,8 @@ pub(crate) fn encode_compute( put64(q, f + 0x5c, r.seq + 0x160); put32(q, f + 0x64, 0u32.wrapping_sub(f as u32)); put8(q, f + 0x68, u8::from(!att.is_empty())); - put64(q, f + 0x69, r.work + 0x8ac); - put64(q, f + 0x71, r.work + 0x88c); + put64(q, f + 0x69, r.work + layout.target as u64); + put64(q, f + 0x71, r.work + layout.completion as u64); put32(q, compute::END, 0x40000002); w[compute::SEQ_EMBEDDED..compute::SEQ_EMBEDDED + compute::SEQ_SIZE].copy_from_slice(q); diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index b054ec08198b7..d949013e46206 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4 25G83 HAL200 render wire records. Inputs are frozen, retained addresses; +//! M4 HAL200 render wire records (25G83 and 26B123). Inputs are frozen, retained addresses; //! these builders neither allocate nor publish queue/notifier state. use super::*; @@ -88,6 +88,7 @@ fn inline_uma(q: &mut [u8], off: usize, r: &RenderRefs, engine: usize) { put8(q, off + 0x34, engine as u8); } +#[allow(clippy::too_many_arguments)] fn timestamps( q: &mut [u8], off: usize, @@ -96,11 +97,12 @@ fn timestamps( user: bool, uuid: u32, engine: usize, + auxiliary: usize, ) { - let (control, pair, auxiliary, context, user_pair) = if engine == 0 { - (0x8c0, 0x8c8, 0x928, 0x83c, 0x8d8) + let (control, pair, context, user_pair) = if engine == 0 { + (0x8c0, 0x8c8, 0x83c, 0x8d8) } else { - (0xc08, 0xc10, 0xc70, 0xb84, 0xc20) + (0xc08, 0xc10, 0xb84, 0xc20) }; for end in [false, true] { let base = off + if end { 0x50 } else { 0 }; @@ -110,7 +112,7 @@ fn timestamps( put64(q, base + 0x14, work + pair + if end { 8 } else { 0 }); put64(q, base + 0x1c, queue); put64(q, base + 0x24, if user { work + user_pair } else { 0 }); - put64(q, base + 0x2c, work + auxiliary); + put64(q, base + 0x2c, work + auxiliary as u64); put64(q, base + 0x34, work + context); put64(q, base + 0x44, u64::from(uuid)); } @@ -126,9 +128,28 @@ fn internal_pair(w: &mut [u8], p: &PassRefs, engine: usize, ts: &[u64; 4]) { put64(w, off + 0x18, ts[2 * engine + 1]); } -/// Encode the 66-record single-cluster tiler work and its exact 0x300 sequence. -#[allow(clippy::too_many_arguments)] +/// Encode the 25G83 66-record single-cluster tiler work and its exact 0x300 sequence. +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_ta( + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + target: u32, + geo: &Geometry, + cl: Option<&ClusterLayout>, + w: &mut [u8; ta::WORK_SIZE], + q: &mut [u8; ta::SEQ_SIZE], +) { + encode_ta_for(&ta::V25G83, r, p, u, ts_va, ctx, target, geo, cl, w, q) +} + +/// Encode the 66-record single-cluster tiler work of `layout`'s ABI and its exact 0x300 +/// sequence. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_ta_for( + layout: &ta::Layout, r: &RenderRefs, p: &PassRefs, u: &uapi::drm_asahi_cmd_render, @@ -242,7 +263,7 @@ pub(crate) fn encode_ta( put64(w, 0x8fe, r.uma_mgr[0]); put8(w, 0x906, 1); put64(w, 0x90f, r.uma_aux[0]); - put8(w, 0x917, r.generation); + put_generation(w, ta::GENERATION, layout.generation_bytes, r.generation); let work = p.ta_work; put32(q, 0, 5); @@ -268,6 +289,7 @@ pub(crate) fn encode_ta( ts_va[0] != 0 || ts_va[1] != 0, r.uuid, 0, + layout.auxiliary, ); let f = 0x268; put32(q, f, 6); @@ -283,14 +305,33 @@ pub(crate) fn encode_ta( put32(q, f + 0x50, target); put64(q, f + 0x78, p.ta_seq + 0x190); put32(q, f + 0x80, 0u32.wrapping_sub(f as u32)); - put64(q, f + 0x85, work + 0x918); + put64(q, f + 0x85, work + layout.completion as u64); put8(q, f + 0x8d, 1); put32(q, f + 0x94, 0x40000002); } -/// Encode the 82-record fragment work and base 0x380 sequence. -#[allow(clippy::too_many_arguments)] +/// Encode the 25G83 82-record fragment work and base 0x380 sequence. +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_fs( + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + usc: u64, + n: u64, + target: u32, + geo: &Geometry, + w: &mut [u8; fs::WORK_SIZE], + q: &mut [u8], +) { + encode_fs_for(&fs::V25G83, r, p, u, ts_va, ctx, usc, n, target, geo, w, q) +} + +/// Encode the 82-record fragment work of `layout`'s ABI and base 0x380 sequence. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_fs_for( + layout: &fs::Layout, r: &RenderRefs, p: &PassRefs, u: &uapi::drm_asahi_cmd_render, @@ -458,8 +499,8 @@ pub(crate) fn encode_fs( put64(w, 0xc46, r.uma_mgr[0]); put8(w, 0xc4e, 1); put64(w, 0xc57, r.uma_aux[1]); - put8(w, 0xc5f, r.generation); - put8(w, 0xc84, 1); + put_generation(w, fs::GENERATION, layout.generation_bytes, r.generation); + put8(w, layout.flag, 1); let work = p.fs_work; put32(q, 0, 7); @@ -487,6 +528,7 @@ pub(crate) fn encode_fs( ts_va[2] != 0 || ts_va[3] != 0, r.uuid, 1, + layout.auxiliary, ); let f = 0x288; put32(q, f, 8); @@ -506,7 +548,7 @@ pub(crate) fn encode_fs( put64(q, f + 0x64, work + 0xa58); put64(q, f + 0x98, p.fs_seq + 0x1b0); put32(q, f + 0xa0, 0u32.wrapping_sub(f as u32)); - put64(q, f + 0xa5, work + 0xc60); + put64(q, f + 0xa5, work + layout.completion as u64); put32(q, f + 0xad, 1); put8(q, f + 0xb1, 1); put32(q, f + 0xb2, 0x71); diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index c431061332cec..691fc1dc42a59 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -187,7 +187,7 @@ pub(crate) struct Flight { pub(crate) published_ns: u64, /// Published behind another flight. pub(crate) behind: bool, - /// The PB epoch this render prefix uses (its own, or a reused one with `g16_pb_reuse`). + /// The PB epoch this render prefix uses (its own, or a reused pass-slot epoch). pub(crate) pb: Option>, /// Its pass slot binding (`Pools::bind`). pub(crate) pb_binding: u64, @@ -432,8 +432,6 @@ pub(crate) struct Engine { pub(crate) prof: KBox, /// The `aurora-g16/stats` file. pub(crate) debugfs: Option>>>>, - /// The `aurora-g16/tune` file. - pub(crate) tune_file: Option>>>>, scratch: Option>, } @@ -467,7 +465,6 @@ impl Engine { stats: KBox::new(Stats::default(), GFP_KERNEL)?, prof: KBox::new(Prof::default(), GFP_KERNEL)?, debugfs: None, - tune_file: None, // Allocate host encoder buffers before any submitted fence can depend on // the device mutex. Publication must never enter direct reclaim here. scratch: Some(KBox::new(Scratch::new()?, GFP_KERNEL)?), @@ -760,6 +757,22 @@ impl Firmware { self.service_power()?; self.drain_rings()?; self.check_hangs(done)?; + self.publish_checked(done) + } + + /// [`Self::publish`] for a poll pass, which has already drained the receive rings and + /// checked for hangs under this device lock; still rechecks the session (including ASC RUN) + /// after retirement before publishing new work. + pub(crate) fn publish_checked(&mut self, done: &mut Completions) -> Result { + if self + .session + .shared + .sleeping + .load(core::sync::atomic::Ordering::Acquire) + { + return Ok(()); + } + self.session.check()?; // The initial G16 backend deliberately serializes hardware publication. Stronger // ordering satisfies Mesa's barriers while slot displacement and cache ownership // stay explicit. Never enable G15's submit-ahead policy on the M4 wire by accident. @@ -979,8 +992,8 @@ impl Firmware { let generation = job.vm.generation; let arena = job.resources.render()?; let mut a = arena.pools.prepare(k, draw)?; - // g16_pb_reuse: reuse this VM's retired epoch of the slot: no reseed, no InitBM. - let (epoch, reused) = match self.pools.reusable(params::pb_reuse(), k, &job.vm) { + // Reuse this VM's retired epoch of the slot when still bound: no reseed, no InitBM. + let (epoch, reused) = match self.pools.reusable(k, &job.vm) { Some(e) => { self.pools.stats.reused += 1; a.init_buffer = false; @@ -1331,7 +1344,7 @@ impl Firmware { fw_stamp: g.fw_stamp.va, work: s.work.va, work_gva: s.work.lower_gva.ok_or(EINVAL)?, - // Exact embedded sequence: every self-reference then matches the 25G83 layout. + // Exact embedded sequence: every self-reference then matches the qualified layout. seq: s.work.va + 0x900, preempt_gva: s.preempt.gva.ok_or(EINVAL)?, its: s.its.va, @@ -1361,7 +1374,8 @@ impl Firmware { let w = image(&mut scratch.cw)?; // User results are published coherently after the complete retirement receipt. // The firmware's internal timestamp pair remains enabled. - encode::encode_compute( + encode::encode_compute_for( + self.init.abi.compute(), &refs, &cmd.cmd, &cmd.attachments, @@ -1427,7 +1441,8 @@ impl Firmware { .render()? .set_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes)?; let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; - encode::encode_ta( + encode::encode_ta_for( + self.init.abi.ta(), &refs, &pass, &cmd.cmd, @@ -1439,7 +1454,8 @@ impl Firmware { image(&mut scratch.ta)?, image(&mut scratch.tas)?, ); - encode::encode_fs( + encode::encode_fs_for( + self.init.abi.fs(), &refs, &pass, &cmd.cmd, diff --git a/drivers/gpu/drm/asahi/g16/fw/channels.rs b/drivers/gpu/drm/asahi/g16/fw/channels.rs index 9b5ae1e7c4b08..395b82134bcdb 100644 --- a/drivers/gpu/drm/asahi/g16/fw/channels.rs +++ b/drivers/gpu/drm/asahi/g16/fw/channels.rs @@ -46,7 +46,10 @@ impl SubmitRecord { } } -/// Device-control opcodes of the qualified 25G83 M4 firmware. +/// Device-control opcodes of each supported M4 firmware ABI. +/// +/// The host advances its generation word alongside the device-control producer for each posted +/// record. pub(crate) mod devctl { /// Re-import Globals. pub(crate) const IMPORT_GLOBALS: u32 = 0x34; @@ -56,6 +59,31 @@ pub(crate) mod devctl { pub(crate) const NOP: u32 = 0x1a; /// PB growth reply. pub(crate) const GROW_REPLY: u32 = 7; + + /// The opcodes the host sends, in one firmware ABI. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Opcodes { + pub(crate) import_globals: u32, + pub(crate) start: u32, + pub(crate) nop: u32, + pub(crate) grow_reply: u32, + } + + pub(crate) const V25G83: Opcodes = Opcodes { + import_globals: IMPORT_GLOBALS, + start: START, + nop: NOP, + grow_reply: GROW_REPLY, + }; + + /// 26B123 device-control opcodes (re-import Globals 0x35, start 0x0a, no-op 0x19, + /// PB growth reply 7). + pub(crate) const V26B123: Opcodes = Opcodes { + import_globals: 0x35, + start: 0x0a, + nop: 0x19, + grow_reply: 7, + }; } /// A device-control record (0x40 bytes, opcode first). diff --git a/drivers/gpu/drm/asahi/g16/fw/graph.rs b/drivers/gpu/drm/asahi/g16/fw/graph.rs index 344dd3da37061..e3c95e2756720 100644 --- a/drivers/gpu/drm/asahi/g16/fw/graph.rs +++ b/drivers/gpu/drm/asahi/g16/fw/graph.rs @@ -21,6 +21,44 @@ pub(crate) mod qinfo { /// u64 scheduling context VA, then u64 4. pub(crate) const SCHED_CTX: usize = 0xa4; pub(crate) const UNK_AC: usize = 0xac; + + /// The queue-info words that move between firmware ABIs. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + /// Bytes of the firmware-owned header (what it invalidates on a new queue); the queue + /// scratch follows it in the same object. + pub(crate) header: usize, + /// u32 2, read as a byte by the firmware (row 2's `UNK_48`). + pub(crate) class_c: usize, + /// u32 `u32::MAX`. + pub(crate) unk_4c: usize, + pub(crate) uuid: usize, + /// u64 scheduling context VA. + pub(crate) sched_ctx: usize, + /// Firmware u32 busy flag: 1 from when the firmware takes a record until DONE (+0x20) + /// reaches the head (+0x28). + pub(crate) busy: usize, + } + + pub(crate) const V25G83: Layout = Layout { + header: 0xb0, + class_c: super::qinfo_row2::UNK_48, + unk_4c: UNK_4C, + uuid: UUID, + sched_ctx: SCHED_CTX, + busy: 0x80, + }; + + /// 26B123 queue-info header (0x80 bytes): class_c at 0x44, unk_4c at 0x48, uuid at 0x4c, + /// busy at 0x54, scheduling context aligned at 0x78, and queue scratch starting at 0x80. + pub(crate) const V26B123: Layout = Layout { + header: 0x80, + class_c: 0x44, + unk_4c: 0x48, + uuid: 0x4c, + sched_ctx: 0x78, + busy: 0x54, + }; } /// Queue-info scheduling rows (the firmware's recognized policy rows). @@ -115,23 +153,36 @@ pub(crate) mod pools { pub(crate) const SEEDS: usize = 8192; } -/// The nonzero queue header; the rest of the fresh 0x24c0 object remains zero. Keeping the -/// scratch inside this object is part of the M4 ABI, not a separate buffer allocation. +/// The nonzero 25G83 queue header; the rest of the fresh 0x24c0 object remains zero. Keeping +/// the scratch inside this object is part of the M4 ABI, not a separate buffer allocation. pub(crate) fn queue_image( state: u64, ring: u64, list: u64, queue: u64, context: u64, +) -> [u8; 0xb4] { + queue_image_for(&qinfo::V25G83, state, ring, list, queue, context) +} + +/// The nonzero queue header of `layout`'s ABI, zero-padded to 0xb4 bytes; the scratch starts +/// right after the firmware-owned header. The same 0x24c0 object holds either. +pub(crate) fn queue_image_for( + layout: &qinfo::Layout, + state: u64, + ring: u64, + list: u64, + queue: u64, + context: u64, ) -> [u8; 0xb4] { let mut q = [0; 0xb4]; for (at, value) in [ (0, state), (8, ring), (0x10, list), - (0x18, queue + 0xb0), + (0x18, queue + layout.header as u64), (0x38, qinfo_row2::MASK_VALUE), - (0xa4, context), + (layout.sched_ctx, context), ] { q[at..at + 8].copy_from_slice(&value.to_le_bytes()); } @@ -139,8 +190,8 @@ pub(crate) fn queue_image( (0x2c, u32::MAX), (0x30, 2u32), (0x34, 2), - (0x48, 2), - (0x4c, u32::MAX), + (layout.class_c, 2), + (layout.unk_4c, u32::MAX), ] { q[at..at + 4].copy_from_slice(&value.to_le_bytes()); } diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 0083f5cad939e..3b74ce8736f4a 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -1,11 +1,13 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! J713/T8132 initdata for the qualified 25G83 firmware. +//! J713/T8132 initdata for the qualified 25G83 firmware and the 26B123 firmware. //! -//! This is a byte encoder for private, unpublished objects. Admission, mapping, -//! cache maintenance and publication belong to the owner. It has no kernel or -//! allocator dependency so a host harness can compare every byte with the C -//! bring-up encoder. +//! The encoder is written in 25G83 offsets; a [`Layout`] maps them to another firmware ABI +//! (26B123 inserts and removes words in several objects, renumbers the register map and +//! moves the FirmwareData words). This is a byte encoder for private, unpublished objects. +//! Admission, mapping, cache maintenance and publication belong to the owner. It has no kernel +//! or allocator dependency so a host harness can compare every byte with the C bring-up +//! encoder. pub(crate) const PAGE: u64 = 0x4000; pub(crate) const PA_MASK: u64 = 0x3ffffffc000; @@ -16,7 +18,6 @@ pub(crate) const BOOTSTRAP_SIZE: u64 = 0x2000000; pub(crate) const OBJECT_COUNT: usize = 31; pub(crate) const LOADER_COUNT: usize = 42; pub(crate) const LOADER_STRIDE: usize = 0x28; -pub(crate) const LOADER_BYTES: usize = LOADER_COUNT * LOADER_STRIDE; /// Stable positions in the firmware's object inventory. pub(crate) mod id { @@ -61,31 +62,623 @@ pub(crate) const OBJECT_SIZE: [usize; OBJECT_COUNT] = [ pub(crate) mod root { pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::ROOT]; - pub(crate) const MAGIC: u64 = 0x0c89c357839204b8; } /// The small root.Control object is the READY acknowledgement. pub(crate) mod ready_control { pub(crate) const READY: usize = 0x14; } -/// Runtime is a distinct pointer graph, not the READY object. -pub(crate) mod runtime { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::RUNTIME]; + +/// One run of a piecewise offset map: the 25G83 offsets `start..end` of an object are at +/// `+ delta` in another firmware ABI. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Run { + pub(crate) start: usize, + pub(crate) end: usize, + pub(crate) delta: usize, +} + +const fn run(start: usize, end: usize, delta: usize) -> Run { + Run { start, end, delta } +} + +/// Const counterpart of [`remap`] for compile-time layout validation. +const fn remap_const(runs: &[Run], at: usize, len: usize) -> Option { + let Some(end) = at.checked_add(len) else { + return None; + }; + let mut i = 0; + while i < runs.len() { + if runs[i].start <= at && end <= runs[i].end { + return at.checked_add(runs[i].delta); + } + i += 1; + } + None +} + +/// Where the `len`-byte field at 25G83 offset `at` lives under `runs`. A field outside every +/// run (an offset whose new position is not known, or the register map) is refused. +pub(crate) fn remap(runs: &[Run], at: usize, len: usize) -> Result { + remap_const(runs, at, len).ok_or(()) +} + +/// The FirmwareData (status B) words the host reads and writes. +#[derive(Clone, Copy, Debug)] +pub(crate) struct FirmwareData { + /// u64 VAs of the FWCTL state and, 8 bytes later, its ring (state + 0x40). + pub(crate) fwctl: usize, + /// u64 recovery generation. + pub(crate) generation: usize, + /// u32 recovery phase. + pub(crate) phase: usize, + /// u32 scheduler import word. + pub(crate) scheduler: usize, + /// The affected-work snapshot: `snapshot_entries` `{flags u32, target u32}` pairs. + pub(crate) snapshot: usize, + pub(crate) snapshot_entries: usize, +} + +/// The InitData ABI of one firmware build: what differs from the 25G83 objects the encoder +/// writes. Offsets of every run are 25G83 offsets. +pub(crate) struct Layout { + pub(crate) name: &'static str, + /// Root +0: the interface version the firmware compares with its own. + pub(crate) version: u64, + pub(crate) object_size: [usize; OBJECT_COUNT], + /// RUNTIME (main config) offset of the unaligned power-config (POWER_PERFORMANCE) pointer. + pub(crate) power_config: usize, + /// Register-map slot in MAIN of each logical (25G83-numbered) loader record; `None` for a + /// record that is empty, and the number of slots of the map at MAIN + 0x640. + pub(crate) loader_slot: [Option; LOADER_COUNT], + pub(crate) register_slots: usize, + /// MAIN (HW data) after the register map, GLOBALS (region C) and POWER_PERFORMANCE (power + /// config). Only runs whose new position is known are listed. + pub(crate) main: &'static [Run], + pub(crate) globals: &'static [Run], + pub(crate) power_performance: &'static [Run], + pub(crate) firmware_data: FirmwareData, + /// GLOBALS p-state selectors the host publishes at runtime (hundredths of a state). + pub(crate) pstate_selectors: [usize; 3], + /// MAIN offset of the u64 size of the host's crash copy buffer, where the build has one. + pub(crate) coredump_copy: Option, + /// Where the RETENTION object is published. + pub(crate) retention: Retention, + /// GLOBALS (region C) words of this build that have no 25G83 position, at their own offsets. + pub(crate) globals_policy: &'static [(usize, u32)], + /// POWER_PERFORMANCE (power config) words of this build that have no 25G83 position, at + /// their own offsets. + pub(crate) power_policy: &'static [(usize, u32)], + /// POWER_PERFORMANCE words derived from the GPU power sample period and average-power + /// filter time constant, where the build has them. + pub(crate) power_sampling: Option, + /// POWER_PERFORMANCE words of the low-peak (PPM) power limiter derived from the machine's + /// ADT (`clpc` low-peak limiter properties and `sgx` sample period), where the build has + /// them. + pub(crate) power_limiter: Option, +} + +/// POWER_PERFORMANCE offsets of the words derived from the GPU power sample period and +/// average-power filter time constant. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PowerSampling { + /// The exact sample period in us (from `gpu-pwr-sample-period-aic-clks`), as u32. + pub(crate) period: &'static [usize], + /// The exact sample period in us, as f32. + pub(crate) period_f32: usize, + /// The average-power filter of `n` samples over the ADT's `cpu-avg-limiter-input-tc` + /// (`(tc_ms * 1000) / period_us`): u32 `n * 4`, f32 `(n - 1) / n` and f32 `1 / n`. + pub(crate) filter: [usize; 3], +} + +/// POWER_PERFORMANCE offsets of the low-peak (PPM) power limiter words derived from the +/// machine's ADT (`clpc` `cpu-lowpeak-limiter-*` and `sgx` `gpu-power-sample-period`). +#[derive(Clone, Copy, Debug)] +pub(crate) struct PowerLimiter { + /// Filter time constant in coarse sample periods, scaled by 4 (`periods * 4`). + pub(crate) filter_periods_x4: usize, + /// IIR filter pole `(periods - 1) / periods`, as f32. + pub(crate) filter_a_neg: usize, + /// IIR filter weight `1 / periods`, as f32. + pub(crate) filter_a: usize, + /// Integral gain scaled by the coarse sample period (`ki * period_s`), as f32. + pub(crate) ki_dt: usize, + /// PI integrator upper bound (`65536.0`, the fixed-point scale shared across M1-M5), as f32. + pub(crate) clamp: usize, + /// Proportional gain (`kp`), as f32. + pub(crate) kp: usize, + /// Filter time constant in ms (`cpu-lowpeak-limiter-input-tc`). + pub(crate) filter_tc_ms: usize, + /// Rounded filter time constant in system-counter ticks (`periods * period_ms * khz`). + pub(crate) filter_tc_clks: usize, +} + +/// IEEE-754 single-precision bits of `num / den` for `num` and `den` non-zero, rounded to +/// nearest, ties to even. The encoder runs where the kernel has no floating point. With 32-bit +/// inputs every step fits in 64 bits. +pub(crate) const fn f32_bits(num: u32, den: u32) -> u32 { + let (mut n, mut d) = (num as u64, den as u64); + let mut exponent: i32 = 0; + while n >= 2 * d { + d *= 2; + exponent += 1; + } + while n < d { + n *= 2; + exponent -= 1; + } + let scaled = n << 23; + let (mut mantissa, rest) = (scaled / d, scaled % d); + if 2 * rest > d || (2 * rest == d && mantissa & 1 == 1) { + mantissa += 1; + } + if mantissa == 1 << 24 { + mantissa >>= 1; + exponent += 1; + } + (((exponent + 127) as u32) << 23) | (mantissa as u32 & 0x7f_ffff) +} +const _: () = assert!(f32_bits(28, 29) == 0x3f77_2c23 && f32_bits(1, 29) == 0x3d0d_3dcb); +const _: () = assert!(f32_bits(8333, 1) == 0x4602_3400 && f32_bits(65536, 1) == 0x4780_0000); + +/// Where the RETENTION object (0x4000 zeroed bytes) is published. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Retention { + /// MAIN's retention pointer (25G83 0xe88). + Main, + /// MAIN's retention pointer stays 0 so the firmware keeps that state in its own RAM, and + /// the zeroed object is instead the RUNTIME table this u64 pointer names. + Runtime(usize), +} + +impl Layout { + /// The register-map slot of logical loader record `slot`. + pub(crate) fn slot(&self, slot: usize) -> Option { + self.loader_slot + .get(slot) + .copied() + .flatten() + .map(usize::from) + } + + /// Register-map records from slot 0 through the highest slot the encoder fills. + pub(crate) fn loader_records(&self) -> usize { + (0..LOADER_COUNT) + .filter(|&slot| LOADERS[slot].length != 0) + .filter_map(|slot| self.slot(slot)) + .max() + .map_or(0, |slot| slot + 1) + } +} + +const fn identity_slots() -> [Option; LOADER_COUNT] { + let mut out = [None; LOADER_COUNT]; + let mut slot = 0; + while slot < LOADER_COUNT { + out[slot] = Some(slot as u8); + slot += 1; + } + out +} + +/// 26B123 renumbers the register map (53 -> 60 slots): 0-7, 9-20 and 22-24 keep their numbers, +/// 26-43 move up by five (seven region types were added). Slots 8, 21 and 25 are empty here. +const fn slots_26b123() -> [Option; LOADER_COUNT] { + let mut out = [None; LOADER_COUNT]; + let mut slot = 0; + while slot < LOADER_COUNT { + out[slot] = match slot { + 0..=7 | 9..=20 | 22..=24 => Some(slot as u8), + // Logical 36 (the protected power-transition block at PA 0x300e00000) stays empty + // on 26B123: the firmware maps that block itself and fills its own VA during + // InitData. + 36 => None, + 26..=43 => Some(slot as u8 + 5), + _ => None, + }; + slot += 1; + } + out +} + +/// The 25G83 InitData ABI. +pub(crate) const V25G83: Layout = Layout { + name: "25G83", + version: 0x0c89c357839204b8, + object_size: OBJECT_SIZE, + power_config: 0x469, + loader_slot: identity_slots(), + register_slots: 53, + main: &[run(0, 0x640, 0), run(0xe88, 0x2658, 0)], + globals: &[run(0, 0xe48, 0)], + power_performance: &[run(0, 0x6578, 0)], + firmware_data: FirmwareData { + fwctl: 0x4f88, + generation: 0x4fa0, + phase: 0x4fb0, + scheduler: 0x4fd4, + snapshot: 0x40b8, + snapshot_entries: 448, + }, + pstate_selectors: [0x88, 0x8c, 0x98], + coredump_copy: None, + retention: Retention::Main, + globals_policy: &[], + power_policy: &[], + power_sampling: None, + power_limiter: None, +}; + +/// The 26B123 InitData ABI: the same 31 objects and pointers, with +/// - the main-config power-config pointer 16 bytes later; +/// - a 60-slot register map in MAIN, then the retention pointer at 0xfa0, a new u64 at 0xfa8 +/// (the crash copy buffer size), the old 0xe90.. words +0x120, 0xec0.. +0x11c (one word +/// removed at 0xebc), 0x2600.. +0x120 and the last bytes +0x124 (new u32s at 0x275c and +/// 0x277e, left zero); +/// - a u32 inserted at GLOBALS 0x38, so every later word moves by four; +/// - POWER_PERFORMANCE with words inserted at 0x9c (0x10 bytes), 0x28b0 (0x18), 0x3b50 (0x28) +/// and 0x63cc (0x680), 8 bytes removed between 0x2d08 and 0x2f08 and 0x20 between 0x62c4 and +/// 0x6318; +/// - FirmwareData words 0x1e0 bytes later (a table was inserted before them); +/// - POWER (left all zero) grown to 0x698 bytes. +pub(crate) const V26B123: Layout = Layout { + name: "26B123", + version: 0x0c8a836f039204b8, + object_size: [ + 0xc8, 0x4000, 0x4b8, 0xe4c, 0x20, 0xedd0, 0x698, 0x4000, 0x2788, 0x6c48, 0x88, 0xc18, + 0x1248, 0xe10, 0x60, 0x1b0, 0x28800, 0x79800, 0x4000, 0x30, 0x4000, 0x30, 0x9000, 0x30, + 0x4800, 0x4, 0x30, 0x4800, 0x4000, 0x4000, 0x4000, + ], + power_config: 0x479, + loader_slot: slots_26b123(), + register_slots: 60, + main: &[ + run(0, 0x640, 0), + run(0xe88, 0xe90, 0x118), + run(0xe90, 0xebc, 0x120), + run(0xec0, 0x25b4, 0x11c), + run(0x2600, 0x263c, 0x120), + run(0x263c, 0x2658, 0x124), + ], + globals: &[run(0, 0x38, 0), run(0x38, 0xe48, 4)], + power_performance: &[ + run(0, 0x9c, 0), + run(0x9c, 0x28b0, 0x10), + run(0x28b0, 0x2d08, 0x28), + run(0x2f08, 0x3b50, 0x20), + run(0x3b50, 0x62c4, 0x48), + run(0x6318, 0x63cc, 0x28), + run(0x63cc, 0x6578, 0x6a8), + ], + firmware_data: FirmwareData { + fwctl: 0x5168, + generation: 0x5180, + phase: 0x5190, + scheduler: 0x51b4, + snapshot: 0x4298, + snapshot_entries: 448, + }, + pstate_selectors: [0x8c, 0x90, 0x9c], + // HW data +0xfa8 holds the crash copy buffer's size, +0xfa0 stays 0, and the RETENTION + // object is published at RUNTIME +0x2c8. Publishing RETENTION at +0xfa0 with the size at + // +0xfa8 faulted on the first resume from idle power-off. + coredump_copy: Some(0xfa8), + retention: Retention::Runtime(0x2c8), + globals_policy: &[], + // 0xa4 selects the powered-up state; leaving 0 there keeps the GPU unpowered and triggers an + // SError on power-up. The low-peak (PPM) limiter words at +0xa80..+0xae0 are computed from + // the machine's ADT in `power_limiter`. + power_policy: &[(0xa4, 1)], + // Exact power sample period (from `gpu-pwr-sample-period-aic-clks`, in us) and the + // average-power IIR filter over the ADT's `cpu-avg-limiter-input-tc`. + power_sampling: Some(PowerSampling { + period: &[0x2b48, 0x2c10], + period_f32: 0x2bbc, + filter: [0x29e4, 0x29f0, 0x29f8], + }), + // Low-peak (PPM) power limiter IIR filter and PI controller words (25G83 +0xa70..+0xad0, + // shifted +0x10 in 26B123), derived from `/arm-io/pmgr/clpc` (`cpu-lowpeak-limiter-*`) + // and `/arm-io/sgx` (`gpu-power-sample-period`). + power_limiter: Some(PowerLimiter { + filter_periods_x4: 0xa80, + filter_a_neg: 0xa8c, + filter_a: 0xa94, + ki_dt: 0xa9c, + clamp: 0xaa8, + kp: 0xaac, + filter_tc_ms: 0xad8, + filter_tc_clks: 0xae0, + }), +}; + +/// Runs are ordered, disjoint and land inside an object of `size` bytes. +const fn runs_fit(runs: &[Run], size: usize) -> bool { + let mut i = 0; + while i < runs.len() { + if runs[i].start >= runs[i].end + || runs[i].end + runs[i].delta > size + || (i > 0 && runs[i].start < runs[i - 1].end) + { + return false; + } + i += 1; + } + true +} + +/// Fixed 25G83 GLOBALS words remapped into every ABI; shared by `encode_for` and `layout_fits`. +const GLOBALS_FIXED: &[(usize, u32)] = &[ + (0x78, 1), + (0xe28, 3), + (0x24, 3000), + (0x998, 40), + (0x99c, 10), + (0x9a0, 250), + (0x9b8, 2), + (0x9bc, 40), + (0x9c0, 5), + (0x9c8, 40), + (0x9cc, 50), +]; + +/// Fixed 25G83 POWER_PERFORMANCE offsets remapped into every ABI; shared by `encode_for` and +/// `layout_fits` so compile-time collision checks cover every remapped write. +const POWER_TEMP_PTR: usize = 0x3b50; +const POWER_FIXED_U32: &[usize] = &[4, 8, 0x10, 0x14, 0x2c, 0x30]; +const POWER_CEILING_U32: &[usize] = &[ + 0x9f0, 0x9f4, 0xa38, 0xaa8, 0xaac, 0xaf0, 0xb78, 0xb7c, 0xb80, 0xbc0, 0x22b0, 0x22b4, 0x22f8, + 0x2210, 0x2870, 0x2a3c, 0x2b84, 0x2b88, 0x2b8c, 0x2bcc, 0x2c40, 0x2c44, 0x2c88, 0x279e, +]; + +const fn ranges_overlap(a: usize, a_len: usize, b: usize, b_len: usize) -> bool { + a < b + b_len && b < a + a_len +} + +/// Every `globals_policy` word fits in GLOBALS and is disjoint from every other policy word, +/// every p-state selector, and every remapped 25G83 GLOBALS word. +const fn globals_policy_fits(layout: &Layout) -> bool { + let size = layout.object_size[id::GLOBALS]; + let mut i = 0; + while i < layout.globals_policy.len() { + let at = layout.globals_policy[i].0; + if at + 4 > size { + return false; + } + let mut j = 0; + while j < i { + if ranges_overlap(at, 4, layout.globals_policy[j].0, 4) { + return false; + } + j += 1; + } + let mut k = 0; + while k < layout.pstate_selectors.len() { + if ranges_overlap(at, 4, layout.pstate_selectors[k], 4) { + return false; + } + k += 1; + } + let mut m = 0; + while m < GLOBALS_FIXED.len() { + let Some(remapped) = remap_const(layout.globals, GLOBALS_FIXED[m].0, 4) else { + return false; + }; + if ranges_overlap(at, 4, remapped, 4) { + return false; + } + m += 1; + } + i += 1; + } + true +} + +/// A 4-byte POWER_PERFORMANCE slot fits and does not collide with any remapped 25G83 word. +const fn power_slot_clear(layout: &Layout, at: usize) -> bool { + let size = layout.object_size[id::POWER_PERFORMANCE]; + if at + 4 > size { + return false; + } + let Some(temp) = remap_const(layout.power_performance, POWER_TEMP_PTR, 8) else { + return false; + }; + if ranges_overlap(at, 4, temp, 8) { + return false; + } + let mut i = 0; + while i < POWER_FIXED_U32.len() { + let Some(remapped) = remap_const(layout.power_performance, POWER_FIXED_U32[i], 4) else { + return false; + }; + if ranges_overlap(at, 4, remapped, 4) { + return false; + } + i += 1; + } + let mut j = 0; + while j < POWER_CEILING_U32.len() { + let Some(remapped) = remap_const(layout.power_performance, POWER_CEILING_U32[j], 4) else { + return false; + }; + if ranges_overlap(at, 4, remapped, 4) { + return false; + } + j += 1; + } + true +} + +const fn power_policy_overlaps(policy: &[(usize, u32)], at: usize) -> bool { + let mut i = 0; + while i < policy.len() { + if ranges_overlap(at, 4, policy[i].0, 4) { + return false; + } + i += 1; + } + true } -/// Recovery words belong to FirmwareData, not root.Control. -pub(crate) mod control { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::FIRMWARE_DATA]; - pub(crate) const GENERATION: usize = 0x4fa0; - pub(crate) const PHASE: usize = 0x4fb0; - pub(crate) const SCHEDULER: usize = 0x4fd4; + +const fn sampling_clear_of(sampling: Option, at: usize) -> bool { + let Some(s) = sampling else { + return true; + }; + if ranges_overlap(at, 4, s.period_f32, 4) { + return false; + } + let mut i = 0; + while i < s.period.len() { + if ranges_overlap(at, 4, s.period[i], 4) { + return false; + } + i += 1; + } + let mut j = 0; + while j < s.filter.len() { + if ranges_overlap(at, 4, s.filter[j], 4) { + return false; + } + j += 1; + } + true } -pub(crate) mod globals { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::GLOBALS]; - pub(crate) const PSTATE_SELECTORS: [usize; 3] = [0x88, 0x8c, 0x98]; + +/// Every `power_policy`, `power_sampling` and `power_limiter` word fits in POWER_PERFORMANCE +/// and is disjoint from every remapped 25G83 word and from every other policy/sampling/limiter +/// word. +const fn power_policy_fits(layout: &Layout) -> bool { + let mut i = 0; + while i < layout.power_policy.len() { + let at = layout.power_policy[i].0; + if !power_slot_clear(layout, at) { + return false; + } + let mut j = 0; + while j < i { + if ranges_overlap(at, 4, layout.power_policy[j].0, 4) { + return false; + } + j += 1; + } + i += 1; + } + if let Some(s) = layout.power_sampling { + if !power_slot_clear(layout, s.period_f32) + || !power_policy_overlaps(layout.power_policy, s.period_f32) + { + return false; + } + let mut p = 0; + while p < s.period.len() { + let at = s.period[p]; + if !power_slot_clear(layout, at) + || !power_policy_overlaps(layout.power_policy, at) + || ranges_overlap(at, 4, s.period_f32, 4) + { + return false; + } + let mut prev = 0; + while prev < p { + if ranges_overlap(at, 4, s.period[prev], 4) { + return false; + } + prev += 1; + } + p += 1; + } + let mut f = 0; + while f < s.filter.len() { + let at = s.filter[f]; + if !power_slot_clear(layout, at) + || !power_policy_overlaps(layout.power_policy, at) + || ranges_overlap(at, 4, s.period_f32, 4) + { + return false; + } + let mut p2 = 0; + while p2 < s.period.len() { + if ranges_overlap(at, 4, s.period[p2], 4) { + return false; + } + p2 += 1; + } + let mut prev = 0; + while prev < f { + if ranges_overlap(at, 4, s.filter[prev], 4) { + return false; + } + prev += 1; + } + f += 1; + } + } + if let Some(lim) = layout.power_limiter { + let slots = [ + lim.filter_periods_x4, + lim.filter_a_neg, + lim.filter_a, + lim.ki_dt, + lim.clamp, + lim.kp, + lim.filter_tc_ms, + lim.filter_tc_clks, + ]; + let mut k = 0; + while k < slots.len() { + let at = slots[k]; + if !power_slot_clear(layout, at) + || !power_policy_overlaps(layout.power_policy, at) + || !sampling_clear_of(layout.power_sampling, at) + { + return false; + } + let mut prev = 0; + while prev < k { + if ranges_overlap(at, 4, slots[prev], 4) { + return false; + } + prev += 1; + } + k += 1; + } + } + true } -pub(crate) mod hwdata { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::MAIN]; + +/// A layout's words fit its objects and do not overlap each other. +pub(crate) const fn layout_fits(layout: &Layout) -> bool { + let fd = &layout.firmware_data; + let size = &layout.object_size; + fd.snapshot + fd.snapshot_entries * 8 <= fd.fwctl + && fd.fwctl + 0x10 <= fd.generation + && fd.generation + 8 <= fd.phase + && fd.phase < fd.scheduler + && fd.scheduler + 4 <= size[id::FIRMWARE_DATA] + && layout.power_config + 8 <= size[id::RUNTIME] + // The register map ends where the MAIN words after it (the retention pointer) start. + && 0x640 + layout.register_slots * LOADER_STRIDE + == layout.main[1].start + layout.main[1].delta + && runs_fit(layout.main, size[id::MAIN]) + && runs_fit(layout.globals, size[id::GLOBALS]) + && runs_fit(layout.power_performance, size[id::POWER_PERFORMANCE]) + && retention_fits(layout) + && globals_policy_fits(layout) + && power_policy_fits(layout) } +/// A RUNTIME retention table pointer is aligned, inside RUNTIME and clear of the power-config +/// pointer. +const fn retention_fits(layout: &Layout) -> bool { + match layout.retention { + Retention::Main => true, + Retention::Runtime(at) => { + at % 8 == 0 + && at + 8 <= layout.object_size[id::RUNTIME] + && (at + 8 <= layout.power_config || layout.power_config + 8 <= at) + } + } +} +const _: () = assert!(layout_fits(&V25G83) && layout_fits(&V26B123)); + /// One logical loader record, including its page offset and exact PTE class. #[derive(Clone, Copy, Debug)] pub(crate) struct Loader { @@ -386,6 +979,34 @@ pub(crate) struct Input { pub(crate) ktrace_mask: u32, pub(crate) progress_recovery: u32, pub(crate) performance: Performance, + /// Exact GPU power sample period in system-counter ticks (`gpu-pwr-sample-period-aic-clks`), + /// written to POWER_PERFORMANCE +4/+8. Non-zero is required. + pub(crate) power_sample_clks: u32, + /// Exact GPU power sample period in us (`power_sample_clks * 1_000_000 / timebase_hz`), + /// used instead of the coarse truncated ms property for the us period and average-power + /// sample count. 0 when absent, which a layout with [`Layout::power_sampling`] refuses. + pub(crate) power_sample_us: u32, + /// Coarse integer millisecond GPU power sample period (`gpu-power-sample-period`). 0 when + /// absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) power_sample_period_ms: u32, + /// System counter frequency in kHz (`timebase_hz / 1000`). 0 is refused by + /// [`Layout::power_limiter`]. + pub(crate) timebase_khz: u32, + /// Average-power filter time constant in ms (`/arm-io/pmgr/clpc` `cpu-avg-limiter-input-tc`). + /// 0 when absent, which a layout with [`Layout::power_sampling`] refuses. + pub(crate) avg_power_filter_tc_ms: u32, + /// Low-peak (PPM) limiter filter time constant in ms (`cpu-lowpeak-limiter-input-tc`). + /// 0 when absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) lowpeak_limiter_tc_ms: u32, + /// Low-peak (PPM) limiter integral gain in Q16.16 (`cpu-lowpeak-limiter-ki`). + /// 0 when absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) lowpeak_limiter_ki_q16: u32, + /// Low-peak (PPM) limiter proportional gain in Q16.16 (`cpu-lowpeak-limiter-kp`). + /// 0 when absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) lowpeak_limiter_kp_q16: u32, + /// Host crash copy buffer size in bytes (`/arm-io/gfx-asc/iop-gfx-nub` + /// `coredump-copy-buffer`). 0 or unaligned is refused by layouts with `coredump_copy`. + pub(crate) coredump_copy_size: u64, } pub(crate) fn object_va(va: u64, size: usize) -> bool { @@ -396,20 +1017,31 @@ fn bootstrap_alias(va: u64) -> bool { && va & (PAGE - 1) == 0 } +/// Encodes the 25G83 root. pub(crate) fn encode_root(out: &mut [u8], va: &[u64; OBJECT_COUNT]) -> Result<(), ()> { + encode_root_for(&V25G83, out, va) +} + +/// Encodes the root of `layout`'s ABI after checking every object VA and overlap. +pub(crate) fn encode_root_for( + layout: &Layout, + out: &mut [u8], + va: &[u64; OBJECT_COUNT], +) -> Result<(), ()> { + let size = &layout.object_size; for i in 0..OBJECT_COUNT { - if !object_va(va[i], OBJECT_SIZE[i]) { + if !object_va(va[i], size[i]) { return Err(()); } for j in 0..i { - if va[i] < va[j] + OBJECT_SIZE[j] as u64 && va[j] < va[i] + OBJECT_SIZE[i] as u64 { + if va[i] < va[j] + size[j] as u64 && va[j] < va[i] + size[i] as u64 { return Err(()); } } } let out = out.get_mut(..root::SIZE).ok_or(())?; out.fill(0); - put64(out, 0, root::MAGIC)?; + put64(out, 0, layout.version)?; for (at, i) in [ (0x08, id::BRN), (0x18, id::RUNTIME), @@ -453,15 +1085,27 @@ pub(crate) fn encode_channel( put64(out, 0x18, ring) } -/// Encodes the complete private 31-object graph, byte-for-byte matching the +/// Encodes the complete private 31-object 25G83 graph, byte-for-byte matching the /// working M4 C encoder. No mapping or publication is performed here. pub(crate) fn encode( objects: &mut [&mut [u8]; OBJECT_COUNT], input: &Input, ceiling: u32, +) -> Result<(), ()> { + encode_for(&V25G83, objects, input, ceiling) +} + +/// Encodes the complete private 31-object graph of `layout`'s ABI. Every input is checked +/// before the first byte is written. +pub(crate) fn encode_for( + layout: &Layout, + objects: &mut [&mut [u8]; OBJECT_COUNT], + input: &Input, + ceiling: u32, ) -> Result<(), ()> { if !input.performance.valid() || !(1..input.performance.count as u32).contains(&ceiling) + || input.power_sample_clks == 0 || !object_va(input.scratch, 0x8000) || !bootstrap_alias(input.lower_uma) || !bootstrap_alias(input.lower_parameter) @@ -470,14 +1114,63 @@ pub(crate) fn encode( { return Err(()); } + // Validate ADT-derived power sampling and limiter inputs before touching any output byte. + let sampling_values = if layout.power_sampling.is_some() { + if input.power_sample_us == 0 || input.avg_power_filter_tc_ms == 0 { + return Err(()); + } + let samples_u64 = (u64::from(input.avg_power_filter_tc_ms) * 1000) + / u64::from(input.power_sample_us); + let samples = u32::try_from(samples_u64).map_err(|_| ())?; + if samples < 2 || samples.checked_mul(4).is_none() { + return Err(()); + } + Some((input.power_sample_us, samples)) + } else { + None + }; + let limiter_values = if layout.power_limiter.is_some() { + if input.power_sample_period_ms == 0 + || input.timebase_khz == 0 + || input.lowpeak_limiter_tc_ms == 0 + || input.lowpeak_limiter_ki_q16 == 0 + || input.lowpeak_limiter_kp_q16 == 0 + { + return Err(()); + } + let periods = input.lowpeak_limiter_tc_ms / input.power_sample_period_ms; + if periods < 2 { + return Err(()); + } + let periods_x4 = periods.checked_mul(4).ok_or(())?; + let ki_num = input + .lowpeak_limiter_ki_q16 + .checked_mul(input.power_sample_period_ms) + .ok_or(())?; + let tc_clks = periods + .checked_mul(input.power_sample_period_ms) + .and_then(|ms| ms.checked_mul(input.timebase_khz)) + .ok_or(())?; + Some((periods, periods_x4, ki_num, tc_clks)) + } else { + None + }; + if layout.coredump_copy.is_some() + && (input.coredump_copy_size == 0 + || input.coredump_copy_size & 0xfff != 0 + || input.coredump_copy_size > 0x10_0000) + { + return Err(()); + } + let size = &layout.object_size; for (i, obj) in objects.iter().enumerate() { - if obj.len() < OBJECT_SIZE[i] { + if obj.len() < size[i] { return Err(()); } } - encode_root(objects[id::ROOT], &input.va)?; + encode_root_for(layout, objects[id::ROOT], &input.va)?; for i in 1..OBJECT_COUNT { - objects[i][..OBJECT_SIZE[i]].fill(0); + objects[i][..size[i]].fill(0); } let runtime = &mut objects[id::RUNTIME]; for (at, i) in [ @@ -498,7 +1191,7 @@ pub(crate) fn encode( (0x26c, id::ACTIVITY_RECOVERY), (0x2d8, id::PARAMETER), (0x2e8, id::UMA), - (0x469, id::POWER_PERFORMANCE), + (layout.power_config, id::POWER_PERFORMANCE), ] { put64(runtime, at, input.va[i])?; } @@ -507,6 +1200,9 @@ pub(crate) fn encode( put64(runtime, 0x2e0, input.lower_uma)?; put32(runtime, 0x250, 1)?; put32(runtime, 0x2f8, 4)?; + if let Retention::Runtime(at) = layout.retention { + put64(runtime, at, input.va[id::RETENTION])?; + } for i in 0..12 { encode_channel( &mut runtime[0x20 + i * 0x20..], @@ -521,35 +1217,33 @@ pub(crate) fn encode( input.va[id::DEVCTRL_RING], true, )?; + let fd = &layout.firmware_data; let fw = &mut objects[id::FIRMWARE_DATA]; - put64(fw, 0x4f88, input.va[id::FWCTL])?; - put64(fw, 0x4f90, input.va[id::FWCTL] + 0x40)?; - put32(fw, 0x4fd4, 1)?; + put64(fw, fd.fwctl, input.va[id::FWCTL])?; + put64(fw, fd.fwctl + 8, input.va[id::FWCTL] + 0x40)?; + put32(fw, fd.scheduler, 1)?; put32(objects[id::CONTROL], 0, input.ktrace_mask)?; put32(objects[id::ACTIVITY_FRAGMENT], 0xc18, 0xffffffff)?; put32(objects[id::ACTIVITY_FRAGMENT], 0xc30, 0xffffffff)?; let g = &mut objects[id::GLOBALS]; - for (at, value) in [ - (0x78, 1), - (0xe28, 3), - (0x24, 3000), - (0x998, 40), - (0x99c, 10), - (0x9a0, 250), - (0x9b8, 2), - (0x9bc, 40), - (0x9c0, 5), - (0x9c8, 40), - (0x9cc, 50), - ] { - put32(g, at, value)?; + for &(at, value) in GLOBALS_FIXED { + put32(g, remap(layout.globals, at, 4)?, value)?; } - for at in globals::PSTATE_SELECTORS { + for at in layout.pstate_selectors { put32(g, at, 100 * ceiling)?; } + for &(at, value) in layout.globals_policy { + put32(g, at, value)?; + } + let runs = layout.main; let main = &mut objects[id::MAIN]; - put64(main, 0x28, HOST_END)?; - put64(main, 0xe88, input.va[id::RETENTION])?; + put64(main, remap(runs, 0x28, 8)?, HOST_END)?; + if layout.retention == Retention::Main { + put64(main, remap(runs, 0xe88, 8)?, input.va[id::RETENTION])?; + } + if let Some(at) = layout.coredump_copy { + put64(main, at, input.coredump_copy_size)?; + } for (at, value) in [ (0xea0, 1), (0xee0, 1), @@ -567,52 +1261,97 @@ pub(crate) fn encode( (0x2568, 8), (0x2570, 1), ] { - put32(main, at, value)?; + put32(main, remap(runs, at, 4)?, value)?; } - put32(main, 0xea4, input.progress_recovery)?; - put64(main, 0xf24, 0x0000000607002004)?; - put32(main, 0xfc4, ceiling)?; + put32(main, remap(runs, 0xea4, 4)?, input.progress_recovery)?; + put64(main, remap(runs, 0xf24, 8)?, 0x0000000607002004)?; + put32(main, remap(runs, 0xfc4, 4)?, ceiling)?; for i in 0..=ceiling as usize { - put32(main, 0xfc8 + i * 4, input.performance.frequency[i])?; - put32(main, 0x1808 + i * 4, input.performance.auxiliary[i])?; + put32( + main, + remap(runs, 0xfc8 + i * 4, 4)?, + input.performance.frequency[i], + )?; + put32( + main, + remap(runs, 0x1808 + i * 4, 4)?, + input.performance.auxiliary[i], + )?; for core in 0..16 { put32( main, - 0x1008 + (i * 16 + core) * 4, + remap(runs, 0x1008 + (i * 16 + core) * 4, 4)?, input.performance.voltage[i], )?; put32( main, - 0x1408 + (i * 16 + core) * 4, + remap(runs, 0x1408 + (i * 16 + core) * 4, 4)?, input.performance.sram[i], )?; } } for slot in 0..LOADER_COUNT { - loader_encode( - slot, - input.loader_va[slot], - &mut main[0x640 + slot * LOADER_STRIDE..], - )?; + // This ABI has no slot for the record: the host must not have mapped it (`build` + // skips it), and it is not described. + let Some(at) = layout.slot(slot) else { + if input.loader_va[slot] != 0 { + return Err(()); + } + continue; + }; + if at >= layout.register_slots { + return Err(()); + } + let mut record = [0u8; LOADER_STRIDE]; + loader_encode(slot, input.loader_va[slot], &mut record)?; + let at = 0x640 + at * LOADER_STRIDE; + main.get_mut(at..at + LOADER_STRIDE) + .ok_or(())? + .copy_from_slice(&record); } + let runs = layout.power_performance; let p = &mut objects[id::POWER_PERFORMANCE]; - put64(p, 0x3b50, input.va[id::TEMPERATURE])?; - for (at, value) in [ - (4, 200000), - (8, 200000), - (0x10, 4), - (0x14, 0x3f800000), - (0x2c, ceiling), - (0x30, ceiling), - ] { + put64(p, remap(runs, POWER_TEMP_PTR, 8)?, input.va[id::TEMPERATURE])?; + let power_fixed_values = [ + input.power_sample_clks, + input.power_sample_clks, + 4, + 0x3f800000, + ceiling, + ceiling, + ]; + for (&at, value) in POWER_FIXED_U32.iter().zip(power_fixed_values) { + put32(p, remap(runs, at, 4)?, value)?; + } + for &at in POWER_CEILING_U32 { + put32(p, remap(runs, at, 4)?, 100 * ceiling)?; + } + // Disjointness from every remapped 25G83 word, power_sampling, and power_limiter slot is + // proved at compile time by layout_fits(). + for &(at, value) in layout.power_policy { put32(p, at, value)?; } - for at in [ - 0x9f0, 0x9f4, 0xa38, 0xaa8, 0xaac, 0xaf0, 0xb78, 0xb7c, 0xb80, 0xbc0, 0x22b0, 0x22b4, - 0x22f8, 0x2210, 0x2870, 0x2a3c, 0x2b84, 0x2b88, 0x2b8c, 0x2bcc, 0x2c40, 0x2c44, 0x2c88, - 0x279e, - ] { - put32(p, at, 100 * ceiling)?; + if let (Some(sampling), Some((period, samples))) = (layout.power_sampling, sampling_values) { + for &at in sampling.period { + put32(p, at, period)?; + } + put32(p, sampling.period_f32, f32_bits(period, 1))?; + let [count, keep, take] = sampling.filter; + put32(p, count, samples * 4)?; + put32(p, keep, f32_bits(samples - 1, samples))?; + put32(p, take, f32_bits(1, samples))?; + } + if let (Some(limiter), Some((periods, periods_x4, ki_num, tc_clks))) = + (layout.power_limiter, limiter_values) + { + put32(p, limiter.filter_periods_x4, periods_x4)?; + put32(p, limiter.filter_a_neg, f32_bits(periods - 1, periods))?; + put32(p, limiter.filter_a, f32_bits(1, periods))?; + put32(p, limiter.ki_dt, f32_bits(ki_num, 65536 * 1000))?; + put32(p, limiter.clamp, f32_bits(65536, 1))?; + put32(p, limiter.kp, f32_bits(input.lowpeak_limiter_kp_q16, 65536))?; + put32(p, limiter.filter_tc_ms, input.lowpeak_limiter_tc_ms)?; + put32(p, limiter.filter_tc_clks, tc_clks)?; } Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/fw/mod.rs b/drivers/gpu/drm/asahi/g16/fw/mod.rs index 77984b8cb5785..eaa924962befe 100644 --- a/drivers/gpu/drm/asahi/g16/fw/mod.rs +++ b/drivers/gpu/drm/asahi/g16/fw/mod.rs @@ -4,15 +4,70 @@ reason = "Firmware layout catalog also describes fields used by host wire regressions." )] -//! M4 firmware 25G83 structures. +//! M4 firmware 25G83 and 26B123 structures. //! //! Layouts of the records, work images and objects the host shares with the qualified 25G83 firmware, //! in the style of `g17/fw`: `#[repr(C)]` structures with `static_assert!` offsets where the //! layout is a fixed record, and offset constants where the driver writes sparse words into a //! larger image. Nothing here allocates, locks or publishes. +//! +//! What differs in another firmware ABI is held per file as `V25G83` / `V26B123` constants; +//! [`FwAbi`] selects them. pub(crate) mod buffer; pub(crate) mod channels; pub(crate) mod graph; pub(crate) mod initdata; pub(crate) mod work; + +use super::hw::FwAbi; + +impl FwAbi { + /// The InitData objects. + pub(crate) const fn initdata(self) -> &'static initdata::Layout { + match self { + FwAbi::V25G83 => &initdata::V25G83, + FwAbi::V26B123 => &initdata::V26B123, + } + } + + /// The device-control opcodes the host sends. + pub(crate) const fn devctl(self) -> &'static channels::devctl::Opcodes { + match self { + FwAbi::V25G83 => &channels::devctl::V25G83, + FwAbi::V26B123 => &channels::devctl::V26B123, + } + } + + /// The queue-info header. + pub(crate) const fn qinfo(self) -> &'static graph::qinfo::Layout { + match self { + FwAbi::V25G83 => &graph::qinfo::V25G83, + FwAbi::V26B123 => &graph::qinfo::V26B123, + } + } + + /// The TA work. + pub(crate) const fn ta(self) -> &'static work::ta::Layout { + match self { + FwAbi::V25G83 => &work::ta::V25G83, + FwAbi::V26B123 => &work::ta::V26B123, + } + } + + /// The FS work. + pub(crate) const fn fs(self) -> &'static work::fs::Layout { + match self { + FwAbi::V25G83 => &work::fs::V25G83, + FwAbi::V26B123 => &work::fs::V26B123, + } + } + + /// The compute work. + pub(crate) const fn compute(self) -> &'static work::compute::Layout { + match self { + FwAbi::V25G83 => &work::compute::V25G83, + FwAbi::V26B123 => &work::compute::V26B123, + } + } +} diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index ef54552540d7b..faa407bceb4c4 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -5,6 +5,11 @@ //! Render records use 66 TA and 82 FS register records, 0x4c-byte //! timestamp commands and 0x40-byte dependencies. Each register is an //! unaligned little-endian `(u32 selector, u64 value)` pair. +//! +//! Each work type's `Layout` holds what moves between firmware ABIs: 26B123 widens the +//! per-work binding generation from 1 to 8 bytes at the same offset, shifting later fixed +//! fields by 7 bytes and leaving the 16-byte span between the completion target and the +//! auxiliary target zeroed by the host. /// Microsequence opcodes. pub(crate) mod op { @@ -70,6 +75,38 @@ pub(crate) mod ta { pub(crate) const TS_END: usize = 0x21c; pub(crate) const FINALIZE: usize = 0x268; pub(crate) const END: usize = 0x2fc; + /// The binding generation. + pub(crate) const GENERATION: usize = 0x917; + + /// TA work fields that move between firmware ABIs. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + /// Width of the binding generation at [`GENERATION`]. + pub(crate) generation_bytes: usize, + /// Target of the finalize record's +0x85 pointer. + pub(crate) completion: usize, + /// Target of the timestamp records' +0x2c ("auxiliary") pointer. + pub(crate) auxiliary: usize, + } + + pub(crate) const V25G83: Layout = Layout { + generation_bytes: 1, + completion: 0x918, + auxiliary: 0x928, + }; + + pub(crate) const V26B123: Layout = Layout { + generation_bytes: 8, + completion: 0x91f, + auxiliary: 0x92f, + }; + + const fn valid(l: &Layout) -> bool { + l.completion == GENERATION + l.generation_bytes + && l.auxiliary == l.completion + 0x10 + && l.auxiliary + 8 <= WORK_SIZE + } + const _: () = assert!(valid(&V25G83) && valid(&V26B123)); pub(crate) const SEL: [u32; 66] = [ 0x1748, 0x10141, 0x1c039, 0x1c9c8, 0x1c0a1, 0x1c031, 0x1c9c0, 0x1c051, 0x1c061, 0x10149, 0x10139, 0x10111, 0x1c9b0, 0x10119, 0x1c9b8, 0x1c958, 0x1c950, 0x1c930, 0x1c880, 0x1c079, @@ -92,6 +129,43 @@ pub(crate) mod fs { pub(crate) const TS_END: usize = 0x23c; pub(crate) const FINALIZE: usize = 0x288; pub(crate) const END: usize = 0x344; + /// The binding generation. + pub(crate) const GENERATION: usize = 0xc5f; + + /// FS work fields that move between firmware ABIs. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + /// Width of the binding generation at [`GENERATION`]. + pub(crate) generation_bytes: usize, + /// Target of the finalize record's +0xa5 pointer. + pub(crate) completion: usize, + /// Target of the timestamp records' +0x2c ("auxiliary") pointer. + pub(crate) auxiliary: usize, + /// u8 flag the host sets to 1. + pub(crate) flag: usize, + } + + pub(crate) const V25G83: Layout = Layout { + generation_bytes: 1, + completion: 0xc60, + auxiliary: 0xc70, + flag: 0xc84, + }; + + pub(crate) const V26B123: Layout = Layout { + generation_bytes: 8, + completion: 0xc67, + auxiliary: 0xc77, + flag: 0xc8b, + }; + + const fn valid(l: &Layout) -> bool { + l.completion == GENERATION + l.generation_bytes + && l.auxiliary == l.completion + 0x10 + && l.flag == l.completion + 0x24 + && l.flag < WORK_SIZE + } + const _: () = assert!(valid(&V25G83) && valid(&V26B123)); pub(crate) const SEL: [u32; 82] = [ 0x1739, 0x10009, 0x15379, 0x15381, 0x15369, 0x15371, 0x15131, 0x15139, 0x100a1, 0x15069, 0x15071, 0x16058, 0x10019, 0x100b1, 0x16030, 0x100d9, 0xa301, 0x10791, 0x16098, 0x15109, diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index d7d9b40438b2e..c45d6772038f8 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -28,6 +28,54 @@ pub(crate) const POOL_SIZE: usize = 0x2000000; pub(crate) const POOL_STATE_SIZE: usize = 0x20000; pub(crate) const PAGE_LIST_SIZE: usize = 0x4000; pub(crate) const EVENT: u32 = 15; +/// The binding generation. +pub(crate) const GENERATION: usize = 0x88b; + +/// Compute work fields that move between firmware ABIs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Layout { + /// Width of the binding generation at [`GENERATION`]. + pub(crate) generation_bytes: usize, + /// Target of the finalize record's +0x71 pointer. + pub(crate) completion: usize, + /// Target of the timestamp records' +0x2c ("auxiliary") pointer. + pub(crate) auxiliary: usize, + /// u32 target of the start record's +0x1a8 and the finalize record's +0x69 pointers. + pub(crate) target: usize, + /// Bytes of the work the firmware caches; the host's private parts lie beyond them. + pub(crate) cached: usize, + /// Optional `(start, end)` u64 tick offsets inside the work object when the firmware writes + /// compute GPU timestamps into work rather than the unit's ITS pair. + pub(crate) work_ticks: Option<(usize, usize)>, +} + +pub(crate) const V25G83: Layout = Layout { + generation_bytes: 1, + completion: 0x88c, + auxiliary: 0x89c, + target: 0x8ac, + cached: 0x8c0, + work_ticks: None, +}; + +pub(crate) const V26B123: Layout = Layout { + generation_bytes: 8, + completion: 0x893, + auxiliary: 0x8a3, + target: 0x8b3, + cached: 0x8e0, + work_ticks: Some((0x7ec, 0x7f4)), +}; + +const fn valid(l: &Layout) -> bool { + l.completion == GENERATION + l.generation_bytes + && l.auxiliary == l.completion + 0x10 + && l.target == l.completion + 0x20 + && l.target + 4 <= l.cached + && l.cached <= SEQ_EMBEDDED + && SEQ_EMBEDDED + SEQ_SIZE <= NOTIFIER +} +const _: () = assert!(valid(&V25G83) && valid(&V26B123)); pub(crate) const SEL: [u32; 24] = [ 0x1a510, 0x1a420, 0x1a4d0, 0x1a4d8, 0x1a4e0, 0x1a4e8, 0x1a440, 0x1a458, 0x101d9, 0x1a089, diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 5adb19bb3d820..80bf1ff79a2b4 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -4,6 +4,7 @@ * and macros. The module pin is retain.c's. Built only with CONFIG_DRM_ASAHI_G16. */ #include +#include #include #include #include @@ -25,6 +26,8 @@ #include #include +#include "glue.h" + bool asahi_g16_board(void); int asahi_g16_display_prepare(struct device *dev); int asahi_g16_hold_power(struct device *dev); @@ -206,6 +209,15 @@ bool asahi_g16_board(void) return apple_pmp_t8132_retained_board(); } +/* + * The system counter frequency the boot loader programmed, in Hz: the clock the + * ADT counts GPU power sample periods in. + */ +u32 asahi_g16_timebase_hz(void) +{ + return arch_timer_get_cntfrq(); +} + /* * The first firmware start follows the native display the boot loader handed * over, as on J713 bring-up: defer until drm/apple has published it. A boot diff --git a/drivers/gpu/drm/asahi/g16/glue.h b/drivers/gpu/drm/asahi/g16/glue.h new file mode 100644 index 0000000000000..fb788f85fce96 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/glue.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ASAHI_G16_GLUE_H +#define _ASAHI_G16_GLUE_H + +u32 asahi_g16_timebase_hz(void); + +#endif /* _ASAHI_G16_GLUE_H */ diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 19405185174d1..43e3bf90e24cd 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -13,7 +13,7 @@ use kernel::{ use super::channel::Channel; use super::fw::graph::{self, job_list, notifier_page, qinfo, qstate, sched_ctx}; -use super::hw::{pte, sizes, tuning}; +use super::hw::{pte, sizes, tuning, FwAbi}; use super::object::{Class, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; @@ -137,6 +137,7 @@ impl QueueObjects { } fn init_queue( + abi: FwAbi, q: &FwObject, state: &FwObject, ring: &FwObject, @@ -145,7 +146,7 @@ fn init_queue( ) -> Result { q.write( 0, - &graph::queue_image(state.va, ring.va, list.va, q.va, context.va), + &graph::queue_image_for(abi.qinfo(), state.va, ring.va, list.va, q.va, context.va), )?; state.w32(qstate::CAP, sizes::QUEUE_CAP) } @@ -179,13 +180,14 @@ impl ComputeGraph { fw_stamp: q.fw_stamp, }) } - fn init(&self) -> Result { + fn init(&self, abi: FwAbi) -> Result { self.sched_ctx.write(0, &graph::context_image())?; init_notifier(&self.notifier, &self.threshold)?; self.notifier .w64(notifier_page::COMPUTE_RECORD, self.threshold.va)?; self.job_list.w64(job_list::SELF, self.job_list.va)?; init_queue( + abi, &self.qinfo, &self.qstate, &self.ring, @@ -241,11 +243,12 @@ impl RenderGraph { )?, }) } - fn init(&self) -> Result { + fn init(&self, abi: FwAbi) -> Result { init_notifier(&self.notifier, &self.threshold)?; for e in 0..2 { self.job_list[e].w64(job_list::SELF, self.job_list[e].va)?; init_queue( + abi, &self.qinfo[e], &self.qstate[e], &self.ring[e], @@ -281,8 +284,8 @@ impl Firmware { return Err(Error::from_errno(-(kernel::bindings::EPROTO as i32))); } } - self.graph.compute.init()?; - self.graph.render.init()?; + self.graph.compute.init(self.init.abi)?; + self.graph.render.init(self.init.abi)?; self.slots.init()?; self.init_render_pools(false)?; super::engine::wmb(); diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index a55d7c9bd0308..4c30ad932be62 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -109,6 +109,22 @@ pub(crate) mod t8132 { 0xa4, 0x07, 0xa6, 0xf2, 0x22, 0x6c, ], }, + FirmwareBuild { + // The 26B123 (macOS 27.2; 26B131 carries the same image) build b000 as loaded + // on a J773g, with every range iBoot fills zeroed (`BOOT_FILLED_26B123_B000`). + // DATA is the `fw-data` region: __DATA (0xd0000) and its __DATA_SHARED_RO tail + // (0x8000), which the boot loader reserves as one. + name: "Apple GFX 26B123 (build b000, iBoot-filled ranges zeroed)", + text_size: 0x64000, + data_size: 0xd8000, + entropy: &[[0x60a1b, 0x60afe]], + boot_filled: BOOT_FILLED_26B123_B000, + text_sha256: [ + 0x48, 0x4c, 0x43, 0xcb, 0x79, 0x89, 0x00, 0xdd, 0x14, 0x65, 0x4e, 0xd5, 0x4e, + 0xfe, 0x16, 0x24, 0xb4, 0x3d, 0xe3, 0xce, 0x80, 0x28, 0xb7, 0x71, 0x42, 0x5d, + 0x63, 0xbc, 0xc6, 0xa7, 0x2c, 0x92, + ], + }, ], }; @@ -117,8 +133,8 @@ pub(crate) mod t8132 { /// - the value of each of the 39 boot parameter records the header at 0x22c places from /// 0x5c8df to 0x5cb10 (a tag, a 32-bit length and the value: carveout addresses below the /// top of DRAM, a per-boot slide, the entropy); - /// - the entry count and the 0x34c-byte body of the two tunable tables at 0x5cb10 and 0x5ce60 - /// (headers 01/03 03 2a), which the shipped image leaves empty. + /// - the entry count and the 0x34c-byte body of the two tunable tables at 0x5cb10 and 0x5ce60, + /// which the shipped image leaves empty and iBoot populates per board. pub(crate) const BOOT_FILLED_25G83_B000: &[(u32, u32)] = &[ (0x224, 4), (0x23c, 8), @@ -166,8 +182,294 @@ pub(crate) mod t8132 { (0x5ce63, 1), (0x5ce64, 0x34c), ]; + + /// What iBoot writes into the 26B123 build b000 TEXT it loads: the same two header words and + /// the same 39 boot parameter records and two tunable tables as 25G83, which the 26B123 image + /// places 0x413c bytes later (the parameter records from 0x60a1b, the tables from 0x60c4c). + pub(crate) const BOOT_FILLED_26B123_B000: &[(u32, u32)] = &[ + (0x224, 4), + (0x23c, 8), + (0x60a23, 8), + (0x60a33, 8), + (0x60a43, 8), + (0x60a53, 8), + (0x60a63, 8), + (0x60a73, 8), + (0x60a83, 8), + (0x60a93, 4), + (0x60a9f, 1), + (0x60aa8, 8), + (0x60ab8, 8), + (0x60ac8, 4), + (0x60ad4, 8), + (0x60ae4, 1), + (0x60aed, 1), + (0x60af6, 8), + (0x60b06, 8), + (0x60b16, 8), + (0x60b26, 8), + (0x60b36, 8), + (0x60b46, 8), + (0x60b56, 8), + (0x60b66, 8), + (0x60b76, 8), + (0x60b86, 8), + (0x60b96, 8), + (0x60ba6, 8), + (0x60bb6, 4), + (0x60bc2, 8), + (0x60bd2, 4), + (0x60bde, 4), + (0x60bea, 8), + (0x60bfa, 8), + (0x60c0a, 1), + (0x60c13, 8), + (0x60c23, 8), + (0x60c33, 4), + (0x60c3f, 1), + (0x60c48, 4), + (0x60c4f, 1), + (0x60c50, 0x34c), + (0x60f9f, 1), + (0x60fa0, 0x34c), + ]; } +/// Which part of the loaded image a firmware page-table leaf maps. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Segment { + Text, + Data, +} + +/// One range of leaves the boot loader builds in the firmware's own page tables: offsets from +/// [`UPPER`], the segment whose physical pages back them (at the same offset from the segment's +/// start), and the exact leaf attribute bits. +pub(crate) struct Leaves { + pub(crate) range: Range, + pub(crate) segment: Segment, + pub(crate) attrs: u64, +} + +/// The firmware ABI a build speaks to the host: its InitData, device-control, queue-info and +/// work-item layouts (`fw::{initdata, channels, graph, work}`, selected in `fw/mod.rs`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum FwAbi { + V25G83, + V26B123, +} + +/// How the firmware's MMIO register table in loaded DATA is filled. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum LoaderTable { + /// The host writes the HW data register-map records at this DATA offset before the + /// initdata doorbell (the firmware's table must be empty on cold entry). + Host(u64), + /// The host leaves loaded DATA alone: the firmware copies every named register-map slot + /// and the SGX window from HW data itself while it parses InitData, as the T6041 and M5 + /// G16-family firmware do. + Firmware, +} + +/// How the host starts a firmware build: RTKit and the MMIO around RUN and the endpoints. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Start { + /// 25G83, as qualified on hardware: RTKit wake (IOP power INIT first), the firmware's crash + /// buffer mapped without a reply, the host generation word zeroed after the endpoints start + /// and a 100 ms receive-ring drain before InitData. + Wake25G83, + /// 26B123 start sequence: see [`start_27_2`]. + MacOs27_2, +} + +/// The 26B123 start sequence up to the InitData doorbell: +/// 1. before RUN, bit 0 of GFXCAXI2AF `+0x104` and `+0x108` is set (read, then written); +/// 2. RTKit boots without an IOP power request: HELLO 12, the crash-log endpoint starts while +/// the endpoint map is handled, the firmware's own crash buffer request (its shared RO +/// segment) is sent back unchanged, the host hands it a 0x8000-byte log buffer of its own +/// ([`MSG_LOG_BUFFER`], 8 pages at a host-window VA), then AP power state ON (0x20); +/// 3. the host block at SGX+0xd60000 is zeroed in [`HOST_BLOCK_ZERO_ORDER`], the scratch word +/// at SGX+0xd640c0 is read, [`HOST_READY`] is read and set to 1; +/// 4. endpoints 0x20 and 0x21 start and the InitData doorbell follows at once. +pub(crate) mod start_27_2 { + /// GFXCAXI2AF registers (register-map slot 22, PA 0x301000000), from SGX. + pub(crate) const AXI2AF: usize = 0x1000000; + /// The two GFXCAXI2AF words whose bit 0 the host sets before RUN. + pub(crate) const AXI2AF_ENABLES: [usize; 2] = [0x104, 0x108]; + /// The 32-bit writes of zero to the host block (SGX+0xd60000). + pub(crate) const HOST_BLOCK_ZERO_ORDER: [usize; 13] = [ + 0x00, 0x20, 0x40, 0x08, 0x28, 0x48, 0x10, 0x30, 0x50, 0x18, 0x38, 0x58, 0x60, + ]; + /// The host block word read and then set to 1 before the endpoints start. + pub(crate) const HOST_READY: usize = 0x60; + /// The scratch word read between zeroing the host block and setting [`HOST_READY`] (SGX offset). + pub(crate) const SCRATCH_PROBE: usize = 0xd640c0; + /// RTKit crash-log endpoint. + pub(crate) const EP_CRASHLOG: u8 = 1; + /// Host log buffer message on the crash-log endpoint: the size in 4 KiB pages (from ADT + /// `coredump-copy-buffer`) at bit 44 and the buffer's address below it. + pub(crate) const MSG_LOG_BUFFER: u64 = 0x9 << 52; + pub(crate) const MSG_LOG_BUFFER_PAGES_SHIFT: u32 = 44; + pub(crate) const MSG_LOG_BUFFER_ADDR_MASK: u64 = (1 << 44) - 1; +} + +/// The two magic words of the PPL handoff page. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct PplMagic { + /// What the AP publishes at +0. + pub(crate) ap: u64, + /// The only non-zero value +8 may hold at cold admission: what the firmware leaves there + /// once it has run. + pub(crate) firmware: u64, + /// The firmware stores `firmware` at +8 from its MMU setup, before the RTKit handshake. + pub(crate) answers: bool, +} + +/// The loaded-image layout of one firmware ABI: the boot loader's handoff for it, the regions +/// it reserves, the leaves it builds in the firmware page tables, and where the boot path writes. +pub(crate) struct FwLayout { + pub(crate) name: &'static str, + /// `apple,g16-handoff-version`, `apple,firmware-segment-vas` and `-flags`. + pub(crate) handoff_version: u32, + pub(crate) segment_vas: &'static [u64], + pub(crate) segment_flags: &'static [u32], + /// Sizes of the reserved `fw-text` and `fw-data` regions (`fw-data` holds every segment + /// after TEXT). + pub(crate) text_size: u64, + pub(crate) data_size: u64, + /// The firmware ABI of the builds this layout holds. + pub(crate) abi: FwAbi, + /// Every leaf the boot loader builds in the firmware's own page tables, in VA order, and + /// the only leaves cold admission accepts (none: the firmware builds its own tree at + /// start); `None` until known, which refuses the firmware. + pub(crate) leaves: Option<&'static [Leaves]>, + /// The PPL handoff page's magic words; `None` until known, which refuses the firmware. + pub(crate) ppl_magic: Option, + /// How the firmware's register table in loaded DATA is filled; `None` until known, which + /// refuses the firmware. + pub(crate) loader_table: Option, + /// How the host starts this firmware. + pub(crate) start: Start, + /// Where on the PPL handoff page the firmware records whether the GPU is powered, for a + /// firmware that powers it down while idle; `None` for one that keeps it powered while it + /// runs. While that byte is 0 the host reads no GPU register. + pub(crate) powered: Option, +} + +impl FwLayout { + /// Whether a boot loader's handoff describes this layout. + pub(crate) fn matches(&self, version: u32, vas: &[u64], flags: &[u32]) -> bool { + version == self.handoff_version && vas == self.segment_vas && flags == self.segment_flags + } + + /// What a firmware start needs that is not known for this layout yet; empty when the + /// firmware can be started. + pub(crate) fn unknown(&self) -> impl Iterator { + [ + self.leaves + .is_none() + .then_some("the leaves the boot loader builds in the firmware page tables"), + self.ppl_magic + .is_none() + .then_some("the PPL handoff magic words"), + self.loader_table.is_none().then_some( + "whether the host writes the register map into the firmware's table in \ + loaded DATA or the firmware copies it from HW data", + ), + ] + .into_iter() + .flatten() + } +} + +/// 25G83 (macOS 26.x): __TEXT 0x60000, __DATA 0x13c000. +pub(crate) const FW_25G83: FwLayout = FwLayout { + name: "25G83", + handoff_version: 1, + segment_vas: &[UPPER, UPPER + 0x60000], + segment_flags: &[1, 0], + text_size: 0x60000, + data_size: 0x13c000, + abi: FwAbi::V25G83, + leaves: Some(&[ + Leaves { + range: 0..0x50000, + segment: Segment::Text, + attrs: 0x4c3, + }, + Leaves { + range: 0x50000..0x58000, + segment: Segment::Text, + attrs: 0x483, + }, + Leaves { + range: 0x58000..0x60000, + segment: Segment::Text, + attrs: 0x4c3, + }, + Leaves { + range: 0x60000..0x6c000, + segment: Segment::Data, + attrs: 0x00200000000004c3, + }, + Leaves { + range: 0x6c000..0x19c000, + segment: Segment::Data, + attrs: 0x0460000000000443, + }, + ]), + // The 25G83 firmware never writes +8; the AP's magic there is accepted. + ppl_magic: Some(PplMagic { + ap: PPL_MAGIC, + firmware: PPL_MAGIC, + answers: false, + }), + loader_table: Some(LoaderTable::Host(0x1332f0)), + start: Start::Wake25G83, + // The GPU stays powered from START until the firmware stops. + powered: None, +}; + +/// 26B123 (macOS 27.2, also 26B131): __TEXT 0x64000, __DATA 0xd0000 and a __DATA_SHARED_RO +/// 0x8000 right after it (aura's handoff version 2; `fw-data` covers both, so the RTKit crash +/// log at the start of the shared read-only segment lies inside it). +/// +/// The boot loader leaves the page-table region zero and the firmware builds its own tree +/// (root, the L2 at +0x4000 and the L3 at +0x8000, with the TEXT and DATA leaves) when it +/// starts, so only an empty tree is admitted. Once it has set up its MMU the firmware leaves +/// 0x4b1d000000000003 at +8 of the PPL handoff page (the 25G83 firmware never wrote there). +/// The AP announces the same word at +0 before RUN, as the G14 firmware-27.2 path does on +/// hardware (linux#2544: AP and firmware exchange 0x4b1d000000000003 through these two words, +/// the firmware answering before the RTKit handshake). The host leaves loaded DATA alone: the +/// firmware takes the register map from HW data while it parses InitData, the T6041 build of +/// this firmware starts on hardware without any DATA write (linux#1954), and 27.2 marks DATA +/// data-isolated. Its register table is at DATA + 0xc72e8 (60 slots). +pub(crate) const FW_26B123: FwLayout = FwLayout { + name: "26B123", + handoff_version: 2, + segment_vas: &[UPPER, UPPER + 0x64000, UPPER + 0x134000], + segment_flags: &[1, 0x10, 0], + text_size: 0x64000, + data_size: 0xd8000, + abi: FwAbi::V26B123, + // The firmware builds its own tree at start; admit only an empty tree. + leaves: Some(&[]), + ppl_magic: Some(PplMagic { + ap: PPL_MAGIC_27_2, + firmware: PPL_MAGIC_27_2, + answers: true, + }), + loader_table: Some(LoaderTable::Firmware), + start: Start::MacOs27_2, + // The firmware powers the GPU down after its idle delay (region C 0x9c0) and back up for + // the next work, under the PPL handoff lock, and sets this byte to 1 after each power-up + // and to 0 after each power-down. + powered: Some(0x648), +}; + +/// The firmware layouts this backend knows, newest last. +pub(crate) const FW_LAYOUTS: &[&FwLayout] = &[&FW_25G83, &FW_26B123]; + /// User VA range reported as `vm_start..vm_end`: 42 bits with the final two pages excluded. pub(crate) const USER_RANGE: Range = 0x4000..0x3ffffff8000; @@ -209,8 +511,10 @@ pub(crate) mod pte { pub(crate) const LEAF_PB_LIST: u64 = 0x00e0000000000c03; } -/// PPL handoff magic. +/// PPL handoff magic the AP publishes for the 25G83 firmware. pub(crate) const PPL_MAGIC: u64 = 0x4b1d000000000002; +/// The PPL handoff magic of the 27.2 (26B123) GPU firmware, published by both sides. +pub(crate) const PPL_MAGIC_27_2: u64 = 0x4b1d000000000003; /// UAT handoff region sizes of this firmware ABI (TTBAT page, TTBAT tables (the firmware kernel /// root), PPL handoff page, shared L2 page); the addresses come from the ADT. @@ -267,10 +571,17 @@ pub(crate) mod client { pub(crate) const CLIENT_APERTURE: Range = 0x7000000000..0x7100000000; pub(crate) const COMPACT_WINDOW: Range = 0x1000000000..0x9000000000; - // Two persistent compute units, each in its own 64 MiB interval and reused across - // application queues. Every alias is inside Mesa's reserved driver hole. + // Persistent compute units, each in its own 64 MiB interval and reused across + // application queues. Units 0 and 1 keep their original placement below the render + // allocators; further units (up to [`super::sizes::COMPUTE_UNITS`]) live between the + // unused CT window and the PB heap, clear of the dynamic PB page-list range + // 0x7040000000..0x7080000000. Every alias is inside Mesa's reserved driver hole. pub(crate) const fn compute_base(k: u64) -> u64 { - 0x7001000000 + k * 0x04000000 + if k < 2 { + 0x7001000000 + k * 0x04000000 + } else { + 0x7090000000 + (k - 2) * 0x04000000 + } } pub(crate) const fn compute_pool(k: u64) -> u64 { compute_base(k) @@ -365,13 +676,20 @@ pub(crate) mod sizes { pub(crate) const PB_BLOCKS: u32 = 2048; pub(crate) const PB_LIST_RECORDS: u32 = 4096; pub(crate) const PB_GROW_STEP: u32 = 10; - /// The qualified M4 protocol permits only one published command at a time. - pub(crate) const FLIGHTS: usize = 1; + /// Published prefixes at most. A render is published only with nothing else in flight; + /// compute commands may queue behind each other on the one firmware compute queue, each + /// in its own retained unit ([`COMPUTE_UNITS`]). + pub(crate) const FLIGHTS: usize = 16; + /// Retained compute units per VM at most; each unit owns its own hardware UMA slot + /// (`COMPUTE_UMA_SLOT + index`). A unit is reused only after a later publication retired + /// (it displaced the unit), so `n` units keep up to `n - 1` compute commands in flight. + pub(crate) const COMPUTE_UNITS: usize = 8; + const _: () = assert!(super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP); /// Inherited diagnostic histogram width; M4 does not fold jobs into a compute horizon. pub(crate) const HORIZON_JOBS: u32 = 1; - /// Two jobs may be admitted per logical queue so exact prior-command dependencies can - /// advance independently of a preceding job's aggregate fence. Firmware stays serialized. - pub(crate) const SCHEDULER_CREDITS: u32 = 2; + /// Jobs admitted to the engine per logical queue: enough to keep a queue's compute + /// commands in flight back to back; exact prior-command dependencies still gate each one. + pub(crate) const SCHEDULER_CREDITS: u32 = 16; /// Unconsumed records per 256-entry channel ring a prefix may be posted behind. pub(crate) const AHEAD_RECORDS: u32 = 64; /// Policy bound on logical queues reported in QUEUE_LIMITS (not a firmware limit). diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index f022689ad0878..01861b790a62d 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -1,22 +1,25 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT //! Owned J713 initdata: 31 inventory objects, 12 submit channel pairs and the -//! exact 42-entry MMIO loader. All bytes are encoded in fresh GEM backing before -//! the boot owner publishes a root or loader address. Firmware-reachable -//! backing and mappings are retained by `Objects` until reboot. +//! exact MMIO register map, in the layout of the admitted firmware's ABI. All bytes are +//! encoded in fresh GEM backing before the boot owner publishes a root or loader address. +//! Firmware-reachable backing and mappings are retained by `Objects` until reboot. use kernel::{device, prelude::*, sync::Arc}; use super::adt::GpuAdt; use super::board; +use super::boot::glue; use super::channel::{Channels, Ring}; -use super::fw::initdata::{self as wire, control, globals, id, ready_control}; -use super::hw; +use super::fw::initdata::{self as wire, id, ready_control}; +use super::hw::{self, FwAbi}; use super::object::{Class, FwObject, Objects, Placement, Request}; /// Firmware graph handles. The small root.Control and large FirmwareData are /// intentionally separate: only the former carries the READY acknowledgement. pub(crate) struct InitData { + /// The firmware ABI these objects were encoded for. + pub(crate) abi: FwAbi, pub(crate) globals: Option>, /// Recovery/scheduler owner: root.FirmwareData, not the small Control. pub(crate) control: Option>, @@ -40,7 +43,8 @@ pub(crate) struct InitData { root: Arc, /// Rows of the board's firmware performance table, including off. pub(crate) rows: u32, - loader: [u8; wire::LOADER_BYTES], + /// The register-map records, slot 0 through the highest filled one. + loader: KVec, /// The complete inventory, including firmware-only log and retention data. _graph: KVec>, } @@ -50,14 +54,24 @@ impl InitData { Ok(self.root.va) } - /// Exact Main loader records which the boot owner publishes to firmware DATA. - pub(crate) fn loader_bytes(&self) -> &[u8; wire::LOADER_BYTES] { + /// Exact Main register-map records, which the boot owner publishes to firmware DATA when + /// the layout has the host write them. + pub(crate) fn loader_bytes(&self) -> &[u8] { &self.loader } + /// The FirmwareData words of this ABI. + pub(crate) fn firmware_data(&self) -> &'static wire::FirmwareData { + &self.abi.initdata().firmware_data + } + /// A phase 1 or 3 stop is owned by the M4 recovery handshake. pub(crate) fn halted(&self) -> Result { - let phase = self.control.as_ref().ok_or(ENODEV)?.r32(control::PHASE)?; + let phase = self + .control + .as_ref() + .ok_or(ENODEV)? + .r32(self.firmware_data().phase)?; Ok(phase == 1 || phase == 3) } @@ -84,13 +98,15 @@ pub(crate) fn build( adt: &GpuAdt, objects: &mut Objects, ) -> Result<(InitData, Channels, u32)> { + let abi = adt.layout.abi; + let layout = abi.initdata(); let performance = board::qualify(dev, adt)?; // The top row: S9 on J713, S10 on J773g. let ceiling = performance.count as u32 - 1; let rows = performance.count as u32; let max_khz = performance.frequency[ceiling as usize] * 1000; let mut graph = KVec::with_capacity(wire::OBJECT_COUNT, GFP_KERNEL)?; - for (i, size) in wire::OBJECT_SIZE.iter().copied().enumerate() { + for (i, size) in layout.object_size.iter().copied().enumerate() { let lower = match i { id::UMA => Some(wire::BOOTSTRAP_START), id::PARAMETER => Some(wire::BOOTSTRAP_START + 0x8000), @@ -139,8 +155,75 @@ pub(crate) fn build( // The host never posts on this firmware-only control channel. pair(&graph, id::FWCTL, id::FWCTL), )?; + // The GPU power sample period: `gpu-pwr-sample-period-aic-clks` gives the exact hardware + // sample period in system-counter ticks (e.g. 200000 ticks at 24 MHz = 8333 us), whereas + // `gpu-power-sample-period` is the coarse truncated integer millisecond period (8 ms). + // Power config +4/+8 take the exact AIC ticks; the us sampling slots and average-power + // filter sample count use the exact us period, while the low-peak (PPM) limiter filter + // uses the coarse ms period, matching `drivers/gpu/drm/asahi/initdata.rs`. + let timebase_hz = glue::timebase_hz(); + let timebase_khz = timebase_hz / 1000; + let Some(power_sample_clks) = adt.performance.power_sample_clks else { + dev_err!( + dev, + "G16: the ADT gives no GPU power sample period (gpu-pwr-sample-period-aic-clks)\n" + ); + return Err(EINVAL); + }; + let power_sample_us = (u64::from(power_sample_clks) * 1_000_000) + .checked_div(u64::from(timebase_hz)) + .and_then(|us| u32::try_from(us).ok()) + .unwrap_or(0); + let power_sample_period_ms = adt.performance.power_sample_period_ms.unwrap_or(0); + let avg_power_filter_tc_ms = adt.performance.avg_power_filter_tc_ms.unwrap_or(0); + let lowpeak_limiter_tc_ms = adt.performance.lowpeak_limiter_tc_ms.unwrap_or(0); + let lowpeak_limiter_ki_q16 = adt.performance.lowpeak_limiter_ki_q16.unwrap_or(0); + let lowpeak_limiter_kp_q16 = adt.performance.lowpeak_limiter_kp_q16.unwrap_or(0); + if layout.power_sampling.is_some() && (power_sample_us == 0 || avg_power_filter_tc_ms == 0) { + dev_err!( + dev, + "G16: the ADT lacks GPU power sampling parameters (power_sample_us={}, cpu-avg-limiter-input-tc={})\n", + power_sample_us, + avg_power_filter_tc_ms + ); + return Err(EINVAL); + } + if layout.power_limiter.is_some() + && (power_sample_period_ms == 0 + || timebase_khz == 0 + || lowpeak_limiter_tc_ms == 0 + || lowpeak_limiter_ki_q16 == 0 + || lowpeak_limiter_kp_q16 == 0) + { + dev_err!( + dev, + "G16: the ADT lacks GPU low-peak power limiter parameters (period_ms={}, tc_ms={}, ki={}, kp={})\n", + power_sample_period_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16 + ); + return Err(EINVAL); + } + let coredump_copy_size = u64::from(adt.performance.coredump_copy_size.unwrap_or(0)); + if layout.coredump_copy.is_some() && coredump_copy_size == 0 { + dev_err!( + dev, + "G16: the ADT gives no GPU crash copy buffer size (coredump-copy-buffer)\n" + ); + return Err(EINVAL); + } let mut input = wire::Input { performance, + power_sample_clks, + power_sample_us, + power_sample_period_ms, + timebase_khz, + avg_power_filter_tc_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16, + coredump_copy_size, va: [0; wire::OBJECT_COUNT], channel_state: [0; 12], channel_ring: [0; 12], @@ -159,7 +242,8 @@ pub(crate) fn build( input.channel_ring[i] = channels.submit[i].ring.va; } for (slot, entry) in wire::LOADERS.iter().enumerate() { - if entry.length == 0 { + // An empty record, or one this ABI has no slot for, is neither mapped nor described. + if entry.length == 0 || layout.slot(slot).is_none() { continue; } let offset = entry.pa & (wire::PAGE - 1); @@ -179,7 +263,7 @@ pub(crate) fn build( // Private CPU-side staging keeps the pure encoder independent of raw GEM // pointers. No staging references survive publication. let mut images = KVec::with_capacity(wire::OBJECT_COUNT, GFP_KERNEL)?; - for size in wire::OBJECT_SIZE { + for size in layout.object_size { images.push(KVVec::from_elem(0u8, size, GFP_KERNEL)?, GFP_KERNEL)?; } { @@ -189,13 +273,19 @@ pub(crate) fn build( } let array: &mut [&mut [u8]; wire::OBJECT_COUNT] = (&mut slices[..]).try_into().map_err(|_| EINVAL)?; - wire::encode(array, &input, ceiling).map_err(|()| EINVAL)?; + wire::encode_for(layout, array, &input, ceiling).map_err(|()| EINVAL)?; } - let mut loader = [0u8; wire::LOADER_BYTES]; - loader.copy_from_slice(&images[id::MAIN][0x640..0x640 + wire::LOADER_BYTES]); + let records = layout.loader_records(); + let mut loader = KVec::with_capacity(records * wire::LOADER_STRIDE, GFP_KERNEL)?; + loader.extend_from_slice( + images[id::MAIN] + .get(0x640..0x640 + records * wire::LOADER_STRIDE) + .ok_or(EINVAL)?, + GFP_KERNEL, + )?; // Host startup policy: Main and PowerPerformance contain the top row, but the // published selectors remain S1 until the thermal owner admits a raise. - for at in globals::PSTATE_SELECTORS { + for at in layout.pstate_selectors { images[id::GLOBALS][at..at + 4].copy_from_slice(&100u32.to_le_bytes()); } for i in 0..wire::OBJECT_COUNT { @@ -204,11 +294,14 @@ pub(crate) fn build( dev_info!( dev, - "M4 initdata: 31 objects, 12 submit channel pairs, 42 loader records, S1 startup (S{} tables)\n", + "M4 initdata ({}): 31 objects, 12 submit channel pairs, {} register-map slots, S1 startup (S{} tables)\n", + layout.name, + records, ceiling ); Ok(( InitData { + abi, globals: Some(graph[id::GLOBALS].clone()), control: Some(graph[id::FIRMWARE_DATA].clone()), ready_control: Some(graph[id::CONTROL].clone()), diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 0f26cb3276738..24b8dd2de3fb0 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -536,13 +536,14 @@ impl Objects { self.pages } - /// Bounded live UAT ownership checks; no user leaf walk and no firmware memory repair. + /// Bounded live checks of the host window; no user leaf walk and no firmware memory repair. + /// The UAT's context bindings are checked by [`super::boot::Session::check`], which every + /// caller runs just before this. pub(crate) fn health(&mut self) -> Result { if let Some(error) = self.error { return Err(error); } - self.window.lock().check()?; - self.uat.check_adopted_bindings() + self.window.lock().check() } /// Allocates and maps a zeroed firmware object. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e384e30a02411..d9dabde95472b 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -56,25 +56,6 @@ impl HrTimerCallback for Shared { } } -/// The `aurora-g16/tune` debugfs file: current tunables. -fn tune_show(_shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { - super::params::tune::show(f) -} - -/// The `aurora-g16/tune` debugfs file: `name=value` lines. -fn tune_write(_shared: &Arc, reader: &mut kernel::uaccess::UserSliceReader) -> Result { - let mut buf = [0u8; 128]; - let len = reader.len().min(buf.len()); - reader.read_slice(&mut buf[..len])?; - let text = core::str::from_utf8(&buf[..len]).map_err(|_| EINVAL)?; - for line in text.split(|c| c == '\n' || c == ' ' || c == ',') { - if !line.trim().is_empty() { - super::params::tune::set(line)?; - } - } - Ok(()) -} - /// The `aurora-g16/stats` debugfs file contents. fn stats_show(shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { let state = shared.state.lock(); @@ -221,15 +202,10 @@ impl Shared { dir.read_callback_file(c_str!("stats"), self.clone(), &stats_show), GFP_KERNEL, )?; - let tune = KBox::pin_init( - dir.read_write_callback_file(c_str!("tune"), self.clone(), &tune_show, &tune_write), - GFP_KERNEL, - )?; let mut state = self.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; firmware.engine.shared = Some(self.clone()); firmware.engine.debugfs = Some(file); - firmware.engine.tune_file = Some(tune); Ok(()) } } @@ -273,7 +249,9 @@ impl Firmware { lap.lap(&mut self.engine.prof.retire_ns); self.answer_growth()?; self.check_hangs(done)?; - let published = self.publish(done); + let published = self + .service_power() + .and_then(|()| self.publish_checked(done)); let s = &mut self.engine.stats; if self.engine.flights.is_empty() && s.idle_from_ns != 0 { // Idle with nothing ready is not a gap: the clients are late. @@ -329,6 +307,33 @@ impl Firmware { o.r32(offset) } + /// A compute unit's GPU start and end ticks. 25G83 writes them into the unit's ITS pair; + /// ABIs with `work_ticks` leave ITS 0/0 and write them into the work object. The ITS pair + /// is used whenever it holds an interval. + fn compute_ticks(&self, unit: &super::slots::ComputeSlot) -> Result<(u64, u64)> { + let (start, end) = (unit.its.r64(0)?, unit.its.r64(8)?); + if start != 0 && end > start { + return Ok((start, end)); + } + let Some((start_off, end_off)) = self.init.abi.compute().work_ticks else { + return Ok((start, end)); + }; + let w = &unit.work; + // Work tick offsets are 4-byte aligned (not 8-byte), so read hi/lo/hi to avoid tearing. + let at = |o: usize| -> Result { + for _ in 0..4 { + let hi1 = w.r32(o + 4)?; + let lo = w.r32(o)?; + let hi2 = w.r32(o + 4)?; + if hi1 == hi2 { + return Ok(u64::from(lo) | (u64::from(hi1) << 32)); + } + } + Err(EIO) + }; + Ok((at(start_off)?, at(end_off)?)) + } + /// Exact M4 queue and submit-pipe proof for one serialized publication. Event /// notifications are wakeups; neither an event nor elapsed time releases an owner. pub(crate) fn queue_receipt( @@ -355,7 +360,7 @@ impl Firmware { return Ok(false); } } - if info.r32(0x80)? != 0 { + if info.r32(self.init.abi.qinfo().busy)? != 0 { return Ok(false); } } @@ -435,8 +440,7 @@ impl Firmware { let k = f.claims.slot[0] as usize; let unit = f.job.resources.compute_unit(k)?; let submitted = unit.counter.r64(0)?; - let start = unit.its.r64(0)?; - let end = unit.its.r64(8)?; + let (start, end) = self.compute_ticks(unit)?; let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; full &= stamp_reached(stamp, f.target, e.target) && (stamp != f.target @@ -456,8 +460,7 @@ impl Firmware { let k = f.claims.slot[0] as usize; let unit = f.job.resources.compute_unit(k)?; let submitted = unit.counter.r64(0)?; - let start = unit.its.r64(0)?; - let end = unit.its.r64(8)?; + let (start, end) = self.compute_ticks(unit)?; full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot && submitted != 0 @@ -519,14 +522,11 @@ impl Firmware { Ok(Retirement::Pending) } - /// Logs the non-zero fault banks of `state`. + /// Logs the fault bank of `state` when it holds a fault. #[allow(dead_code)] pub(crate) fn log_fault(&self, state: &EngineState) { - for bank in 0..2 { - let (f, va) = (state.status[bank], state.address[bank]); - if f == 0 { - continue; - } + let (bank, f, va) = (state.bank, state.status, state.address); + if f != 0 { let access = if (f >> 4) & 1 != 0 { "read" } else { "write" }; let reason = if (f >> 1) & 7 != 0 { "reason!=unmapped" @@ -584,9 +584,7 @@ impl Firmware { let committed = f.pb.as_ref().ok_or(EINVAL).and_then(|epoch| { let k = timestamp_claims.pass[0] as usize; self.pools.retire_binding(k, epoch)?; - let enabled = params::pb_reuse(); - self.pools - .retire_epoch(enabled, k, f.pb_binding, result.is_ok()); + self.pools.retire_epoch(k, f.pb_binding, result.is_ok()); Ok(()) }); if let Err(error) = committed { @@ -890,7 +888,12 @@ impl Firmware { let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); let ch = &self.channels; let rd = |o: &super::object::FwObject, off| o.r32(off).unwrap_or(0xdeadbeef); - let state = self.session.regs.engine_state().unwrap_or_default(); + let state = self + .session + .engine_state() + .ok() + .flatten() + .unwrap_or_default(); let f = e.oldest(); let ms = f.map_or(0, |f| now_ns().wrapping_sub(f.published_ns) / 1_000_000); @@ -1099,7 +1102,6 @@ impl Firmware { s.hold[1], s.hold[2] )?; - super::params::tune::show(f)?; } let p = &self.engine.prof; writeln!( diff --git a/drivers/gpu/drm/asahi/g16/power.rs b/drivers/gpu/drm/asahi/g16/power.rs index ae07876b3b45b..1de8da0bdcc4c 100644 --- a/drivers/gpu/drm/asahi/g16/power.rs +++ b/drivers/gpu/drm/asahi/g16/power.rs @@ -20,15 +20,20 @@ pub(crate) mod policy; use core::{ffi::c_void, ptr::NonNull}; use kernel::{device, prelude::*, sync::aref::ARef}; -use super::fw::initdata::globals; +use super::fw::initdata; use super::recovery::now_ns; use super::regs::wmb; use super::Firmware; use policy::{COOLING_MAX, TOP_DEFAULT}; -static_assert!(globals::PSTATE_SELECTORS[0] == 0x88); -static_assert!(globals::PSTATE_SELECTORS[1] == 0x8c); -static_assert!(globals::PSTATE_SELECTORS[2] == 0x98); +// The three Globals p-state selectors: 0x88, 0x8c and 0x98 in 25G83; four bytes later in +// 26B123, which inserted a word at 0x38. +static_assert!(initdata::V25G83.pstate_selectors[0] == 0x88); +static_assert!(initdata::V25G83.pstate_selectors[1] == 0x8c); +static_assert!(initdata::V25G83.pstate_selectors[2] == 0x98); +static_assert!(initdata::V26B123.pstate_selectors[0] == 0x8c); +static_assert!(initdata::V26B123.pstate_selectors[1] == 0x90); +static_assert!(initdata::V26B123.pstate_selectors[2] == 0x9c); extern "C" { fn asahi_g16_clpc_gpu_get(dev: *mut c_void, out: *mut *mut c_void) -> core::ffi::c_int; @@ -287,7 +292,7 @@ impl Firmware { return Ok(()); } let globals = self.init.globals.as_ref().ok_or(ENODEV)?; - for offset in globals::PSTATE_SELECTORS { + for offset in self.init.abi.initdata().pstate_selectors { globals.w32(offset, target * 100)?; } wmb(); diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 18975b812e276..f1aa0f417c028 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -21,8 +21,13 @@ use kernel::{ use logic::{RecoveryAction, Retirement, SnapshotEntry}; use super::job::{Completions, Job}; +use super::regs::wmb; use super::{params, Firmware}; +/// S1, the lowest powered row of the firmware DVFS table, as the Globals p-state selectors +/// express it (hundredths of a state). The host starts the firmware there too. +const FLOOR_SELECTOR: u32 = 100; + /// Monotonic time, ns. pub(crate) fn now_ns() -> u64 { ::ktime_get() as u64 @@ -126,7 +131,9 @@ impl Firmware { } pub(crate) fn recovery_pending(&self) -> Result { - Ok(self.recovery.running || self.new_recovery() || self.firmware_r32(logic::PHASE)? != 0) + Ok(self.recovery.running + || self.new_recovery() + || self.firmware_r32(self.init.firmware_data().phase)? != 0) } pub(crate) fn recovery_idle(&self) -> Result { @@ -235,6 +242,7 @@ impl Firmware { pub(crate) fn fail_stop(&mut self, error: Error, done: &mut Completions) { if self.recovery.failed.is_none() { self.recovery.failed = Some(error); + self.floor_power(error); } self.engine.frozen = true; self.events.grow.clear(); @@ -249,6 +257,60 @@ impl Firmware { } } + /// A failed device must not stay at its last performance request: the J773g idled at 98 C + /// after a fail-stop, against 83 C with the GPU idle. The Globals ceiling selectors are + /// host-owned (`service_power` writes them at runtime and stops after a failure): drop them + /// to S1 and log the one fail-stop summary. Nothing firmware-owned is touched, and no GPU + /// register is read. + fn floor_power(&mut self, error: Error) { + let before = self.power.effective; + let selectors = self.init.abi.initdata().pstate_selectors; + let mut ok = 0usize; + let mut failed = 0usize; + if let Some(globals) = self.init.globals.as_ref() { + // Write every selector without short-circuiting so a single write error cannot + // leave the remaining selectors unfloored. + for offset in selectors { + match globals.w32(offset, FLOOR_SELECTOR) { + Ok(()) => ok += 1, + Err(write_err) => { + failed += 1; + dev_err!( + self.dev(), + "G16: fail-stop: failed to floor Globals +{:#x}: {:?}\n", + offset, + write_err + ); + } + } + } + } + if ok != 0 { + wmb(); + } + let all_floored = ok == selectors.len() && failed == 0; + if all_floored { + self.power.effective = 1; + } + let outcome = if all_floored { + "S1" + } else if ok != 0 { + "partial S1" + } else { + "unchanged (Globals unwritable)" + }; + dev_err!( + self.dev(), + "G16: fail-stop ({:?}): host ceiling S{} -> {} ({}/{} selectors written), temperature {} mC\n", + error, + before, + outcome, + ok, + selectors.len(), + self.power.temperature_mc + ); + } + /// Flights own firmware-visible resources and slot claims. Failed-stop /// flights are retained whole, never released to the free slot lists. pub(crate) fn fail_flights(&mut self, error: Error, done: &mut Completions) { @@ -288,16 +350,18 @@ impl Firmware { fn firmware_generation(&self) -> Result { // The firmware is stopped while its published generation is consumed. - let lo = self.firmware_r32(logic::GENERATION)?; - let hi = self.firmware_r32(logic::GENERATION + 4)?; + let generation = self.init.firmware_data().generation; + let lo = self.firmware_r32(generation)?; + let hi = self.firmware_r32(generation + 4)?; Ok(u64::from(lo) | (u64::from(hi) << 32)) } /// Resolve the snapshot while the firmware is stopped. A missing retained /// owner prevents acknowledgement: its failure cannot safely be attributed. fn mark_recovery(&mut self, stage: [u32; 3], event: u32, asid: Option) -> Result { - for i in 0..logic::SNAPSHOT_ENTRIES { - let offset = logic::SNAPSHOT + i * 8; + let data = self.init.firmware_data(); + for i in 0..data.snapshot_entries { + let offset = data.snapshot + i * 8; let flags = self.firmware_r32(offset)?; let target = self.firmware_r32(offset + 4)?; let Some(entry) = SnapshotEntry::decode(flags, target) else { @@ -327,12 +391,11 @@ impl Firmware { // These frontiers must be captured before the host answers 2: the // firmware can force the stage target while aborting a work item. let stage = self.recovery_snapshot()?; - let fault = self.session.regs.engine_state()?; - let asid = fault - .status - .iter() - .find(|status| **status & 1 != 0) - .map(|status| ((*status >> 17) & 0x3f) as u32) + // Powered down, the GPU holds no fault to read. + let fault = self.session.fault_scan()?.unwrap_or_default(); + let asid = Some(fault.status) + .filter(|status| status & 1 != 0) + .map(|status| ((status >> 17) & 0x3f) as u32) .filter(|asid| *asid >= 1); let deadline = start.saturating_add(logic::RECOVERY_BUDGET_NS); let mut answered = false; @@ -346,7 +409,7 @@ impl Firmware { dev_err!(self.dev(), "M4 GPU recovery exceeded 1000 ms\n"); return Err(ETIMEDOUT); } - let phase = self.firmware_r32(logic::PHASE)?; + let phase = self.firmware_r32(self.init.firmware_data().phase)?; let current_generation = if phase == 1 || phase == 3 { self.firmware_generation()? } else { @@ -376,13 +439,13 @@ impl Firmware { self.mark_recovery(stage, event, asid)?; // Snapshot reads and all TPC repairs precede acknowledgement. barrier(); - self.firmware_w32(logic::PHASE, 2)?; + self.firmware_w32(self.init.firmware_data().phase, 2)?; barrier(); answered = true; } RecoveryAction::Resume => { barrier(); - self.firmware_w32(logic::PHASE, 0)?; + self.firmware_w32(self.init.firmware_data().phase, 0)?; barrier(); self.recovery.recoveries += 1; self.recovery.errors_seen = self.events.errors; diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index 4d8bcb716eda5..413c2be0ecef2 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -25,11 +25,8 @@ pub(crate) const fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool dh <= dc && dc <= dt } -/// FirmwareData words and affected-work snapshot geometry. -pub(crate) const SNAPSHOT: usize = 0x40b8; -pub(crate) const SNAPSHOT_ENTRIES: usize = 448; -pub(crate) const GENERATION: usize = 0x4fa0; -pub(crate) const PHASE: usize = 0x4fb0; +// The FirmwareData words (phase, generation, affected-work snapshot) are per firmware ABI: +// `fw::initdata::FirmwareData`. pub(crate) const RECOVERY_BUDGET_NS: u64 = 1_000_000_000; pub(crate) const EVENT_WAIT_NS: u64 = 50_000_000; pub(crate) const WINDOW_NS: u64 = 10_000_000_000; @@ -227,8 +224,6 @@ mod tests { .event, 15 ); - assert_eq!(SNAPSHOT + SNAPSHOT_ENTRIES * 8, 0x4eb8); - assert!(SNAPSHOT + SNAPSHOT_ENTRIES * 8 <= GENERATION); } #[test] @@ -246,7 +241,6 @@ mod tests { #[test] fn deadlines_are_absolute_and_do_not_wrap() { - assert_eq!(PHASE, 0x4fb0); let first_record_ns = 5_000_000_000; let deadline = first_record_ns + RECOVERY_BUDGET_NS; assert!(!expired(deadline, deadline)); diff --git a/drivers/gpu/drm/asahi/g16/regs.rs b/drivers/gpu/drm/asahi/g16/regs.rs index e264e319c2a64..74b8fd7a43417 100644 --- a/drivers/gpu/drm/asahi/g16/regs.rs +++ b/drivers/gpu/drm/asahi/g16/regs.rs @@ -7,7 +7,8 @@ //! (`+0x1500` core mask, `+0x1000` pstate), status `+0xc000` //! (`+0x20`/`+0x120` busy, `+0x1800` bank select, `+0x18c0` fault status, `+0x18c8` fault //! address >> 6). ASC `+0x44` bit 4 is RUN (mapped from `asc` here; the shared layer does not -//! map it). No blind reads of unpowered blocks: read only after the AGX vote. +//! map it). No blind reads of unpowered blocks: read only after the AGX vote (25G83) or, on +//! 26B123, after admission holds the GPU's power domain and GFXCAXI2AF is enabled. //! //! The status window needs 64-bit stores (the fault bank select), which the shared accessors do //! not offer, so it is mapped here, as is `asc`. This module also holds the [`Mapping`] type the @@ -21,6 +22,8 @@ use kernel::{ prelude::*, }; +use core::sync::atomic::{AtomicU32, Ordering}; + use crate::regs::G16Resources; /// Write memory barrier (`wmb()`): `dsb st`. @@ -149,23 +152,28 @@ pub(crate) struct Identity { pub(crate) core_masks: [u32; 2], } -/// Engine receipts: busy bit and the two fault banks. +/// Fault-bank selector values (`+0xd800`) that name a fault bank. +const FAULT_BANKS: u64 = 8; + +/// Engine receipts: busy bit and one fault bank. #[derive(Copy, Clone, Default)] pub(crate) struct EngineState { /// Bit 0 of `+0xc020 | +0xc120`. #[allow(dead_code)] pub(crate) busy: u64, - /// `+0xd8c0` under fault-bank selectors 0 and 1. - pub(crate) status: [u64; 2], - /// `+0xd8c8 << 6` under fault-bank selectors 0 and 1. - pub(crate) address: [u64; 2], + /// The fault-bank selector (`+0xd800`) the status and address were read under. + pub(crate) bank: u64, + /// `+0xd8c0`: bit 0 set when the bank holds a fault. + pub(crate) status: u64, + /// `+0xd8c8 << 6`. + pub(crate) address: u64, } impl EngineState { - /// Fault status of both banks, OR-ed together. + /// Fault status of the bank read. #[allow(dead_code)] pub(crate) fn fault(&self) -> u64 { - self.status[0] | self.status[1] + self.status } } @@ -179,6 +187,11 @@ pub(crate) struct Regs { status: Mapping, /// Host-owned generation register page (SGX +0xd60000). generation: Mapping, + /// GFXCAXI2AF registers (SGX +0x1000000), written only by the 27.2 start. + axi2af: Mapping, + /// Highest firmware performance state the board's table holds: S9 until the table is + /// known (the ten-row J713/J604 tables), S10 on the eleven-row J773g table. + top: AtomicU32, } impl Regs { @@ -198,11 +211,13 @@ impl Regs { asc: window(c_str!("asc"), 0)?, status: window(c_str!("sgx"), SGX_STATUS as u64)?, generation: window(c_str!("sgx"), 0xd60000)?, + axi2af: window(c_str!("sgx"), super::hw::start_27_2::AXI2AF as u64)?, + top: AtomicU32::new(9), res, }) } - /// Reads the identification words and the enabled-core mask (after the AGX vote). + /// Reads the identification words and the enabled-core mask (after the AGX vote on 25G83). pub(crate) fn identity(&self) -> Result { let version = self.res.sgx_read32_at(SGX_ID)?; let counts = self.res.sgx_read32_at(SGX_ID + 0x10)?; @@ -216,10 +231,22 @@ impl Regs { }) } - /// Actual cold or running firmware pstate (zero is valid while stopped). + /// Adopts the board's firmware performance table, `rows` rows including off. + pub(crate) fn set_table(&self, rows: u32) { + let top = rows.saturating_sub(1).clamp(1, super::fw::initdata::PERF_STATES as u32 - 1); + self.top.store(top, Ordering::Relaxed); + } + + /// Highest performance state the firmware may run in. + pub(crate) fn top(&self) -> u32 { + self.top.load(Ordering::Relaxed) + } + + /// Actual cold or running firmware pstate (zero is valid while stopped). A state above the + /// board table's top row is a protocol error. pub(crate) fn pstate(&self) -> Result { let state = self.res.sgx_read32_at(SGX_CORE + 0x1000)? & 0xf; - if state > 9 { + if state > self.top() { Err(super::boot::eproto()) } else { Ok(state) @@ -236,6 +263,32 @@ impl Regs { Ok(()) } + /// 26B123 before RUN: sets bit 0 of the two GFXCAXI2AF enables, each read first. + pub(crate) fn enable_axi2af(&self) -> Result { + let r = self.axi2af.io(); + for offset in super::hw::start_27_2::AXI2AF_ENABLES { + let value = r.try_read32(offset)?; + r.try_write32(value | 1, offset)?; + } + mb(); + Ok(()) + } + + /// 26B123 after AP power-on and before the GPU endpoints start: zeroes the host block, + /// reads the scratch word, then reads and raises the ready word. Returns the scratch word. + pub(crate) fn publish_host_block(&self) -> Result { + use super::hw::start_27_2 as s; + let g = self.generation.io(); + for offset in s::HOST_BLOCK_ZERO_ORDER { + g.try_write32(0, offset)?; + } + let probe = self.res.sgx_read32_at(s::SCRATCH_PROBE)?; + let _ = g.try_read32(s::HOST_READY)?; + g.try_write32(1, s::HOST_READY)?; + mb(); + Ok(probe) + } + /// ASC control word (`asc + 0x44`). pub(crate) fn asc_control(&self) -> Result { self.asc.io().try_read32(ASC_CONTROL) @@ -246,22 +299,42 @@ impl Regs { self.asc.io().try_write32(value, ASC_CONTROL) } - /// Engine receipts, under the device lock: busy is bit 0 of `C020 | C120`; the fault status - /// is `D8C0` under fault-bank selectors 0 and 1 (`D800`), with the saved selector restored. - /// 64-bit accesses. + /// Engine receipts for a running firmware, read only: busy is bit 0 of `C020 | C120`; the + /// fault status and address are `D8C0`/`D8C8` under the selector `D800` already holds. A + /// firmware that powers the GPU down while idle writes `D800` itself on the way down, so the + /// selector is not written here. 64-bit accesses. pub(crate) fn engine_state(&self) -> Result { let r = self.status.io(); + Ok(EngineState { + busy: (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1, + bank: r.try_read64(0x1800)?, + status: r.try_read64(0x18c0)?, + address: r.try_read64(0x18c8)? << 6, + }) + } + + /// Engine receipts for a firmware halted for recovery and waiting on the host: the first + /// fault bank, selectors 0 to 7 in order, whose status has bit 0 set, with the saved + /// selector restored. Without a fault, the status is zero and the bank the saved selector. + pub(crate) fn fault_scan(&self) -> Result { + let r = self.status.io(); + let saved = r.try_read64(0x1800)?; let mut state = EngineState { busy: (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1, + bank: saved, ..Default::default() }; - let sel = r.try_read64(0x1800)?; - for bank in 0..2 { - r.try_write64(bank as u64, 0x1800)?; - state.status[bank] = r.try_read64(0x18c0)?; - state.address[bank] = r.try_read64(0x18c8)? << 6; + for bank in 0..FAULT_BANKS { + r.try_write64(bank, 0x1800)?; + let status = r.try_read64(0x18c0)?; + if status & 1 != 0 { + state.bank = bank; + state.status = status; + state.address = r.try_read64(0x18c8)? << 6; + break; + } } - r.try_write64(sel, 0x1800)?; + r.try_write64(saved, 0x1800)?; Ok(state) } } diff --git a/drivers/gpu/drm/asahi/g16/uat.rs b/drivers/gpu/drm/asahi/g16/uat.rs index 72ca9cb94b846..b49944399e8a4 100644 --- a/drivers/gpu/drm/asahi/g16/uat.rs +++ b/drivers/gpu/drm/asahi/g16/uat.rs @@ -16,7 +16,13 @@ use core::ops::Range; use core::sync::atomic::Ordering; -use kernel::{device, io::Io, prelude::*, sync::Arc}; +use kernel::{ + device, + io::Io, + prelude::*, + sync::Arc, + time::{delay::fsleep, Delta, Instant, Monotonic}, +}; use super::hw; use super::regs::{mb, Mapping}; @@ -177,6 +183,11 @@ pub(crate) struct Window { firmware_root: [u64; 2], text_pa: u64, data_pa: u64, + /// The leaves the boot loader builds in this firmware's page tables (none for a firmware + /// that builds its own tree at start). + leaves: &'static [hw::Leaves], + /// The PPL handoff magic words of this firmware's layout. + ppl: hw::PplMagic, } impl Window { @@ -193,6 +204,9 @@ impl Window { firmware_root: [0; 2], text_pa: adt.text.start, data_pa: adt.data.start, + // Admission refuses a layout with either unknown; never guess them here. + leaves: adt.layout.leaves.ok_or(ENOTSUPP)?, + ppl: adt.layout.ppl_magic.ok_or(ENOTSUPP)?, }; window.admit_cold()?; Ok(window) @@ -220,9 +234,9 @@ impl Window { return Err(EBUSY); } let h = self.handoff.io(); - for offset in [0, 8] { + for (offset, expected) in [(0, self.ppl.ap), (8, self.ppl.firmware)] { let magic = h.try_read64(offset)?; - if magic != 0 && magic != hw::PPL_MAGIC { + if magic != 0 && magic != expected { return Err(EBUSY); } } @@ -293,24 +307,23 @@ impl Window { } else { let address = va | ((index as u64) << shift); let off = address.checked_sub(hw::UPPER).ok_or(EINVAL)?; - let expected = if off < 0x60000 { - (self.text_pa + off) - | if (0x50000..0x58000).contains(&off) { - 0x483 - } else { - 0x4c3 - } - } else if off < 0x19c000 { - let data_offset = off - 0x60000; - (self.data_pa + data_offset) - | if data_offset < 0xc000 { - 0x00200000000004c3 - } else { - 0x0460000000000443 - } - } else { - return Err(EINVAL); - }; + let leaf = self + .leaves + .iter() + .find(|leaf| leaf.range.contains(&off)) + .ok_or(EINVAL)?; + // TEXT starts at UPPER; every later segment is in DATA, contiguously. + let text_end = self + .leaves + .iter() + .filter(|l| l.segment == hw::Segment::Text) + .map(|l| l.range.end) + .max() + .ok_or(EINVAL)?; + let expected = match leaf.segment { + hw::Segment::Text => self.text_pa + off, + hw::Segment::Data => self.data_pa + (off - text_end), + } | leaf.attrs; if pte != expected { return Err(EINVAL); } @@ -327,6 +340,38 @@ impl Window { Ok(()) } + /// After RUN, waits up to 1 s for a firmware that answers at start ([`hw::PplMagic::answers`]) + /// to store its magic at +8, as GPU firmware 27.2 does on G14 (linux#2544). [`Self::bootstrap`] + /// clears +8 before RUN so a stale value can never satisfy the wait; a missing answer fails + /// with `ETIMEDOUT`. + pub(crate) fn await_firmware_magic(&self, dev: &device::Device) -> Result { + if !self.ppl.answers { + return Ok(()); + } + let start = Instant::::now(); + loop { + let magic = self.handoff.io().try_read64(8)?; + if magic == self.ppl.firmware { + dev_info!( + dev, + "G16: firmware PPL magic {:#x} after {} us\n", + magic, + start.elapsed().as_micros_ceil() + ); + return Ok(()); + } + if start.elapsed() >= Delta::from_millis(1000) { + dev_err!( + dev, + "G16: no firmware PPL magic within 1 s (+8 = {:#x})\n", + magic + ); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + } + /// Cold-start check: all 128 TTBAT words are zero. pub(crate) fn ttbat_is_clear(&self) -> Result { let t = self.ttbs.io(); @@ -353,12 +398,19 @@ impl Window { let lower = uat.kernel_lower_root(); let shadow_l2 = Self::shadow_l2(uat)?; let handoff = uat.lock_m4_handoff()?; - let fw_magic = self.handoff.io().try_read64(8)?; - self.handoff.io().try_write64(hw::PPL_MAGIC, 0)?; + let fw_magic = if self.ppl.answers { + // Clear any leftover firmware magic before RUN so await_firmware_magic() only + // accepts a fresh answer written by this boot's firmware. + self.handoff.io().try_write64(0, 8)?; + 0 + } else { + self.handoff.io().try_read64(8)? + }; + self.handoff.io().try_write64(self.ppl.ap, 0)?; // Cold admission proved both interests clear. The common guard now owns AP // interest; never reset either participant's lock words behind that guard. self.handoff.io().try_write32(0xffff, 0x18)?; - if fw_magic != hw::PPL_MAGIC { + if fw_magic != self.ppl.firmware { self.handoff.io().try_write8(1, 0x638)?; } for index in 0..65 * 3 { diff --git a/drivers/gpu/drm/asahi/timestamp.rs b/drivers/gpu/drm/asahi/timestamp.rs index 2a18ebbeb5d9c..7118cffde3301 100644 --- a/drivers/gpu/drm/asahi/timestamp.rs +++ b/drivers/gpu/drm/asahi/timestamp.rs @@ -203,6 +203,14 @@ pub(crate) struct Destinations(Option bool { + self.0 + .as_deref() + .is_none_or(|destinations| destinations.iter().all(Option::is_none)) + } + /// G16 retains its eight-byte destination alignment and EINVAL contract. #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) fn resolve_aligned( From ed41e08f7a02090730538b72ba1f02b3624dda6c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 13:01:09 -0500 Subject: [PATCH 05/19] selftests: drm/asahi-m4: add 26B123 ABI offset-oracle and update host tests Add check-abi-26b123.rs and test-abi-26b123.py to verify 26B123 layout selection, compile-time policy collision guards, and exact byte-for-byte InitData/work/queue encoding parity against independent per-field offset tables. Extend test-perf.py for ADT power-sampling, low-peak limiter, and coredump-copy-buffer parsing; extend test-vm.py for 26B123 firmware page tables, +8 clear before RUN, and ETIMEDOUT on missing magic answer; and update the remaining host suites for the 26B123 ABI and compute work tick layout. Signed-off-by: Diljit Singh --- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 364 ++++++++++++++++++ .../gpu/asahi-m4/check-initdata-bounds.rs | 14 +- .../drivers/gpu/asahi-m4/check-initdata.rs | 35 +- .../drivers/gpu/asahi-m4/test-abi-26b123.py | 239 ++++++++++++ .../gpu/asahi-m4/test-command-stream.py | 12 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 10 +- .../drivers/gpu/asahi-m4/test-perf.py | 90 +++-- .../drivers/gpu/asahi-m4/test-publication.py | 11 +- .../drivers/gpu/asahi-m4/test-recovery.py | 14 +- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 29 +- .../drivers/gpu/asahi-m4/test-timestamps.py | 2 +- .../selftests/drivers/gpu/asahi-m4/test-vm.py | 53 ++- 12 files changed, 807 insertions(+), 66 deletions(-) create mode 100644 tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs create mode 100755 tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs new file mode 100644 index 0000000000000..2ef40886e69c5 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs @@ -0,0 +1,364 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#![allow(dead_code,non_camel_case_types,non_snake_case,non_upper_case_globals,unused_imports)] +// Encodes the same InitData, work items and queue info for the 25G83 and 26B123 firmware +// ABIs with the production encoders, checks the layout catalog, and writes both encodings +// for test-abi-26b123.py's independent offset oracle. +extern crate self as kernel; +pub mod prelude { pub type Result = core::result::Result; pub const E2BIG:i32=7; } +mod uapi {include!("public-uapi.rs");} +mod hw { + pub enum GpuVariant {G} + pub mod engine {pub const COMPUTE_SEED:u32=0x100;} + pub mod client {pub const PB_HEAP_SIZE:u64=0x10000000;} + pub(crate) use super::backend_hw::FwAbi; +} +mod fwid { +@FWID_BUILD@ +} +struct Config { + chip_id:u32,gpu_variant:hw::GpuVariant,gpu_revision:u32,uat_ias:u32,uat_oas:u32, + num_clusters:u32,num_cores_per_cluster:u32, + hw_ids:&'static[backend_hw::HwId],firmware:&'static[backend_hw::FirmwareBuild], +} +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/hw.rs"] +mod backend_hw; +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/mod.rs"] +mod fw; +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/encode.rs"] +mod encode; + +use backend_hw::{FwAbi, LoaderTable, PplMagic, FW_25G83, FW_26B123, PPL_MAGIC, UPPER}; +use fw::initdata::{self as wire, id}; +use fw::work::{compute, fs, ta}; + +const HOST: u64 = wire::HOST_START; + +/// An eleven-row (J773g-sized) table so the encoder fills every performance row. +fn input() -> wire::Input { + let mut p = wire::Performance { + count: 11, + frequency: [0; 11], + auxiliary: [0; 11], + voltage: [0; 11], + sram: [0; 11], + }; + for i in 0..11 { + p.frequency[i] = if i == 0 { 0 } else { 200 + 100 * i as u32 }; + p.auxiliary[i] = if i == 0 { 0 } else { 190 + 100 * i as u32 }; + p.voltage[i] = if i == 0 { 100 } else { 600 + 40 * i as u32 }; + p.sram[i] = 800 + 30 * i as u32; + } + wire::Input { + performance: p, + va: core::array::from_fn(|i| HOST + 0x100000 + i as u64 * 0x100000), + channel_state: core::array::from_fn(|i| HOST + 0x4000000 + i as u64 * 0x10000), + channel_ring: core::array::from_fn(|i| HOST + 0x4004000 + i as u64 * 0x10000), + loader_va: core::array::from_fn(|i| { + if wire::LOADERS[i].length != 0 { + HOST + 0x5000000 + i as u64 * 0x100000 + (wire::LOADERS[i].pa & 0x3fff) + } else { + 0 + } + }), + scratch: HOST + 0xa000000, + lower_uma: wire::BOOTSTRAP_START + 0x200000, + lower_parameter: wire::BOOTSTRAP_START + 0x240000, + ktrace_mask: 0x12345678, + progress_recovery: 1, + // T8132 ADT sgx and pmgr/clpc power-sampling and low-peak limiter parameters (24 MHz). + power_sample_clks: 200_000, + power_sample_us: 8333, + power_sample_period_ms: 8, + timebase_khz: 24_000, + avg_power_filter_tc_ms: 248, + lowpeak_limiter_tc_ms: 16, + lowpeak_limiter_ki_q16: 134_217, + lowpeak_limiter_kp_q16: 33_554, + coredump_copy_size: 0x8000, + } +} + +fn initdata(layout: &wire::Layout, ceiling: u32) -> Result, ()> { + let mut buffers: [Vec; wire::OBJECT_COUNT] = + core::array::from_fn(|i| vec![0xa5u8; layout.object_size[i]]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + // As `build`: a record the ABI has no slot for is not mapped. + let mut input = input(); + for slot in 0..wire::LOADER_COUNT { + if layout.slot(slot).is_none() { + input.loader_va[slot] = 0; + } + } + wire::encode_for(layout, &mut slices, &input, ceiling)?; + Ok(buffers.into_iter().flatten().collect()) +} + +fn object<'a>(image: &'a [u8], layout: &wire::Layout, object: usize) -> &'a [u8] { + let start: usize = layout.object_size[..object].iter().sum(); + &image[start..start + layout.object_size[object]] +} + +fn r32(b: &[u8], at: usize) -> u32 { u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) } +fn r64(b: &[u8], at: usize) -> u64 { u64::from_le_bytes(b[at..at + 8].try_into().unwrap()) } + +fn render(out: &std::path::Path) { + let f = 0xfffffc2000000000u64; + let g = 0x1000000000u64; + let mut u = uapi::drm_asahi_cmd_render::default(); + u.width_px = 1919; u.height_px = 1079; u.layers = 3; u.samples = 2; + u.utile_width_px = 16; u.utile_height_px = 32; u.sample_size_B = 4; + u.flags = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_RSRC_SPEC_HI; + u.vdm_ctrl_stream_base = g + 0xa00000; + u.depth.base = g + 0xe00000; u.stencil.base = g + 0xf00000; + u.bg.usc = 0x10000; u.eot.usc = 0x20000; + let r = encode::RenderRefs { + notifier: f + 0x800000, qinfo: [f + 0xf00000, f + 0x1000000], + user_stamp: [f + 0x800620, f + 0x800630], fw_stamp: [f + 0x4000000, f + 0x4004000], + uma_mgr: [f + 0x300000, f + 0x300000], uma_aux: [f + 0x300100, f + 0x300200], + uma_gpu: g + 0x6000000, pb_mgr: f + 0x3000000, scene_list: g + 0x500000, + parameter_id: 3, generation: 254, activity: [f + 0x900004, f + 0xa00008], + counter: [4, 3], uma_submitted: 4, uuid: 0x123401, usc_base: 1 << 40, + ..Default::default() + }; + let p = encode::PassRefs { + ta_work: f + 0xb00000, ta_work_gva: g + 0x7000000, fs_work: f + 0xc00000, + fs_work_gva: g + 0x8000000, ta_seq: f + 0xd00000, fs_seq: f + 0xe00000, + scene: f + 0x100000, tpc_gva: g + 0x200000, tpc_fw: f + 0x3200000, + tilemap_gva: g + 0x100000, heap_gva: g + 0x300000, scene_user_gva: g + 0x900000, + scratch_fw: f + 0x200000, pre_gva: [g + 0x600000, g + 0x700000, g + 0x800000], + aux_gva: g + 0xb00000, ..Default::default() + }; + let geo = encode::Geometry::new(&u, p.heap_gva); + let ts = [f + 0xffc000100, 0, 0, f + 0xffc000118]; + let mut images = Vec::new(); + for (ta_layout, fs_layout) in [(&ta::V25G83, &fs::V25G83), (&ta::V26B123, &fs::V26B123)] { + let mut tw = [0xa5; ta::WORK_SIZE]; let mut tq = [0xa5; ta::SEQ_SIZE]; + let mut fw_ = [0xa5; fs::WORK_SIZE]; let mut fq = [0xa5; fs::SEQ_SIZE]; + encode::encode_ta_for(ta_layout, &r, &p, &u, &ts, 7, 0x300, &geo, None, &mut tw, &mut tq); + encode::encode_fs_for(fs_layout, &r, &p, &u, &ts, 7, 1 << 40, 1, 0x300, &geo, &mut fw_, &mut fq); + images.push((tw, tq, fw_, fq)); + } + // The 25G83 entry points are the 25G83 layouts. + let (mut tw, mut tq) = ([0; ta::WORK_SIZE], [0; ta::SEQ_SIZE]); + let (mut fw_, mut fq) = ([0; fs::WORK_SIZE], [0; fs::SEQ_SIZE]); + encode::encode_ta(&r, &p, &u, &ts, 7, 0x300, &geo, None, &mut tw, &mut tq); + encode::encode_fs(&r, &p, &u, &ts, 7, 1 << 40, 1, 0x300, &geo, &mut fw_, &mut fq); + assert!(tw == images[0].0 && tq == images[0].1 && fw_ == images[0].2 && fq == images[0].3); + let (ref tw, ref tq, ref fw_, ref fq) = images[1]; + assert_eq!(r64(tw, 0x917), 254, "TA generation is a u64 at 0x917"); + assert_eq!(r64(tq, ta::FINALIZE + 0x85), p.ta_work + 0x91f); + for record in [ta::TS_START, ta::TS_END] { + assert_eq!(r64(tq, record + 0x2c), p.ta_work + 0x92f); + } + assert_eq!(r64(fw_, 0xc5f), 254, "FS generation is a u64 at 0xc5f"); + assert_eq!((fw_[0xc84], fw_[0xc8b]), (0, 1), "FS flag moved to 0xc8b"); + assert_eq!(r64(fq, fs::FINALIZE + 0xa5), p.fs_work + 0xc67); + for record in [fs::TS_START, fs::TS_END] { + assert_eq!(r64(fq, record + 0x2c), p.fs_work + 0xc77); + } + // The 26B123 timestamp op stores two u64s after the completion target: host-free. + assert!(tw[0x927..0x937].iter().all(|&b| b == 0)); + assert!(fw_[0xc6f..0xc7f].iter().all(|&b| b == 0)); + for (name, (tw, tq, fw_, fq)) in ["25g83", "26b123"].iter().zip(&images) { + let mut all = tw.to_vec(); all.extend(tq); all.extend(fw_); all.extend(fq); + std::fs::write(out.join(format!("render-{name}.bin")), all).unwrap(); + } +} + +fn compute_work(out: &std::path::Path) { + let f = 0xfffffc2000000000u64; + let g = 0x1000000000u64; + let r = encode::ComputeRefs { + notifier: f + 0x600400, qinfo: f + 0x200000, user_stamp: f + 0x600648, + fw_stamp: f + 0x600640, work: f + 0x100000, work_gva: g + 0x100000, seq: f + 0x100900, + preempt_gva: g + 0x200000, its: f + 0x500040, stats_fw: f + 0x300000, + auxiliary_fw: f + 0x400000, auxiliary_gva: g + 0x400000, + context_store_gva: g + 0x500000, counter_fw: f + 0x500000, + pool_state_gva: g + 0x600000, page_list_gva: g + 0x700000, usc_base: 1 << 40, + record_fw: f + 0x700000, binding_generation: 200, uma_slot: 3, command_id: 9, + compute_index: 8, work_818: 0, target_stamp: 0x900, submitted: 5, + }; + let c = uapi::drm_asahi_cmd_compute { + cdm_ctrl_stream_base: g + 0x300000, cdm_ctrl_stream_end: g + 0x300200, + ..Default::default() + }; + let att = [uapi::drm_asahi_attachment { pointer: g + 0x50000000, size: 137, ..Default::default() }]; + let ts = [0xfffffc2ffc000100, 0]; + let mut images = Vec::new(); + for layout in [&compute::V25G83, &compute::V26B123] { + let mut w = [0xa5; compute::WORK_SIZE]; let mut q = [0xa5; compute::SEQ_SIZE]; + encode::encode_compute_for(layout, &r, &c, &att, &ts, 1, 1, 1, &mut w, &mut q).unwrap(); + images.push((w, q)); + } + let (mut w, mut q) = ([0; compute::WORK_SIZE], [0; compute::SEQ_SIZE]); + encode::encode_compute(&r, &c, &att, &ts, 1, 1, 1, &mut w, &mut q).unwrap(); + assert!(w == images[0].0 && q == images[0].1); + let (ref w, ref q) = images[1]; + assert_eq!(r64(w, 0x88b), 200, "compute generation is a u64 at 0x88b"); + assert_eq!(r64(q, 0x1a8), r.work + 0x8b3); + assert_eq!(r64(q, compute::FINALIZE + 0x69), r.work + 0x8b3); + assert_eq!(r64(q, compute::FINALIZE + 0x71), r.work + 0x893); + for record in [compute::TS_START, compute::TS_END] { + assert_eq!(r64(q, record + 0x2c), r.work + 0x8a3); + } + assert!(w[0x89b..0x8ab].iter().all(|&b| b == 0)); + assert!(w[0x8e0..compute::SEQ_EMBEDDED].iter().all(|&b| b == 0), "beyond the cached prefix"); + assert_eq!(&w[compute::SEQ_EMBEDDED..compute::SEQ_EMBEDDED + compute::SEQ_SIZE], &q[..]); + for (name, (w, q)) in ["25g83", "26b123"].iter().zip(&images) { + let mut all = w.to_vec(); all.extend(q); + std::fs::write(out.join(format!("compute-{name}.bin")), all).unwrap(); + } +} + +fn queues(out: &std::path::Path) { + let f = 0xfffffc2000000000u64; + let args = (f + 0x100000, f + 0x200000, f + 0x400000, f + 0x300000, f + 0x500000); + let v25 = fw::graph::queue_image_for(FwAbi::V25G83.qinfo(), args.0, args.1, args.2, args.3, args.4); + assert_eq!(v25, fw::graph::queue_image(args.0, args.1, args.2, args.3, args.4)); + let v26 = fw::graph::queue_image_for(FwAbi::V26B123.qinfo(), args.0, args.1, args.2, args.3, args.4); + assert_eq!(r64(&v26, 0x18), args.3 + 0x80, "scratch after the 0x80 header"); + assert_eq!((r32(&v26, 0x44), r32(&v26, 0x48)), (2, u32::MAX)); + assert_eq!(r64(&v26, 0x78), args.4, "aligned scheduling context"); + assert!(v26[0x80..].iter().all(|&b| b == 0)); + let mut all = v25.to_vec(); all.extend(v26); + std::fs::write(out.join("queue.bin"), all).unwrap(); +} + +fn catalog() { + // Handoff selection and what a 26B123 start still needs. + assert!(FW_25G83.matches(1, &[UPPER, UPPER + 0x60000], &[1, 0])); + assert!(FW_26B123.matches(2, &[UPPER, UPPER + 0x64000, UPPER + 0x134000], &[1, 0x10, 0])); + assert!(!FW_25G83.matches(2, &[UPPER, UPPER + 0x64000, UPPER + 0x134000], &[1, 0x10, 0])); + assert!(!FW_26B123.matches(2, &[UPPER, UPPER + 0x64000], &[1, 0x10])); + assert_eq!((FW_25G83.abi, FW_26B123.abi), (FwAbi::V25G83, FwAbi::V26B123)); + assert_eq!(FW_25G83.unknown().count(), 0); + // Nothing known to be missing refuses a 26B123 start any more. + let unknown: Vec<_> = FW_26B123.unknown().collect(); + assert!(unknown.is_empty(), "{unknown:?}"); + assert_eq!(FW_25G83.loader_table, Some(LoaderTable::Host(0x1332f0))); + assert_eq!(FW_26B123.loader_table, Some(LoaderTable::Firmware)); + assert_eq!(PPL_MAGIC, 0x4b1d000000000002); + assert_eq!(FW_25G83.ppl_magic, Some(PplMagic { ap: PPL_MAGIC, firmware: PPL_MAGIC, answers: false })); + assert_eq!(FW_26B123.ppl_magic, Some(PplMagic { ap: 0x4b1d000000000003, firmware: 0x4b1d000000000003, answers: true })); + // The 26B123 firmware builds its own page-table tree: the boot loader builds no leaf. + assert_eq!(FW_25G83.leaves.map(|l| l.len()), Some(5)); + assert_eq!(FW_26B123.leaves.map(|l| l.len()), Some(0)); + // Device control. + let (a, b) = (FwAbi::V25G83.devctl(), FwAbi::V26B123.devctl()); + assert_eq!((a.import_globals, a.start, a.nop, a.grow_reply), (0x34, 0x0a, 0x1a, 7)); + assert_eq!((b.import_globals, b.start, b.nop, b.grow_reply), (0x35, 0x0a, 0x19, 7)); + // FirmwareData, selectors, register map. + let (v25, v26) = (FwAbi::V25G83.initdata(), FwAbi::V26B123.initdata()); + let (d25, d26) = (&v25.firmware_data, &v26.firmware_data); + assert_eq!((d25.fwctl, d25.generation, d25.phase, d25.scheduler, d25.snapshot), (0x4f88, 0x4fa0, 0x4fb0, 0x4fd4, 0x40b8)); + assert_eq!((d26.fwctl, d26.generation, d26.phase, d26.scheduler, d26.snapshot), (0x5168, 0x5180, 0x5190, 0x51b4, 0x4298)); + assert_eq!(d25.snapshot + d25.snapshot_entries * 8, 0x4eb8); + assert_eq!(v25.pstate_selectors, [0x88, 0x8c, 0x98]); + assert_eq!(v26.pstate_selectors, [0x8c, 0x90, 0x9c]); + for (i, &at) in v25.pstate_selectors.iter().enumerate() { + assert_eq!(wire::remap(v26.globals, at, 4), Ok(v26.pstate_selectors[i])); + } + assert_eq!((v25.loader_records(), v26.loader_records()), (42, 47)); + assert_eq!((v25.register_slots, v26.register_slots), (53, 60)); + assert_eq!((v25.power_config, v26.power_config), (0x469, 0x479)); + assert_eq!(v25.object_size, wire::OBJECT_SIZE); + // Words whose 26B123 position is not known are refused rather than guessed. + assert_eq!(wire::remap(v26.main, 0x25b8, 4), Err(())); + assert_eq!(wire::remap(v26.main, 0xebc, 4), Err(())); + assert_eq!(wire::remap(v26.main, 0x700, 4), Err(()), "the register map is slot-mapped"); + assert_eq!(wire::remap(v26.power_performance, 0x2e00, 4), Err(())); + assert_eq!(wire::remap(v26.power_performance, 0x62c8, 4), Err(())); + assert_eq!(wire::remap(v26.globals, 0x36, 4), Err(()), "a field may not straddle an insert"); + // A mapped record this ABI has no slot for refuses the encoding. + let mut no_slot = wire::Layout { name: "test", ..wire::V26B123 }; + no_slot.loader_slot[3] = None; + let mut buffers: [Vec; wire::OBJECT_COUNT] = + core::array::from_fn(|i| vec![0xa5u8; no_slot.object_size[i]]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + assert!(wire::encode_for(&no_slot, &mut slices, &input(), 10).is_err()); + // The protected power-transition block (logical 36) has no 26B123 slot: slot 41 stays empty. + let v26 = initdata(&wire::V26B123, 10).unwrap(); + let main = object(&v26, &wire::V26B123, id::MAIN); + assert!(main[0x640 + 41 * 0x28..0x640 + 42 * 0x28].iter().all(|&b| b == 0)); + let mut past_map = wire::Layout { name: "test", ..wire::V26B123 }; + past_map.loader_slot[41] = Some(60); + assert!(initdata(&past_map, 10).is_err()); + // Missing or zero ADT power-sampling / limiter / coredump inputs must fail closed without writing. + for bad_case in 0..10 { + let mut inp = input(); + for slot in 0..wire::LOADER_COUNT { + if wire::V26B123.slot(slot).is_none() { + inp.loader_va[slot] = 0; + } + } + match bad_case { + 0 => inp.power_sample_clks = 0, + 1 => inp.power_sample_us = 0, + 2 => inp.avg_power_filter_tc_ms = 0, + 3 => inp.power_sample_period_ms = 0, + 4 => inp.timebase_khz = 0, + 5 => inp.lowpeak_limiter_tc_ms = 0, + 6 => inp.lowpeak_limiter_ki_q16 = 0, + 7 => inp.lowpeak_limiter_kp_q16 = 0, + 8 => inp.coredump_copy_size = 0, + _ => inp.coredump_copy_size = 0x8001, + } + let mut buffers: [Vec; wire::OBJECT_COUNT] = + core::array::from_fn(|i| vec![0xa5u8; wire::V26B123.object_size[i]]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + assert!(wire::encode_for(&wire::V26B123, &mut slices, &inp, 10).is_err()); + assert!(buffers.iter().all(|b| b.iter().all(|&x| x == 0xa5))); + } + // Compile-time layout checker must reject policy words colliding with remapped 25G83 words, + // pstate selectors, or ADT-derived sampling/limiter slots. + assert!(wire::layout_fits(&wire::V25G83) && wire::layout_fits(&wire::V26B123)); + let mut bad_power = wire::Layout { name: "test", ..wire::V26B123 }; + bad_power.power_policy = &[(0x2a64, 1)]; // collides with remapped 25G83 0x2a3c ceiling word + assert!(!wire::layout_fits(&bad_power)); + bad_power.power_policy = &[(0x29e4, 1)]; // collides with power_sampling.filter[0] + assert!(!wire::layout_fits(&bad_power)); + bad_power.power_policy = &[(0xa80, 1)]; // collides with power_limiter.filter_periods_x4 + assert!(!wire::layout_fits(&bad_power)); + let mut bad_globals = wire::Layout { name: "test", ..wire::V26B123 }; + bad_globals.globals_policy = &[(0x8c, 1)]; // collides with pstate_selectors[0] + assert!(!wire::layout_fits(&bad_globals)); + bad_globals.globals_policy = &[(0x7c, 1)]; // collides with remapped 25G83 0x78 + assert!(!wire::layout_fits(&bad_globals)); +} + +fn main() { + let out = std::path::PathBuf::from(std::env::args().nth(1).unwrap()); + catalog(); + let v25 = initdata(&wire::V25G83, 10).unwrap(); + // The 25G83 entry point is the 25G83 layout. + let mut buffers = wire::OBJECT_SIZE.map(|size| vec![0xa5u8; size]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + wire::encode(&mut slices, &input(), 10).unwrap(); + assert_eq!(buffers.concat(), v25); + let v26 = initdata(&wire::V26B123, 10).unwrap(); + let l = &wire::V26B123; + assert_eq!(r64(object(&v26, l, id::ROOT), 0), 0x0c8a836f039204b8); + let runtime = object(&v26, l, id::RUNTIME); + assert_eq!(r64(runtime, 0x479), input().va[id::POWER_PERFORMANCE]); + assert!(runtime[0x469..0x479].iter().all(|&b| b == 0)); + let data = object(&v26, l, id::FIRMWARE_DATA); + assert_eq!((r64(data, 0x5168), r64(data, 0x5170), r32(data, 0x51b4)), + (input().va[id::FWCTL], input().va[id::FWCTL] + 0x40, 1)); + let main = object(&v26, l, id::MAIN); + // 26B123: no retention pointer in MAIN, the crash copy buffer size at 0xfa8, and the + // RETENTION object at RUNTIME +0x2c8. + assert_eq!(r64(main, 0xfa0), 0); + assert_eq!(r64(main, 0xfa8), input().coredump_copy_size); + assert_eq!(r64(object(&v26, l, id::RUNTIME), 0x2c8), input().va[id::RETENTION]); + // CRE (25G83 slot 28) is register-map slot 33 in 26B123. + assert_eq!(r64(main, 0x640 + 33 * 0x28), 0x300d58000); + assert!(main[0x640 + 28 * 0x28..0x640 + 29 * 0x28].iter().all(|&b| b == 0)); + let power = object(&v26, l, id::POWER_PERFORMANCE); + assert_eq!(r64(power, 0x3b98), input().va[id::TEMPERATURE]); + std::fs::write(out.join("initdata-25g83.bin"), &v25).unwrap(); + std::fs::write(out.join("initdata-26b123.bin"), &v26).unwrap(); + render(&out); + compute_work(&out); + queues(&out); + println!("26B123 layout catalog, InitData ({} / {} bytes), TA/FS/compute work and queue info encode; 25G83 entry points equal the 25G83 layouts", v25.len(), v26.len()); +} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs index 29b51ee5cefaf..52787524d33f4 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs @@ -6,12 +6,13 @@ const HOST: u64 = wire::HOST_START; fn emit(out:&mut Vec, value:Result)->Option { out.push(u8::from(value.is_err()));value.ok() } fn input()->wire::Input { wire::Input { - // Independently pinned qualified C/J713 bin for this immutable byte fixture. + // J713 frequencies with synthetic voltage bins. performance: wire::Performance { - frequency: [0,338,618,796,928,1056,1170,1278,1338,1470], - auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326], - voltage: [125,610,645,680,725,780,825,865,895,970], - sram: [780,780,780,780,780,780,825,865,895,970], + count: 10, + frequency: [0,338,618,796,928,1056,1170,1278,1338,1470,0], + auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326,0], + voltage: [100,600,650,700,750,800,850,900,950,1000,0], + sram: [800,800,800,800,800,800,850,900,950,1000,0], }, va: core::array::from_fn(|i|HOST+0x100000+i as u64*0x100000), channel_state:core::array::from_fn(|i|HOST+0x4000000+i as u64*0x10000), @@ -19,6 +20,9 @@ fn input()->wire::Input { loader_va:core::array::from_fn(|i|if wire::LOADERS[i].length!=0 {HOST+0x5000000+i as u64*0x100000+(wire::LOADERS[i].pa&0x3fff)}else{0}), scratch:HOST+0xa000000,lower_uma:wire::BOOTSTRAP_START+0x200000, lower_parameter:wire::BOOTSTRAP_START+0x240000,ktrace_mask:0,progress_recovery:1, + power_sample_clks:200_000,power_sample_us:8333,power_sample_period_ms:8, + timebase_khz:24_000,avg_power_filter_tc_ms:248,lowpeak_limiter_tc_ms:16, + lowpeak_limiter_ki_q16:134_217,lowpeak_limiter_kp_q16:33_554,coredump_copy_size:0x8000, } } fn init_result(buffers:&mut[Vec;wire::OBJECT_COUNT], input:&wire::Input, ceiling:u32)->Result<(),()> { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs index 97d526fbf504f..03ab056cc5e46 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs @@ -7,12 +7,13 @@ fn input(variant: u64) -> initdata::Input { let start = 0xfffffc2000000000u64; let shift = variant * 0x100000000; let mut input = initdata::Input { - // Independently pinned qualified C/J713 bin for this immutable byte fixture. + // J713 frequencies with synthetic voltage bins. performance: initdata::Performance { - frequency: [0,338,618,796,928,1056,1170,1278,1338,1470], - auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326], - voltage: [125,610,645,680,725,780,825,865,895,970], - sram: [780,780,780,780,780,780,825,865,895,970], + count: 10, + frequency: [0,338,618,796,928,1056,1170,1278,1338,1470,0], + auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326,0], + voltage: [100,600,650,700,750,800,850,900,950,1000,0], + sram: [800,800,800,800,800,800,850,900,950,1000,0], }, va: core::array::from_fn(|i| start + shift + 0x100000 + i as u64 * 0x100000), channel_state: core::array::from_fn(|i| start + shift + 0x4000000 + i as u64 * 0x10000), @@ -23,6 +24,16 @@ fn input(variant: u64) -> initdata::Input { lower_parameter: 0x7000240000, ktrace_mask: [0, 0x12345678, 0xfedcba98][variant as usize], progress_recovery: u32::from(variant != 1), + // T8132 ADT power-sampling ticks; 25G83 writes power_sample_clks to +4/+8. + power_sample_clks: 200_000, + power_sample_us: 8333, + power_sample_period_ms: 8, + timebase_khz: 24_000, + avg_power_filter_tc_ms: 248, + lowpeak_limiter_tc_ms: 16, + lowpeak_limiter_ki_q16: 134_217, + lowpeak_limiter_kp_q16: 33_554, + coredump_copy_size: 0x8000, }; for (i, loader) in initdata::LOADERS.iter().enumerate() { if loader.length != 0 { @@ -41,12 +52,22 @@ fn main() { let mut slices: [&mut [u8]; initdata::OBJECT_COUNT] = buffers.each_mut().map(|buffer| buffer.as_mut_slice()); initdata::encode(&mut slices, &input(variant as u64), ceiling).expect("valid C fixture rejected"); let got: Vec<_> = buffers.into_iter().flatten().collect(); - let expected = std::fs::read(directory.join(format!("initdata-{variant}.bin"))).unwrap(); + let mut expected = + std::fs::read(directory.join(format!("initdata-{variant}.bin"))).unwrap(); + // Substitute synthetic voltages in the immutable C golden before comparison. + let main: usize = initdata::OBJECT_SIZE[..initdata::id::MAIN].iter().sum(); + let perf = input(variant as u64).performance; + for i in 0..=ceiling as usize { for lane in 0..16 { + for (offset, value) in [(0x1008, perf.voltage[i]), (0x1408, perf.sram[i])] { + let at = main + offset + (i * 16 + lane) * 4; + expected[at..at+4].copy_from_slice(&value.to_le_bytes()); + } + }} if let Some(offset) = got.iter().zip(&expected).position(|(a, b)| a != b) { panic!("initdata variant {variant} differs at {offset:#x}: C={:#x}, Rust={:#x}", expected[offset], got[offset]); } assert_eq!(got.len(), expected.len()); bytes_checked += got.len(); } - println!("3 initdata fixtures / {bytes_checked} output bytes match qualified C exactly"); + println!("3 initdata fixtures / {bytes_checked} bytes match C with synthetic voltages"); } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py new file mode 100755 index 0000000000000..fa6239d6f8a7a --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""The 26B123 firmware ABI: production encoders against an independent offset oracle. + +check-abi-26b123.rs encodes the same InitData graph, TA/FS/compute work and queue info with +the production 25G83 and 26B123 layouts. This script rebuilds the expected 26B123 bytes from +the 25G83 bytes with explicit per-field tables (old offset -> new offset, written out +independently of the production offset runs) and requires an exact match, and that every +non-zero 25G83 byte is accounted for. CPU-only. +""" +import json +from pathlib import Path +import struct +import subprocess +import time +from common import HERE, frozen_bindings, kernel_root, output_dir, rustc, sha + +OBJECTS_25G83 = [ + 0xc8, 0x4000, 0x4b8, 0xe48, 0x20, 0xeaf0, 0x670, 0x4000, 0x2658, 0x6578, 0x88, 0xc18, 0x1248, + 0xe10, 0x60, 0x1b0, 0x28800, 0x79800, 0x4000, 0x30, 0x4000, 0x30, 0x9000, 0x30, 0x4800, 0x4, + 0x30, 0x4800, 0x4000, 0x4000, 0x4000] +# 26B123 grows GLOBALS (+4), FIRMWARE_DATA (+0x2e0), POWER, MAIN and POWER_PERFORMANCE. +OBJECTS_26B123 = list(OBJECTS_25G83) +OBJECTS_26B123[3] = 0xe4c +OBJECTS_26B123[5] = 0xedd0 +OBJECTS_26B123[6] = 0x698 +OBJECTS_26B123[8] = 0x2788 +OBJECTS_26B123[9] = 0x6c48 +ROOT, RUNTIME, GLOBALS, FIRMWARE_DATA, MAIN, POWER_PERFORMANCE = 0, 2, 3, 5, 8, 9 + + +def fields(pairs, width=4): + return [(old, new, width) for old, new in pairs] + + +# GLOBALS: one u32 inserted at 0x38; the words the host writes. +GLOBALS_MAP = fields([(0x24, 0x24), (0x78, 0x7c), (0x88, 0x8c), (0x8c, 0x90), (0x98, 0x9c), + (0x998, 0x99c), (0x99c, 0x9a0), (0x9a0, 0x9a4), (0x9b8, 0x9bc), + (0x9bc, 0x9c0), (0x9c0, 0x9c4), (0x9c8, 0x9cc), (0x9cc, 0x9d0), + (0xe28, 0xe2c)]) +# FirmwareData: FWCTL state/ring pointers and the scheduler word. +FIRMWARE_DATA_MAP = [(0x4f88, 0x5168, 8), (0x4f90, 0x5170, 8), (0x4fd4, 0x51b4, 4)] +# HW data: the G16-written words, then the register map slot renumbering. +MAIN_MAP = [(0x28, 0x28, 8), (0xf24, 0x1040, 8)] + fields([ + (0xea0, 0xfc0), (0xea4, 0xfc4), (0xeb8, 0xfd8), (0xed0, 0xfec), (0xed4, 0xff0), + (0xed8, 0xff4), (0xee0, 0xffc), (0xfc0, 0x10dc), (0xfc4, 0x10e0), (0x2544, 0x2660), + (0x2548, 0x2664), (0x254c, 0x2668), (0x2550, 0x266c), (0x2554, 0x2670), (0x2568, 0x2684), + (0x2570, 0x268c), (0x259c, 0x26b8)]) +MAIN_MAP += fields([(0xfc8 + 4 * i, 0x10e4 + 4 * i) for i in range(16)]) +MAIN_MAP += fields([(0x1808 + 4 * i, 0x1924 + 4 * i) for i in range(16)]) +MAIN_MAP += fields([(0x1008 + 4 * k, 0x1124 + 4 * k) for k in range(256)]) +MAIN_MAP += fields([(0x1408 + 4 * k, 0x1524 + 4 * k) for k in range(256)]) +SLOTS = {0: 0, 3: 3, 9: 9, 10: 10, 12: 12, 14: 14, 15: 15, 17: 17, 22: 22, 26: 31, 27: 32, + 28: 33, 29: 34, 31: 36, 32: 37, 39: 44, 40: 45, 41: 46} +MAIN_MAP += [(0x640 + old * 0x28, 0x640 + new * 0x28, 0x28) for old, new in SLOTS.items()] +# Logical 36 (the protected power-transition block, slot 41) stays empty on 26B123: its 25G83 +# bytes are accounted for without a 26B123 position. The retention pointer (25G83 MAIN 0xe88) +# leaves MAIN and moves to RUNTIME +0x2c8. +DROPPED = {MAIN: [(0x640 + 36 * 0x28, 0x28), (0xe88, 8)]} +# Power config: the words the host writes and the temperature pointer. +POWER_MAP = [(0x3b50, 0x3b98, 8)] + fields([ + (0x4, 0x4), (0x8, 0x8), (0x10, 0x10), (0x14, 0x14), (0x2c, 0x2c), (0x30, 0x30), + (0x9f0, 0xa00), (0x9f4, 0xa04), (0xa38, 0xa48), (0xaa8, 0xab8), (0xaac, 0xabc), + (0xaf0, 0xb00), (0xb78, 0xb88), (0xb7c, 0xb8c), (0xb80, 0xb90), (0xbc0, 0xbd0), + (0x2210, 0x2220), (0x22b0, 0x22c0), (0x22b4, 0x22c4), (0x22f8, 0x2308), (0x279e, 0x27ae), + (0x2870, 0x2880), (0x2a3c, 0x2a64), (0x2b84, 0x2bac), (0x2b88, 0x2bb0), (0x2b8c, 0x2bb4), + (0x2bcc, 0x2bf4), (0x2c40, 0x2c68), (0x2c44, 0x2c6c), (0x2c88, 0x2cb0)]) +# Words new in 26B123 that the host writes: the u64 crash copy buffer size at HW data 0xfa8. +NEW_26B123 = {MAIN: [(0xfa8, 0x8000)]} +MOVED = {GLOBALS: GLOBALS_MAP, FIRMWARE_DATA: FIRMWARE_DATA_MAP, MAIN: MAIN_MAP, + POWER_PERFORMANCE: POWER_MAP, + # Main config: only the power-config pointer moves (16 bytes later). + RUNTIME: [(0, 0, 0x469), (0x469, 0x479, 8)]} + + +def split(image, sizes): + out, at = [], 0 + for size in sizes: + out.append(image[at:at + size]) + at += size + assert at == len(image), (at, len(image)) + return out + + +def name_index(name): + return int(name.split()[1]) if name.startswith('object ') else -1 + + +def moved(old, size, table, name): + """New object of `size` bytes holding `old`'s fields at their new offsets; every non-zero + byte of `old` must belong to some field.""" + new, covered = bytearray(size), bytearray(len(old)) + for at, to, width in table: + new[to:to + width] = old[at:at + width] + covered[at:at + width] = b'\1' * width + for at, width in DROPPED.get(name_index(name), []): + covered[at:at + width] = b'\1' * width + stray = [hex(i) for i, (b, c) in enumerate(zip(old, covered)) if b and not c] + assert not stray, f'{name}: 25G83 bytes without a 26B123 position: {stray[:8]}' + return new + + +def expect_initdata(old_image): + old = split(old_image, OBJECTS_25G83) + new = [] + for index, (before, size) in enumerate(zip(old, OBJECTS_26B123)): + if index == ROOT: + assert struct.unpack_from(' = core::result::Result; const EIO:Error=Error(-5); const ENODEV:Error=Error(-19); const ECANCELED:Error=Error(-125); const ETIMEDOUT:Error=Error(-110);const ENOMEM:Error=Error(-12);const EAGAIN:Error=Error(-11); const EINVAL:Error=Error(-22); -const EOVERFLOW:Error=Error(-75); const NONE:u16=u16::MAX; +const EOVERFLOW:Error=Error(-75); const NONE:u16=u16::MAX; const COMPUTE:usize=1; ORDER_SOURCE pub mod task { pub const MAX_SCHEDULE_TIMEOUT:i64=i64::MAX; } struct InputState { status:AtomicI32,waits:AtomicUsize,interrupted:AtomicI64,gate:Mutex<()>,changed:Condvar } @@ -96,7 +96,7 @@ def function(text, name): } } mod command { pub(crate) use super::Order; } -struct QueueState { completed:[AtomicU64;2],cancelled_at:[AtomicU64;2] } +struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2] } impl QueueState { QUEUE_METHODS } struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,orders:Vec,queue:Arc,full_retired:AtomicU32,terminal_retired:AtomicBool } struct Shared { crashed:AtomicBool,submitted:Mutex>,submit_result:Result } @@ -116,7 +116,7 @@ def function(text, name): } fn job_with_inputs(id:u64,status:Arc,inputs:Vec)->Arc { let orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap(),Order::new([0,0],[0,1],[NONE;2],[0;2],1).unwrap()]; - job_with_orders(id,status,inputs,orders,Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]})) + job_with_orders(id,status,inputs,orders,Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]})) } fn job_with_orders(id:u64,status:Arc,inputs:Vec,orders:Vec,queue:Arc)->Arc { Arc::new(Job{id,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), @@ -278,7 +278,7 @@ def function(text, name): } #[test] fn cancellation_checks_both_command_ordinal_and_cross_engine_failed_prefix() { - let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]}); + let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]}); let cutoff=Order::new([0,2],[0,0],[NONE;2],[0;2],1).unwrap();queue.cancel(&[cutoff],0); let earlier=Order::new([0,1],[0,0],[NONE;2],[0;2],1).unwrap(); let independent_render=Order::new([0,3],[0,0],[NONE;2],[0;2],0).unwrap(); @@ -292,7 +292,7 @@ def function(text, name): } #[test] fn exact_prefix_does_not_wait_for_the_aggregate_or_next_ordinal() { - let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]}); + let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]}); let status=Arc::new(Status::new()); let old=job_with_orders(1,status.clone(),vec![],vec![ Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap(), diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py index 0daa8ffdcd8d8..667b38a0998d6 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py @@ -27,6 +27,23 @@ def node(props, children=()): image = node({'name': b'device-tree\0'}, [node({'name': b'arm-io\0'}, [node({'name': b'sgx\0', **properties})])]) blob = out / 'measured-perf.adt' blob.write_bytes(image) +clpc_props = { + 'cpu-avg-limiter-input-tc': struct.pack(' usize { data.windows(32).position(|value| value.starts_with(name) && value[name.len()..].iter().all(|&x| x==0)).unwrap() @@ -56,6 +74,9 @@ def node(props, children=()): loader_va: core::array::from_fn(|i| if wire::LOADERS[i].length==0 {0} else {HOST+0x5000000+i as u64*0x100000+(wire::LOADERS[i].pa&0x3fff)}), scratch: HOST+0xa000000, lower_uma: wire::BOOTSTRAP_START, lower_parameter: wire::BOOTSTRAP_START+0x8000, ktrace_mask:0, progress_recovery:1, + power_sample_clks:200_000, power_sample_us:8333, power_sample_period_ms:8, + timebase_khz:24_000, avg_power_filter_tc_ms:248, lowpeak_limiter_tc_ms:16, + lowpeak_limiter_ki_q16:134_217, lowpeak_limiter_kp_q16:33_554, coredump_copy_size:0x8000, } } fn encode(performance: wire::Performance) -> Result<[Vec; wire::OBJECT_COUNT], ()> { @@ -98,8 +119,8 @@ def node(props, children=()): [100,590,630,650,690,730,790,840,890,940,990], [760,760,760,760,760,760,790,840,890,940,990]), ] { - let (p,name)=data::select_named(&j773g(core,sram),Some(11)).unwrap(); - assert_eq!(name,"J773g"); assert_eq!(p.count,11); + let (p,name)=data::select_named(&j773g(core,sram)).unwrap(); + assert_eq!(name,"11-row"); assert_eq!(p.count,11); assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,1578]); assert_eq!(p.auxiliary,[0,338,618,796,928,952,1053,1152,1204,1326,1578]); assert_eq!(p.voltage,voltage); assert_eq!(p.sram,row_sram); @@ -118,7 +139,7 @@ def node(props, children=()): #[test] fn the_row_count_bounds_the_encoded_ceiling() { let j713=tables(); let j773g=data::select_named(&j773g( [100,600,620,660,700,750,750,800,800,850,850,900,900,950,950,1000], - [740,740,740,740,740,750,750,800,800,850,850,900,900,950,950,1000]),Some(11)).unwrap().0; + [740,740,740,740,740,750,750,800,800,850,850,900,900,950,950,1000])).unwrap().0; for (p,good,bad) in [(j713,[1,9],[0,10]),(j773g,[1,10],[0,11])] { for ceiling in good { let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); @@ -201,10 +222,9 @@ def node(props, children=()): let mut s=source();s.core_mv[6]=s.core_mv[5];s.sram_mv[6]=s.sram_mv[5];assert!(data::select(&s).is_err()); let mut s=source();s.core_mv[4]-=1;s.core_mv[6]-=1;assert!(data::select(&s).is_err()); } -#[test] fn j604_shape_selects_its_own_layout_and_the_j713_keeps_its_own() { - assert_eq!(data::select_named(&source(),None).unwrap().1,"J713"); - // J604 shape: five low states, equal-voltage pairs 5/6 to 13/14, a single top state 15. - // Rows 0-3 and 5-15 are the J604's selected values; state 4 (left out) is synthetic. +#[test] fn eleven_row_shape_selects_all_eleven_rows_from_adt_without_board_check() { + assert_eq!(data::select_named(&source()).unwrap().1,"10-row"); + // 11-row shape (J604/J773g): five low states, equal-voltage pairs 5/6 to 13/14, single top 15. let mhz=[0,338,618,796,928,952,1056,1053,1170,1152,1278,1204,1338,1326,1470,1578]; let mv=[125,625,640,680,725,780,780,825,825,865,865,895,895,970,970,1045]; let mut s=source(); @@ -212,27 +232,17 @@ def node(props, children=()): s.frequency_mhz[i]=mhz[i];s.sram_frequency_mhz[i]=mhz[i]; s.core_mv[i]=mv[i];s.sram_mv[i]=mv[i].max(780); } - let (p,name)=data::select_named(&s,None).unwrap(); - assert_eq!(name,"J604"); assert_eq!(p.count,10); - assert_eq!(p.frequency,[0,338,618,796,1056,1170,1278,1338,1470,1578,0]); - assert_eq!(p.auxiliary,[0,338,618,796,952,1053,1152,1204,1326,1578,0]); - assert_eq!(p.voltage,[125,625,640,680,780,825,865,895,970,1045,0]); - assert_eq!(p.sram,[780,780,780,780,780,825,865,895,970,1045,0]); - assert!(encode(p.clone()).is_ok()); - // The board's row count picks between the two layouts of this shape. - assert_eq!(data::select_named(&s,Some(10)).unwrap(),(p,"J604")); - let (p,name)=data::select_named(&s,Some(11)).unwrap(); - assert_eq!(name,"J773g"); assert_eq!(p.count,11); + let (p,name)=data::select_named(&s).unwrap(); + assert_eq!(name,"11-row"); assert_eq!(p.count,11); assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,1578]); assert_eq!(p.auxiliary,[0,338,618,796,928,952,1053,1152,1204,1326,1578]); - // The J713 shape has no eleven-row layout, and no board has another row count. - assert_eq!(data::select_named(&source(),Some(10)).unwrap().1,"J713"); - assert_eq!(data::select_named(&source(),Some(11)),Err(perf::Error::Shape)); - for rows in [0,9,12] { assert_eq!(data::select_named(&s,Some(rows)),Err(perf::Error::Shape)); } - // A J604 shape with one unequal pair matches no layout. + assert_eq!(p.voltage,[125,625,640,680,725,780,825,865,895,970,1045]); + assert_eq!(p.sram,[780,780,780,780,780,780,825,865,895,970,1045]); + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + assert!(wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),10).is_ok()); + // An 11-row shape with one unequal pair matches no layout. let mut bad=s;bad.core_mv[9]+=1;bad.sram_mv[9]+=1; assert_eq!(data::select(&bad),Err(perf::Error::Shape)); - assert_eq!(data::select_named(&bad,Some(11)),Err(perf::Error::Shape)); } #[test] fn invalid_encoder_input_is_refused_without_mutating_output() { for variant in 0..5 { @@ -242,9 +252,39 @@ def node(props, children=()): assert!(buffers.iter().all(|buffer|buffer.iter().all(|&byte|byte==0xa5))); } } +#[test] fn clpc_and_sgx_power_limiter_properties_parse_and_reject_zero() { + let minimal = source(); + assert_eq!(minimal.avg_power_filter_tc_ms, None); + assert_eq!(minimal.lowpeak_limiter_tc_ms, None); + let full = perf::parse(MEASURED_CLPC).unwrap(); + assert_eq!(full.power_sample_clks, Some(200_000)); + assert_eq!(full.power_sample_period_ms, Some(8)); + assert_eq!(full.avg_power_filter_tc_ms, Some(248)); + assert_eq!(full.lowpeak_limiter_tc_ms, Some(16)); + assert_eq!(full.lowpeak_limiter_ki_q16, Some(134_217)); + assert_eq!(full.lowpeak_limiter_kp_q16, Some(33_554)); + assert_eq!(full.coredump_copy_size, Some(0x8000)); + for name in [ + b"gpu-pwr-sample-period-aic-clks".as_slice(), + b"gpu-power-sample-period", + b"cpu-avg-limiter-input-tc", + b"cpu-lowpeak-limiter-input-tc", + b"cpu-lowpeak-limiter-ki", + b"cpu-lowpeak-limiter-kp", + b"coredump-copy-buffer", + ] { + let mut bad = MEASURED_CLPC.to_vec(); + set_cell(&mut bad, name, 0); + assert_eq!(perf::parse(&bad), Err(perf::Error::Range)); + } + let mut unaligned = MEASURED_CLPC.to_vec(); + set_cell(&mut unaligned, b"coredump-copy-buffer", 0x8001); + assert_eq!(perf::parse(&unaligned), Err(perf::Error::Range)); +} ''' for marker, value in {'PARSER': backend / 'adt/perf.rs', 'ENCODER': backend / 'fw/initdata.rs', - 'SELECT': backend / 'board/data.rs', 'FIXTURE': blob}.items(): + 'SELECT': backend / 'board/data.rs', 'FIXTURE': blob, + 'FIXTURE_CLPC': blob_clpc}.items(): source = source.replace('@' + marker + '@', str(value)) path = out / 'perf.rs' path.write_text(source) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 6f388b4693fd4..d59521d36719b 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -39,7 +39,8 @@ def item(declaration): fn count(&self)->u32{self.count} fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } -struct Job { id:u32,vm:Vm,queue:Queue,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool } +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}} +struct Job { id:u32,vm:Vm,queue:Queue,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} fn mark_terminal_retired(&self)->Result{assert!(!self.progress.pending.load(Ordering::Relaxed));self.terminal_marked.store(true,Ordering::Relaxed);Ok(())} @@ -64,6 +65,7 @@ def item(declaration): impl Slots{ fn compute_exhausted(&self)->bool{self.compute_exhausted} fn render_exhausted(&self)->bool{self.render_exhausted} + fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted} fn release(&mut self,_claims:&mut Claims){self.releases+=1;} fn quarantine(&mut self,_claims:&mut Claims){self.quarantines+=1;} } @@ -114,6 +116,9 @@ def item(declaration): } impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} + // Queuing behind in-flight compute is exercised on hardware; this recorder keeps the + // serialized selection and error isolation under test. + fn can_queue_behind(&self,_job:&Arc)->bool{false} fn service_power(&self)->Result{Ok(())} fn drain_rings(&mut self)->Result{Ok(())} fn check_hangs(&mut self,_done:&mut Completions)->Result{Ok(())} @@ -139,12 +144,13 @@ def item(declaration): } __PUBLISH_PREFIX__ __PUBLISH__ + __PUBLISH_CHECKED__ } fn job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ Arc::new(Job{id,vm:Vm{status:Status(AtomicU32::new(0)),slot:id}, queue:Queue{turn:AtomicU64::new(0),priority:0}, progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(())};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false)}) + commands:vec![if render{Command::Render(())}else{Command::Compute(())};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)}},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, @@ -239,6 +245,7 @@ def item(declaration): '__UNPEND__': 'fn unpend(&mut self', '__PUBLISH_PREFIX__': 'fn publish_prefix(', '__PUBLISH__': 'pub(crate) fn publish(&mut self', + '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', }.items(): diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py index 36f4cdeac268e..031d918925c00 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py @@ -31,7 +31,7 @@ // This is the retirement policy used by poll.rs: an affected fence does not // erase the independently authenticated owner receipt. No synthetic receipt // is generated here; the hardware poller remains responsible for that proof. - fn finish(owners: &mut Lifetime, unit: usize, receipt: Retirement, affected: bool) -> bool { + fn finish(owners: &mut Lifetime, unit: usize, receipt: Retirement, affected: bool) -> bool { assert!(receipt.complete()); if receipt.owner_retired() { assert!(owners.retire(unit)); @@ -43,7 +43,7 @@ #[test] fn ten_thousand_affected_full_receipts_preserve_displacement() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); for number in 0..10_000 { let unit = number % 2; assert!(owners.claim(unit)); @@ -58,7 +58,7 @@ #[test] fn actual_abort_never_supplies_a_displacement_receipt() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); assert!(owners.claim(0)); assert!(owners.publish(0)); assert!(!finish(&mut owners, 0, Retirement::Full, false)); @@ -77,8 +77,8 @@ #[test] fn exhausted_compute_ledger_does_not_poison_render_ledger() { - let mut compute = Lifetime::new(); - let mut render = Lifetime::new(); + let mut compute = Lifetime::<2>::new(false); + let mut render = Lifetime::<2>::new(false); assert!(compute.claim(0)); assert!(compute.publish(0)); finish(&mut compute, 0, Retirement::Aborted, true); @@ -101,7 +101,7 @@ #[test] fn two_aborts_stay_bounded_and_cannot_be_reset_by_preparation_cancel() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); for unit in 0..2 { assert!(owners.claim(unit)); assert!(owners.publish(unit)); @@ -115,7 +115,7 @@ #[test] fn repeated_handshakes_and_storm_limit_preserve_owner_accounting() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); let (mut window, mut count) = (1, 0); for number in 0..logic::WINDOW_LIMIT { assert!(logic::admit(100, &mut window, &mut count)); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py index fc1682600f23f..41a8c1a9dd217 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py @@ -43,10 +43,11 @@ def function(text, name): struct Graph{compute:CGraph,render:RGraph} struct Vm{slot:u32}struct Job{vm:Vm,resources:Resources} struct Resources{compute:Vec,passes:Vec,pools:Pools} -impl Resources{fn compute(&self)->Result<&Self>{Ok(self)}fn render(&self)->Result<&Self>{Ok(self)}} +impl Resources{fn compute(&self)->Result<&Self>{Ok(self)}fn render(&self)->Result<&Self>{Ok(self)}fn compute_unit(&self,k:usize)->Result<&CUnit>{self.compute.get(k).ok_or(EINVAL)}} struct Claims{slot:[u32;1],pass:[u32;1]} struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} -struct Engine{flights:Vec} +struct Engine{flights:Vec,target:u32} +fn stamp_reached(observed:u32,own:u32,tail:u32)->bool{logic::stamp_reached(observed,own,tail)} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} struct CUnit{counter:Object,its:Object,work:Object} struct RUnit{scene:Object} @@ -58,6 +59,9 @@ def function(text, name): fn rmb(){}fn now_ns()->u64{100_000_000} impl Firmware{ fn queue_receipt(&self,_ch:Channel,_state:&Object,_info:&Object,_head:u32,_rec:u32)->Result{Ok(self.queue_passed)} + fn queue_passed(&self,_ch:Channel,_state:&Object,_info:&Object,_f:&Flight)->Result{Ok(self.queue_passed)} + // The ITS-pair ticks (25G83, and the first choice on 26B123): the receipt tests set them. + fn compute_ticks(&self,unit:&CUnit)->Result<(u64,u64)>{Ok((unit.its.r64(0)?,unit.its.r64(8)?))} __RETIRED__ __RETIRED_SNAPSHOT__ } @@ -66,7 +70,7 @@ def function(text, name): let mut f=Firmware{ graph:Graph{compute:CGraph{fw_stamp:Object::default(),qstate:Object::default(),qinfo:Object::default(),notifier:Object::default()}, render:RGraph{fw_stamp:Default::default(),qstate:Default::default(),qinfo:Default::default(),notifier:Object::default()}}, - engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true}}},claims:Claims{slot:[0],pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],recovery_suspect:false,recovery_started_ns:0,doomed:false}]}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true}}},claims:Claims{slot:[0],pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],recovery_suspect:false,recovery_started_ns:0,doomed:false}],target}, slots:Slots{scrub:Scrub{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}]}}, pools:Pools{full:true},queue_passed:true, }; @@ -113,6 +117,25 @@ def function(text, name): } }} } +#[test]fn queued_compute_flight_retires_on_passed_receipts_in_order(){ + for n in [0x7fffff,0x800000,0xffffff,0x1000000,0x1000001]{ + let mut f=firmware(false,n); + let later=firmware(false,n+1).engine.flights.remove(0); + f.engine.flights.push(later);f.engine.target=encode::stamp(n+1); + // The command behind it finished too: the shared stamp and notifier cells name it. + f.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(n+1))); + f.graph.compute.notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(n+1))); + f.graph.compute.notifier.set(notifier_page::COMPUTE_CONTEXT,9); + assert_eq!(f.retired(),Ok(Retirement::Full)); + f.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(n-1))); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(n))); + assert_eq!(f.retired(),Ok(Retirement::Full)); + f.queue_passed=false;assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.queue_passed=true;f.engine.flights[0].job.resources.compute[0].work.set(compute::DESCRIPTOR_COMPLETED,n-1); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + } +} #[test]fn changing_packed_receipt_remains_pending_and_stable_retry_can_retire(){ let mut f=firmware(false,1);f.engine.flights[0].job.resources.compute[0].its.unstable=true; assert_eq!(f.retired(),Ok(Retirement::Pending)); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py index 9a159e849e86b..2abd69cf194e1 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -161,7 +161,7 @@ def function(source, marker): pub struct Scrub{pub compute:Vec,pub passes:Vec} pub struct Slots{pub scrub:Scrub}pub struct Firmware{pub slots:Slots} pub struct Resources{pub compute:Vec,pub passes:Vec} - impl Resources{pub fn compute(&self)->Result<&Self>{Ok(self)}pub fn render(&self)->Result<&Self>{Ok(self)}} + impl Resources{pub fn compute(&self)->Result<&Self>{Ok(self)}pub fn render(&self)->Result<&Self>{Ok(self)}pub fn compute_unit(&self,k:usize)->Result<&Compute>{self.compute.get(k).ok_or(super::EINVAL)}} pub struct Job{pub commands:Vec,pub resources:Resources} pub struct Flight{pub job:Job,pub first:usize,pub count:usize,pub renders:u32} pub mod poll{use super::*;impl Firmware{ __RETIRE__ }} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py index 2c98ab19a751a..7553c91f4ffc8 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py @@ -20,11 +20,19 @@ def body(source, marker): i += 1 return source[start:i] uat = (ROOT/'drivers/gpu/drm/asahi/g16/uat.rs').read_text() +hw = (ROOT/'drivers/gpu/drm/asahi/g16/hw.rs').read_text() +# The production 25G83 firmware page-table leaves, admitted against the frozen C oracle below. +layout = hw[hw.index('pub(crate) const FW_25G83: FwLayout = FwLayout {'):] +leaves = layout[layout.index('leaves: Some(&[') + len('leaves: Some('):layout.index(']),') + 1] +hw_leaves = '\n'.join([body(hw, '#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub(crate) enum Segment {'), + body(hw, 'pub(crate) struct Leaves {'), + body(hw, '#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub(crate) struct PplMagic {'), + 'pub const LEAVES_25G83: &[Leaves] = ' + leaves + ';']) vm = (ROOT/'drivers/gpu/drm/asahi/g16/vm.rs').read_text() pt = (ROOT/'drivers/gpu/drm/asahi/pgtable.rs').read_text() methods = '\n'.join(body(uat, m) for m in [ - 'fn cold_snapshot(', 'fn admit_cold(', 'fn admit_table(', 'pub(crate) fn ttbat_is_clear(', - 'pub(crate) fn bootstrap(', + 'fn cold_snapshot(', 'fn admit_cold(', 'fn admit_table(', 'pub(crate) fn await_firmware_magic(', + 'pub(crate) fn ttbat_is_clear(', 'pub(crate) fn bootstrap(', 'fn verify_root(', 'fn shadow_l2(', 'pub(crate) fn sync_range(', 'fn sync_inner(', ]) prot_constants = pt[pt.index('const PTE_TYPE_BITS:'):pt.index('impl Prot {')] @@ -41,7 +49,9 @@ def body(source, marker): mod hw { pub const PAGE:u64=0x4000; pub const TABLES_SIZE:u64=0x40000; pub const UPPER:u64=0xfffffc0000000000; pub const HOST:u64=0xfffffc2000000000; pub const HOST_SIZE:u64=0x1000000000; pub const PPL_MAGIC:u64=0x4b1d000000000002; - pub const PA_MASK:u64=0x3ffffffc000; } + pub const PA_MASK:u64=0x3ffffffc000; + use std::ops::Range; + __HW_LEAVES__ } mod device { pub struct Device; } // The common PPL lease is modeled here; test-ppl.py executes its actual guard with // concurrency and timeout injection. This harness tests Window's graph operations. @@ -51,6 +61,7 @@ def body(source, marker): pub fn kernel_lower_root(&self)->u64 {self.lower} pub fn kernel_window_root(&self)->u64 {self.shadow} pub fn lock_m4_handoff(&self)->super::Result{super::note("ppl-lock");Ok(HandoffGuard)} } } macro_rules! dev_info {($($tt:tt)*)=>{()};} +macro_rules! dev_err {($($tt:tt)*)=>{()};} thread_local!{static TRACE:RefCell>=const{RefCell::new(Vec::new())};} fn note(s:impl Into){TRACE.with(|t|t.borrow_mut().push(s.into()));} fn take_trace()->Vec{TRACE.with(|t|std::mem::take(&mut *t.borrow_mut()))} @@ -64,9 +75,12 @@ def body(source, marker): fn try_write32(&self,v:u32,off:usize)->Result{self.data.borrow_mut().get_mut(off..off+4).ok_or(EINVAL)?.copy_from_slice(&v.to_le_bytes());note(format!("{}:{off:x}={v:x}",self.label));Ok(())} fn try_write64(&self,v:u64,off:usize)->Result{self.data.borrow_mut().get_mut(off..off+8).ok_or(EINVAL)?.copy_from_slice(&v.to_le_bytes());note(format!("{}:{off:x}={v:x}",self.label));Ok(())} } -struct Monotonic; struct Delta; impl Delta{fn from_millis(ms:u64)->u64{ms}} +struct Monotonic; +#[derive(Copy,Clone,PartialEq,Eq,PartialOrd,Ord)] struct Delta(u64); +impl Delta{fn from_millis(ms:u64)->Self{Self(ms)}fn as_micros_ceil(self)->u64{self.0*1000}} +fn fsleep(_:Delta){} struct Instant{n:std::cell::Cell,t:std::marker::PhantomData} -impl Instant{fn now()->Self{Self{n:std::cell::Cell::new(0),t:std::marker::PhantomData}}fn elapsed(&self)->u64{let n=self.n.get();self.n.set(n+1);n}} +impl Instant{fn now()->Self{Self{n:std::cell::Cell::new(0),t:std::marker::PhantomData}}fn elapsed(&self)->Delta{let n=self.n.get();self.n.set(n+500);Delta(n)}} fn mb(){note("mb");} fn wmb(){note("wmb");} fn rmb(){} mod mem{pub fn sync(){super::note("sync");}pub fn tlbi_range(asid:u8,va:usize,len:usize){super::note(format!("tlbi:{asid}:{va:x}:{len:x}"));}} fn tlbi_all(){note("tlbi_all");} fn clean_lower(_: &mmu::Uat)->Result{note("clean_lower");Ok(())} @@ -75,8 +89,8 @@ def body(source, marker): fn entry(pa:u64,index:usize)->Result{with_table(pa,index+1,|e|e[index].load(Ordering::Acquire))} fn clean_entries(pa:u64,first:usize,count:usize)->Result{with_table(pa,first+count,|_|())?;note(format!("clean:{pa:x}:{first}:{count}"));Ok(())} fn clean_page(pa:u64)->Result{clean_entries(pa,0,ENTRIES)} -struct Window{handoff:Mapping,ttbs:Mapping,root:Mapping,shared_l2:Mapping,image:Vec,snapshot:Vec,published:bool,firmware_root:[u64;2],text_pa:u64,data_pa:u64} -impl Window{fn blank()->Self{Self{handoff:Mapping::new(0x807000000,0x4000,"handoff"),ttbs:Mapping::new(0x808000000,0x4000,"ttbs"),root:Mapping::new(0x800000000,0x40000,"root"),shared_l2:Mapping::new(0x801000000,0x4000,"shared"),image:vec![0;2048],snapshot:vec![0;2048],published:false,firmware_root:[0;2],text_pa:0x802000000,data_pa:0x803000000}} +struct Window{handoff:Mapping,ttbs:Mapping,root:Mapping,shared_l2:Mapping,image:Vec,snapshot:Vec,published:bool,firmware_root:[u64;2],text_pa:u64,data_pa:u64,leaves:&'static [hw::Leaves],ppl:hw::PplMagic} +impl Window{fn blank()->Self{Self{handoff:Mapping::new(0x807000000,0x4000,"handoff"),ttbs:Mapping::new(0x808000000,0x4000,"ttbs"),root:Mapping::new(0x800000000,0x40000,"root"),shared_l2:Mapping::new(0x801000000,0x4000,"shared"),image:vec![0;2048],snapshot:vec![0;2048],published:false,firmware_root:[0;2],text_pa:0x802000000,data_pa:0x803000000,leaves:hw::LEAVES_25G83,ppl:hw::PplMagic{ap:hw::PPL_MAGIC,firmware:hw::PPL_MAGIC,answers:false}}} ''' post = r''' } @@ -103,6 +117,27 @@ def body(source, marker): for i in 0..195{w.handoff.try_write64(1,0x20+i*8).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY));w.handoff.try_write64(0,0x20+i*8).unwrap();} for i in 0..128{w.ttbs.try_write64(1,i*8).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY));w.ttbs.try_write64(0,i*8).unwrap();} } +// 26B123: the firmware builds its own tree at start, so only an empty tree is admitted, and it +// leaves its own magic at +8 of the handoff page once it has run. +fn firmware_built_tree_tests(){ + const FW:u64=0x4b1d000000000003; + let fresh=||{let mut w=Window::blank();w.leaves=&[];w.ppl=hw::PplMagic{ap:FW,firmware:FW,answers:true};w}; + assert!(fresh().admit_cold().is_ok()); + let mut built=seeded();built.leaves=&[];assert_eq!(built.admit_cold(),Err(EINVAL)); + let mut w=fresh();w.root.try_write64(fw_word(0,&w),0).unwrap();assert_eq!(w.admit_cold(),Err(EINVAL)); + let mut w=fresh(); + w.handoff.try_write64(FW,8).unwrap();assert!(w.admit_cold().is_ok()); + w.handoff.try_write64(hw::PPL_MAGIC,8).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY)); + w.handoff.try_write64(0,8).unwrap();w.handoff.try_write64(hw::PPL_MAGIC,0).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY)); + w.handoff.try_write64(FW,0).unwrap();assert!(w.admit_cold().is_ok()); + let uat=mmu::Uat{lower:0x804000000,shadow:0x805000000};let l2=0x805004000;let l3=0x805008000; + {let mut ram=RAM.lock().unwrap();for pa in [uat.shadow,l2,l3]{ram.insert(pa,(0..2048).map(|_|AtomicU64::new(0)).collect());}ram[&uat.shadow][2].store(l2|3,Ordering::Release);} + for firmware_magic in [0,FW]{let mut w=fresh();w.handoff.try_write64(firmware_magic,8).unwrap();w.bootstrap(&device::Device,&uat).unwrap(); + // Answering builds always clear +8 before RUN so a stale magic cannot satisfy the wait. + assert_eq!(w.handoff.try_read64(0).unwrap(),FW);assert_eq!(w.handoff.try_read64(8).unwrap(),0);assert_eq!(w.handoff.try_read8(0x638).unwrap(),1); + assert_eq!(w.await_firmware_magic(&device::Device),Err(ETIMEDOUT)); + w.handoff.try_write64(FW,8).unwrap();assert_eq!(w.await_firmware_magic(&device::Device),Ok(()));} +} fn publication_tests(){ let uat=mmu::Uat{lower:0x804000000,shadow:0x805000000};let l2=0x805004000;let l3=0x805008000; {let mut ram=RAM.lock().unwrap();for pa in [uat.shadow,l2,l3]{ram.insert(pa,(0..2048).map(|_|AtomicU64::new(0)).collect());}ram[&uat.shadow][2].store(l2|3,Ordering::Release);ram[&l2][4].store(l3|3,Ordering::Release);ram[&l3][0].store(0x806000000|0x00e000000000040b,Ordering::Release);} @@ -117,9 +152,9 @@ def body(source, marker): for p in [0x00c000000000044bu64,0x00e000000000040b,0x00c0000000000443,0x00e0000000000403,0x00c0000000000447,0x0080000000000447,0x00200000000004c7]{assert_eq!(Prot::from_pte(p).leaf_bits()|3,p);} let ranges=reserved_ranges();assert_eq!(ranges,[0x1000000000..0x1000010000,0x7000000000..0x7100000000]);assert_eq!(ranges[1].end-ranges[1].start,4u64<<30); } -fn main(){let args:Vec<_>=std::env::args().collect();for id in 0..12{assert_c_parity(&mutation(id),id,&args[1],&args[2]);}root_admission_tests();publication_tests();prot_and_va_tests();println!("12 C/Rust firmware-graph parity fixtures; 195 flush, 128 TTBAT ownership rejections; stopped publication ordering; live link ownership/global TLBI; exact M4 leaf classes/VA reservations passed (mock hardware; PPL lease mocked and tested separately)");} +fn main(){let args:Vec<_>=std::env::args().collect();for id in 0..12{assert_c_parity(&mutation(id),id,&args[1],&args[2]);}root_admission_tests();publication_tests();firmware_built_tree_tests();prot_and_va_tests();println!("12 C/Rust firmware-graph parity fixtures; 195 flush, 128 TTBAT ownership rejections; stopped publication ordering; live link ownership/global TLBI; exact M4 leaf classes/VA reservations; empty firmware-built tree and +8 firmware magic passed (mock hardware; PPL lease mocked and tested separately)");} ''' -harness = pre + methods + post + prot_constants + prot_impl + reserved +harness = pre.replace('__HW_LEAVES__', hw_leaves) + methods + post + prot_constants + prot_impl + reserved (OUT/'check-vm.rs').write_text(harness) golden = OUT/'golden' From 2244998f3fc6a6cc3e14cf22aea78778084ba63f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 09:15:23 +1100 Subject: [PATCH 06/19] drm/asahi: g16: Write all four 26B123 power-up words, so the GPU survives a deep wake The 26B123 POWER_PERFORMANCE layout inserts four u32s at +0x9c. G16 writes only +0xa4, the powered-up state selector. That is enough for a cold boot, but not for the firmware's warm restart after a deep sleep: on the J713 (M4 Air) the first deep wake ends with "GPU firmware back in 691 us" and, 0.3 ms later, "RTKit: co-processor has crashed" in the firmware's power-up path, before any client has submitted work. The GPU is gone until reboot. macOS 27.2 sets all four words to 1, and so did this driver before the 26B123 layout was reworked. Write +0x9c, +0xa0 and +0xa8 again, next to +0xa4. The words belong to the 26B123 layout, so they are selected by the firmware ABI, as before; 25G83 is unchanged. On the J713 (macOS 27.2 firmware, default kernel command line) with the external monitor and the USB4 peer attached: 3 of 3 deep sleeps wake with the GPU alive, with vkmark running across the first sleep, then dEQP-VK smoke and glmark2 after the wakes. Without the change the same kernel crashed on the first wake. The host tests and the 26B123 offset oracle are updated for the three words. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 11 +++++++---- .../selftests/drivers/gpu/asahi-m4/test-abi-26b123.py | 6 +++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 3b74ce8736f4a..864a1e9bc3f65 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -364,10 +364,13 @@ pub(crate) const V26B123: Layout = Layout { coredump_copy: Some(0xfa8), retention: Retention::Runtime(0x2c8), globals_policy: &[], - // 0xa4 selects the powered-up state; leaving 0 there keeps the GPU unpowered and triggers an - // SError on power-up. The low-peak (PPM) limiter words at +0xa80..+0xae0 are computed from - // the machine's ADT in `power_limiter`. - power_policy: &[(0xa4, 1)], + // The four u32s this build inserts at +0x9c, 1 each as macOS 27.2 writes them. 0xa4 selects + // the powered-up state; leaving 0 there keeps the GPU unpowered and triggers an SError on + // power-up. The firmware's warm restart after a deep sleep needs the other three as well: with + // only 0xa4 set it crashed in its power-up right after the RTKit handshake on the first wake. + // The low-peak (PPM) limiter words at +0xa80..+0xae0 are computed from the machine's ADT in + // `power_limiter`. + power_policy: &[(0x9c, 1), (0xa0, 1), (0xa4, 1), (0xa8, 1)], // Exact power sample period (from `gpu-pwr-sample-period-aic-clks`, in us) and the // average-power IIR filter over the ADT's `cpu-avg-limiter-input-tc`. power_sampling: Some(PowerSampling { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py index fa6239d6f8a7a..b82324d7647fe 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py @@ -121,9 +121,9 @@ def expect_initdata(old_image): assert not any(after[0x2c8:0x2d0]) after[0x2c8:0x2d0] = old[MAIN][0xe88:0xe90] if index == POWER_PERFORMANCE: - # 26B123 power-up state selector (+0xa4) plus ADT-derived low-peak (PPM) limiter - # and average-power sampling filter words. - for at, value in ((0xa4, 1), (0xa80, 8), (0xa8c, 0x3f000000), (0xa94, 0x3f000000), + # 26B123 power-up words (+0x9c..+0xa8, +0xa4 selects the powered-up state) plus + # ADT-derived low-peak (PPM) limiter and average-power sampling filter words. + for at, value in ((0x9c, 1), (0xa0, 1), (0xa4, 1), (0xa8, 1), (0xa80, 8), (0xa8c, 0x3f000000), (0xa94, 0x3f000000), (0xa9c, 0x3c86378d), (0xaa8, 0x47800000), (0xaac, 0x3f031200), (0xad8, 0x10), (0xae0, 0x5dc00), (0x29e4, 116), (0x29f0, 0x3f772c23), (0x29f8, 0x3d0d3dcb), (0x2b48, 8333), (0x2bbc, 0x46023400), From 02370c0d89cde9e6e3d9bd63ded16c52c7e9a0e2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 21:08:05 -0500 Subject: [PATCH 07/19] drm/asahi: g16: defer recovery snapshot/fault_scan to phase 1 and clear idle phase-0 notices Defer recovery storm admission, pool invalidation, stage snapshot capture, and fault_scan() until firmware actually halts in phase 1 inside MarkAndAcknowledge, instead of running them before the phase loop while firmware may still be executing on phase 0. Also dismiss trailing type-4/0x16 recovery notifications when phase stays at 0 with no flights in flight for 50 ms (PHANTOM_PHASE0_WAIT_NS), so a late notification drained after Resume does not spin for the full 1000 ms recovery budget and fail-stop the GPU. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/recovery.rs | 62 +++++++++++++-------- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 24 ++++++++ 2 files changed, 64 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index f1aa0f417c028..70e250a3b8ef7 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -374,29 +374,8 @@ impl Firmware { fn recover(&mut self) -> Result { let start = self.events.recovery_started_ns.unwrap_or_else(now_ns); - if !logic::admit( - start, - &mut self.recovery.window_ns, - &mut self.recovery.window_count, - ) { - dev_err!(self.dev(), "M4 GPU recovery storm: fail-stop\n"); - return Err(EIO); - } self.recovery.running = true; self.engine.frozen = true; - // A recovery may reset what the firmware keeps for a bound PB epoch, also one whose - // render was not affected: start the next render on each pass slot fresh. - self.pools.invalidate(); - self.events.grow.clear(); - // These frontiers must be captured before the host answers 2: the - // firmware can force the stage target while aborting a work item. - let stage = self.recovery_snapshot()?; - // Powered down, the GPU holds no fault to read. - let fault = self.session.fault_scan()?.unwrap_or_default(); - let asid = Some(fault.status) - .filter(|status| status & 1 != 0) - .map(|status| ((status >> 17) & 0x3f) as u32) - .filter(|asid| *asid >= 1); let deadline = start.saturating_add(logic::RECOVERY_BUDGET_NS); let mut answered = false; let mut generation = 0; @@ -425,6 +404,14 @@ impl Firmware { poll_sleep(); continue; } + if !logic::admit( + now, + &mut self.recovery.window_ns, + &mut self.recovery.window_count, + ) { + dev_err!(self.dev(), "M4 GPU recovery storm: fail-stop\n"); + return Err(EIO); + } generation = current_generation; let event = if have_event { let event = self.events.last_error.ok_or(super::boot::eproto())?; @@ -436,6 +423,19 @@ impl Firmware { } else { u32::MAX }; + // Firmware is now halted in phase 1: invalidate bound PB state and + // capture stage frontiers and fault-bank state before answering 2 + // (firmware may force stage targets while aborting work, and fault_scan + // writes the fault-bank selector so it must not run against active FW). + self.pools.invalidate(); + self.events.grow.clear(); + let stage = self.recovery_snapshot()?; + // Powered down, the GPU holds no fault to read. + let fault = self.session.fault_scan()?.unwrap_or_default(); + let asid = Some(fault.status) + .filter(|status| status & 1 != 0) + .map(|status| ((status >> 17) & 0x3f) as u32) + .filter(|asid| *asid >= 1); self.mark_recovery(stage, event, asid)?; // Snapshot reads and all TPC repairs precede acknowledgement. barrier(); @@ -470,7 +470,25 @@ impl Firmware { ); return Err(super::boot::eproto()); } - RecoveryAction::Wait => {} + RecoveryAction::Wait => { + if logic::phantom_phase0( + phase, + answered, + self.engine.flights.is_empty(), + now.saturating_sub(start), + ) { + self.recovery.errors_seen = self.events.errors; + self.recovery.statistics_seen = self.events.recovery_statistics; + self.events.recovery_started_ns = None; + self.recovery.running = false; + self.engine.frozen = false; + dev_warn!( + self.dev(), + "M4 GPU idle recovery notification cleared without phase 1\n" + ); + return Ok(()); + } + } } self.drain_rings()?; poll_sleep(); diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index 413c2be0ecef2..5a7aca6dd0ab2 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -29,6 +29,8 @@ pub(crate) const fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool // `fw::initdata::FirmwareData`. pub(crate) const RECOVERY_BUDGET_NS: u64 = 1_000_000_000; pub(crate) const EVENT_WAIT_NS: u64 = 50_000_000; +/// Bounded wait before dismissing a trailing phase-0 recovery notification on an idle GPU. +pub(crate) const PHANTOM_PHASE0_WAIT_NS: u64 = 50_000_000; pub(crate) const WINDOW_NS: u64 = 10_000_000_000; pub(crate) const WINDOW_LIMIT: u32 = 32; #[allow(dead_code)] @@ -77,6 +79,17 @@ pub(crate) enum RecoveryAction { ProtocolError, } +/// A type-4 or 0x16 notification drained after a completed recovery leaves phase at 0 with +/// no flights in flight. Consume it after a short bounded wait instead of spinning to fail-stop. +pub(crate) const fn phantom_phase0( + phase: u32, + answered: bool, + flights_empty: bool, + elapsed_ns: u64, +) -> bool { + phase == 0 && !answered && flights_empty && elapsed_ns >= PHANTOM_PHASE0_WAIT_NS +} + /// Only the host writes phases 2 and 0; the firmware publishes phases 1 and 3. /// An acknowledged recovery may not return to phase 0 or start a new phase 1. pub(crate) fn action(phase: u32, answered: bool, generation_matches: bool) -> RecoveryAction { @@ -246,6 +259,7 @@ mod tests { assert!(!expired(deadline, deadline)); assert!(expired(deadline + 1, deadline)); assert!(EVENT_WAIT_NS < RECOVERY_BUDGET_NS); + assert!(PHANTOM_PHASE0_WAIT_NS < RECOVERY_BUDGET_NS); assert!(ABORT_GRACE_NS < RECOVERY_BUDGET_NS); assert!(expired(1, EXPIRED)); assert_eq!(renew(7, 5000, 1000), (5_000_000_007, 1_000_000_007)); @@ -285,6 +299,16 @@ mod tests { } } + #[test] + fn phantom_phase0_clears_only_idle_unanswered_phase0_after_wait() { + assert!(!phantom_phase0(0, false, true, PHANTOM_PHASE0_WAIT_NS - 1)); + assert!(phantom_phase0(0, false, true, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(0, false, false, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(0, true, true, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(1, false, true, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(2, true, true, PHANTOM_PHASE0_WAIT_NS)); + } + #[test] fn stamps_and_wrapping_receipts() { assert!(!stamp_reached(0, 0x100, 0x300)); From 20cf2487e0a9c07256b9a7f24222c2ab9c3a5987 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 09:39:46 -0500 Subject: [PATCH 08/19] drm/asahi: g16: set 26B123 MAIN +0x277e as macOS 27.2 does Live macOS 27.2 (26B123) InitData captures on J773g write 1 at MAIN (HW data) +0x277e, an unaligned u32 that 26B123 adds and that we left at zero. With it at zero, long single-dispatch compute shaders (compute.long, more than ~500 ms per workgroup) were falsely reported as stalled and the firmware started GPU recovery (event=[4, 0, 0, 0xf], stats[0]=0x16), as measured on J773g. Write 1 there, as macOS does. Add Layout::main_policy with compile-time disjointness validation in layout_fits(), set MAIN +0x277e = 1 on V26B123, and update the asahi-m4 host ABI and golden tests accordingly. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 52 ++++++++++++++++++- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 10 ++++ .../drivers/gpu/asahi-m4/test-abi-26b123.py | 11 ++-- 3 files changed, 66 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 864a1e9bc3f65..1bbc1fafa0b10 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -143,6 +143,8 @@ pub(crate) struct Layout { pub(crate) coredump_copy: Option, /// Where the RETENTION object is published. pub(crate) retention: Retention, + /// MAIN (HW data) words of this build that have no 25G83 position, at their own offsets. + pub(crate) main_policy: &'static [(usize, u32)], /// GLOBALS (region C) words of this build that have no 25G83 position, at their own offsets. pub(crate) globals_policy: &'static [(usize, u32)], /// POWER_PERFORMANCE (power config) words of this build that have no 25G83 position, at @@ -302,6 +304,7 @@ pub(crate) const V25G83: Layout = Layout { pstate_selectors: [0x88, 0x8c, 0x98], coredump_copy: None, retention: Retention::Main, + main_policy: &[], globals_policy: &[], power_policy: &[], power_sampling: None, @@ -312,8 +315,8 @@ pub(crate) const V25G83: Layout = Layout { /// - the main-config power-config pointer 16 bytes later; /// - a 60-slot register map in MAIN, then the retention pointer at 0xfa0, a new u64 at 0xfa8 /// (the crash copy buffer size), the old 0xe90.. words +0x120, 0xec0.. +0x11c (one word -/// removed at 0xebc), 0x2600.. +0x120 and the last bytes +0x124 (new u32s at 0x275c and -/// 0x277e, left zero); +/// removed at 0xebc), 0x2600.. +0x120 and the last bytes +0x124 (new u32s at 0x275c, left +/// zero, and 0x277e, enabled via `main_policy`); /// - a u32 inserted at GLOBALS 0x38, so every later word moves by four; /// - POWER_PERFORMANCE with words inserted at 0x9c (0x10 bytes), 0x28b0 (0x18), 0x3b50 (0x28) /// and 0x63cc (0x680), 8 bytes removed between 0x2d08 and 0x2f08 and 0x20 between 0x62c4 and @@ -363,6 +366,9 @@ pub(crate) const V26B123: Layout = Layout { // +0xfa8 faulted on the first resume from idle power-off. coredump_copy: Some(0xfa8), retention: Retention::Runtime(0x2c8), + // macOS 27.2 writes 1 here; with 0 the firmware falsely flags long compute dispatches as + // stalled. + main_policy: &[(0x277e, 1)], globals_policy: &[], // The four u32s this build inserts at +0x9c, 1 each as macOS 27.2 writes them. 0xa4 selects // the powered-up state; leaving 0 there keeps the GPU unpowered and triggers an SError on @@ -436,6 +442,44 @@ const fn ranges_overlap(a: usize, a_len: usize, b: usize, b_len: usize) -> bool a < b + b_len && b < a + a_len } +/// Every `main_policy` word fits in MAIN and is disjoint from every other policy word, the +/// register map, `coredump_copy`, and every remapped 25G83 MAIN run. +const fn main_policy_fits(layout: &Layout) -> bool { + let size = layout.object_size[id::MAIN]; + let map_len = layout.register_slots * LOADER_STRIDE; + let mut i = 0; + while i < layout.main_policy.len() { + let at = layout.main_policy[i].0; + if at + 4 > size || ranges_overlap(at, 4, 0x640, map_len) { + return false; + } + if let Some(cc) = layout.coredump_copy { + if ranges_overlap(at, 4, cc, 8) { + return false; + } + } + let mut j = 0; + while j < i { + if ranges_overlap(at, 4, layout.main_policy[j].0, 4) { + return false; + } + j += 1; + } + let mut r = 0; + while r < layout.main.len() { + let run = layout.main[r]; + let start = run.start + run.delta; + let len = run.end - run.start; + if ranges_overlap(at, 4, start, len) { + return false; + } + r += 1; + } + i += 1; + } + true +} + /// Every `globals_policy` word fits in GLOBALS and is disjoint from every other policy word, /// every p-state selector, and every remapped 25G83 GLOBALS word. const fn globals_policy_fits(layout: &Layout) -> bool { @@ -664,6 +708,7 @@ pub(crate) const fn layout_fits(layout: &Layout) -> bool { && runs_fit(layout.globals, size[id::GLOBALS]) && runs_fit(layout.power_performance, size[id::POWER_PERFORMANCE]) && retention_fits(layout) + && main_policy_fits(layout) && globals_policy_fits(layout) && power_policy_fits(layout) } @@ -1247,6 +1292,9 @@ pub(crate) fn encode_for( if let Some(at) = layout.coredump_copy { put64(main, at, input.coredump_copy_size)?; } + for &(at, value) in layout.main_policy { + put32(main, at, value)?; + } for (at, value) in [ (0xea0, 1), (0xee0, 1), diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs index 2ef40886e69c5..f8421689ef133 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs @@ -324,6 +324,15 @@ fn catalog() { assert!(!wire::layout_fits(&bad_globals)); bad_globals.globals_policy = &[(0x7c, 1)]; // collides with remapped 25G83 0x78 assert!(!wire::layout_fits(&bad_globals)); + let mut bad_main = wire::Layout { name: "test", ..wire::V26B123 }; + bad_main.main_policy = &[(0xfa8, 1)]; // collides with coredump_copy + assert!(!wire::layout_fits(&bad_main)); + bad_main.main_policy = &[(0x640, 1)]; // collides with register map + assert!(!wire::layout_fits(&bad_main)); + bad_main.main_policy = &[(0x2778, 1)]; // collides with remapped 25G83 0x2654 + assert!(!wire::layout_fits(&bad_main)); + bad_main.main_policy = &[(0x2786, 1)]; // overflows MAIN (0x2788) + assert!(!wire::layout_fits(&bad_main)); } fn main() { @@ -349,6 +358,7 @@ fn main() { // RETENTION object at RUNTIME +0x2c8. assert_eq!(r64(main, 0xfa0), 0); assert_eq!(r64(main, 0xfa8), input().coredump_copy_size); + assert_eq!(r32(main, 0x277e), 1); assert_eq!(r64(object(&v26, l, id::RUNTIME), 0x2c8), input().va[id::RETENTION]); // CRE (25G83 slot 28) is register-map slot 33 in 26B123. assert_eq!(r64(main, 0x640 + 33 * 0x28), 0x300d58000); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py index b82324d7647fe..a5765e8c4546d 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py @@ -65,8 +65,9 @@ def fields(pairs, width=4): (0x2210, 0x2220), (0x22b0, 0x22c0), (0x22b4, 0x22c4), (0x22f8, 0x2308), (0x279e, 0x27ae), (0x2870, 0x2880), (0x2a3c, 0x2a64), (0x2b84, 0x2bac), (0x2b88, 0x2bb0), (0x2b8c, 0x2bb4), (0x2bcc, 0x2bf4), (0x2c40, 0x2c68), (0x2c44, 0x2c6c), (0x2c88, 0x2cb0)]) -# Words new in 26B123 that the host writes: the u64 crash copy buffer size at HW data 0xfa8. -NEW_26B123 = {MAIN: [(0xfa8, 0x8000)]} +# Words new in 26B123 that the host writes: u64 crash copy buffer size at HW data 0xfa8, +# and u32 USC shader-core progress monitoring enable at HW data 0x277e. +NEW_26B123 = {MAIN: [(0xfa8, 8, 0x8000), (0x277e, 4, 1)]} MOVED = {GLOBALS: GLOBALS_MAP, FIRMWARE_DATA: FIRMWARE_DATA_MAP, MAIN: MAIN_MAP, POWER_PERFORMANCE: POWER_MAP, # Main config: only the power-config pointer moves (16 bytes later). @@ -130,9 +131,9 @@ def expect_initdata(old_image): (0x2c10, 8333)): assert not any(after[at:at + 4]), f'POWER_PERFORMANCE +{at:#x}' struct.pack_into(' Date: Sat, 21 Nov 2026 16:46:14 -0500 Subject: [PATCH 09/19] drm/asahi: g16: decouple PbEpoch standby pool from per-job Prepared Previously Cache::prepare() popped a spare PbEpoch (cap 4) or allocated and UAT-mapped a fresh 80 KiB PbEpoch for every queued render job, only for almost every render to reuse the slot's existing epoch and discard the unused epoch on drop once submission depth exceeded 4. Keep a shared per-VM standby pool in Cache::standby guarded by SpinLockIrq with the invariant epochs.len() >= reserved for all accepted unpublished render commands. Cache::prepare() tops up only the deficit in SUBMIT ioctl context before any fence exists, waiting interruptibly on a CondVar for standby headroom during bursts instead of failing with E2BIG (matching Budget::reserve's 10-second administrative bound) and retrying if a concurrent InitBM pops an epoch before commit. Steady-state queued renders at any depth allocate zero PbEpochs and perform zero UAT mappings or window syncs. Fresh InitBM publications draw from standby under the device lock without allocating, unpublished rollbacks return the unexposed epoch, and Cache::close() drops surplus epochs immediately while retaining only reserved epochs until accepted jobs drain. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 26 +- drivers/gpu/drm/asahi/g16/resources.rs | 299 ++++++++++++++---- .../drivers/gpu/asahi-m4/test-resources.py | 52 +++ 3 files changed, 313 insertions(+), 64 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 691fc1dc42a59..75caf7a98ecd3 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1000,8 +1000,12 @@ impl Firmware { (e, true) } None => { - let e = job.resources.pb(job.progress.sent() as usize)?.clone(); - e.prepare(k, arena.pools.heap_gva(k)?, arena.pools.heap_blocks())?; + let e = job.resources.take_pb()?; + if let Err(err) = e.prepare(k, arena.pools.heap_gva(k)?, arena.pools.heap_blocks()) + { + job.resources.return_pb(e); + return Err(err); + } self.pools.stats.fresh += 1; (e, false) } @@ -1074,6 +1078,23 @@ impl Firmware { job: &Arc, f: &mut Flight, visible: &mut bool, + ) -> Result { + let result = self.publish_prefix_body(job, f, visible); + if result.is_err() && !*visible { + if let Some(epoch) = f.pb.take() { + if epoch.unexposed() { + job.resources.return_pb(epoch); + } + } + } + result + } + + fn publish_prefix_body( + &mut self, + job: &Arc, + f: &mut Flight, + visible: &mut bool, ) -> Result { let behind = !self.engine.flights.is_empty(); if behind && !self.can_queue_behind(job) { @@ -1196,6 +1217,7 @@ impl Firmware { if render { let k = f.claims.pass[0] as usize; f.pb.as_ref().ok_or(EINVAL)?.expose(); + job.resources.commit_render(); job.resources.render()?.pools.publish(k, f.uma_submitted)?; // Notifier service dereferences u32 counters; the host ordering ledger // remains u64. Eight-byte spacing is retained allocation padding. diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 63238572b27ee..c7461db6b643e 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -13,17 +13,19 @@ use super::{ vm::VmState, }; use crate::mmu; -use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use kernel::{ - new_mutex, new_spinlock, + new_condvar, new_mutex, new_spinlock_irq, prelude::*, - sync::{Arc, Mutex, SpinLock}, + sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SpinLockIrq}, }; -/// Never-exposed PB epochs a VM keeps for its next renders. With PB epoch reuse most -/// renders never expose the epoch prepared for them; allocating and mapping a fresh one per -/// render submit costs far more than the render itself. -const SPARE_EPOCHS: usize = 4; +/// Never-exposed PB epochs an open VM keeps on standby after bursts drain. +/// +/// With PB epoch reuse most renders never expose a fresh epoch; keeping a +/// shared per-VM standby pool instead of attaching one epoch per queued job +/// avoids allocating and mapping fresh epochs whenever submission depth rises. +const SPARE_EPOCHS: usize = 32; pub(crate) struct ComputeArena(crate::cleanup::Deferred); impl core::ops::Deref for ComputeArena { @@ -141,15 +143,27 @@ struct Ready { last_compute_ns: u64, burst: u32, } +struct Standby { + /// Never-exposed epochs kept on standby for this VM's queued renders. + /// Invariant: while open or while `reserved > 0`, `epochs.len() >= reserved as usize`. + epochs: KVec>, + /// Accepted, not-yet-published render commands of this VM. + reserved: u32, +} + #[pin_data] pub(crate) struct Cache { #[pin] ready: Mutex, - /// Never-exposed epochs returned by retired jobs (at most [`SPARE_EPOCHS`]). Each holds - /// the VM, which holds this cache: [`Self::close`] breaks that cycle. + /// Shared per-VM standby pool of never-exposed PB epochs. Each holds the VM, which + /// holds this cache: [`Self::close`] drains surplus epochs immediately and the remaining + /// reserved epochs as accepted renders finish. #[pin] - spares: SpinLock>>, - /// The VM's client closed: no arena or spare is kept here any more. + standby: SpinLockIrq, + /// Wakes `SUBMIT` callers waiting for standby reservation headroom. + #[pin] + standby_available: CondVar, + /// The VM's client closed: no arena or surplus spare is kept here any more. closed: AtomicBool, pub(crate) factory: Factory, bind: mmu::VmBind, @@ -163,34 +177,120 @@ impl Cache { live: Arc, ) -> Result> { let budget = super::budget::Budget::new()?; - let spares = KVec::with_capacity(SPARE_EPOCHS, GFP_KERNEL)?; + let epochs = KVec::with_capacity(super::budget::LIMIT as usize, GFP_KERNEL)?; Arc::pin_init( pin_init!(Self { ready <- new_mutex!(Ready::default(), "g16::resources"), - spares <- new_spinlock!(spares, "g16::spare_epochs"), + standby <- new_spinlock_irq!(Standby { epochs, reserved: 0 }, "g16::spare_epochs"), + standby_available <- new_condvar!(), closed: AtomicBool::new(false), factory, bind, live, budget }), GFP_KERNEL, ) } - /// Returns a retired job's never-exposed epoch for the next renders. Any context. - fn give_back(&self, epoch: Arc) { - let mut spares = self.spares.lock(); - // Without room, or once the client closed, the epoch drops: its deferred cleanup - // unmaps it as before. - if !self.closed.load(Ordering::Acquire) { - let _ = spares.push_within_capacity(epoch); + + /// Pops one never-exposed standby epoch for a fresh InitBM publication. + fn take_standby(&self) -> Result> { + let mut standby = self.standby.lock(); + while let Some(epoch) = standby.epochs.pop() { + if epoch.unexposed() { + return Ok(epoch); + } } + Err(EINVAL) } - /// The VM's client closed. Lets go of the arenas and spare epochs: what jobs and the - /// hardware slots' last-owner leases still need, they hold themselves. - pub(crate) fn close(&self) { - let spares = { - let mut spares = self.spares.lock(); - self.closed.store(true, Ordering::Release); - core::mem::take(&mut *spares) + /// Returns a never-exposed epoch whose publication was deferred or failed before visibility. + fn return_standby(&self, epoch: Arc) { + if !epoch.unexposed() { + return; + } + let overflow = { + let mut standby = self.standby.lock(); + let keep = if self.closed.load(Ordering::Acquire) { + standby.reserved as usize + } else { + super::budget::LIMIT as usize + }; + if standby.epochs.len() < keep { + standby.epochs.push_within_capacity(epoch).err().map(|e| e.0) + } else { + Some(epoch) + } }; - drop(spares); + drop(overflow); + } + + /// Releases `count` reserved render credits and trims any surplus standby epochs outside + /// the spinlock (each `PbEpoch` defers its own unmap, so dropping here never sleeps). + fn release_reserved(&self, count: u32) { + if count == 0 { + return; + } + loop { + let excess = { + let mut standby = self.standby.lock(); + standby.reserved = standby.reserved.saturating_sub(count); + let keep = if self.closed.load(Ordering::Acquire) { + standby.reserved as usize + } else { + (standby.reserved as usize).max(SPARE_EPOCHS) + }; + if standby.epochs.len() > keep { + standby.epochs.pop() + } else { + None + } + }; + if excess.is_none() { + break; + } + drop(excess); + // Subsequent iterations only trim remaining surplus; count was already subtracted. + loop { + let more = { + let mut standby = self.standby.lock(); + let keep = if self.closed.load(Ordering::Acquire) { + standby.reserved as usize + } else { + (standby.reserved as usize).max(SPARE_EPOCHS) + }; + if standby.epochs.len() > keep { + standby.epochs.pop() + } else { + None + } + }; + if more.is_none() { + break; + } + drop(more); + } + break; + } + self.standby_available.notify_all(); + } + + /// The VM's client closed. Lets go of the arenas and surplus standby epochs: accepted + /// renders keep only the exact standby count they reserved until they finish, and hardware + /// slots hold their own last-owner leases. + pub(crate) fn close(&self) { + self.closed.store(true, Ordering::Release); + loop { + let excess = { + let mut standby = self.standby.lock(); + let keep = standby.reserved as usize; + if standby.epochs.len() > keep { + standby.epochs.pop() + } else { + None + } + }; + if excess.is_none() { + break; + } + drop(excess); + } + self.standby_available.notify_all(); let ready = { let mut ready = self.ready.lock(); ( @@ -212,14 +312,16 @@ impl Cache { .filter(|c| matches!(c, Command::Compute(_))) .count(); let compute = computes != 0; - let render_count = commands + let render_count: u32 = commands .iter() .filter(|c| matches!(c, Command::Render(_))) - .count(); + .count() + .try_into()?; let render = render_count != 0; - let mut epochs = super::budget::Budget::reserve(&self.budget, render_count.try_into()?)?; let (compute, compute_ext, render) = { // Never held by publication, completion, recovery or fence signalling. + // Serializing standby top-up under `ready` prevents concurrent SUBMITs on the + // same VM from over-allocating or racing each other's deficit calculation. let mut ready = self.ready.lock(); if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { return Err(EIO); @@ -266,8 +368,86 @@ impl Cache { &self.live, )?); } + if render { + if render_count > super::budget::LIMIT { + return Err(E2BIG); + } + let mut remaining = kernel::time::msecs_to_jiffies(10_000); + loop { + let deficit = { + let mut standby = self.standby.lock(); + if vm.status.get() != 0 + || vm.vm.is_closed() + || self.closed.load(Ordering::Acquire) + { + return Err(EIO); + } + if let Some(needed) = standby + .reserved + .checked_add(render_count) + .filter(|&n| n <= super::budget::LIMIT) + { + if standby.epochs.len() >= needed as usize { + standby.reserved = needed; + break; + } + needed - standby.epochs.len() as u32 + } else { + match self + .standby_available + .wait_interruptible_timeout(&mut standby, remaining) + { + CondVarTimeoutResult::Woken { jiffies } => { + remaining = jiffies; + continue; + } + CondVarTimeoutResult::Signal { .. } => return Err(ERESTARTSYS), + CondVarTimeoutResult::Timeout => { + if vm.status.get() != 0 + || vm.vm.is_closed() + || self.closed.load(Ordering::Acquire) + { + return Err(EIO); + } + let needed = standby + .reserved + .checked_add(render_count) + .filter(|&n| n <= super::budget::LIMIT) + .ok_or(EBUSY)?; + if standby.epochs.len() >= needed as usize { + standby.reserved = needed; + break; + } + needed - standby.epochs.len() as u32 + } + } + } + }; + let mut epochs = super::budget::Budget::reserve(&self.budget, deficit)?; + let mut fresh = KVec::with_capacity(deficit as usize, GFP_KERNEL)?; + for _ in 0..deficit { + fresh.push(PbEpoch::new(&self.factory, vm, epochs.take()?)?, GFP_KERNEL)?; + } + let mut overflow = KVec::with_capacity(fresh.len(), GFP_KERNEL)?; + { + let mut standby = self.standby.lock(); + let closed = self.closed.load(Ordering::Acquire); + for epoch in fresh { + if closed { + let _ = overflow.push_within_capacity(epoch); + } else if let Err(err) = standby.epochs.push_within_capacity(epoch) { + let _ = overflow.push_within_capacity(err.0); + } + } + } + drop(overflow); + } + } // A concurrent fault retains even newly constructed backing in this VM cache. if vm.status.get() != 0 || vm.vm.is_closed() { + if render { + self.release_reserved(render_count); + } return Err(EIO); } ( @@ -276,32 +456,12 @@ impl Cache { if render { ready.render.clone() } else { None }, ) }; - let mut pb = KVec::with_capacity(commands.len(), GFP_KERNEL)?; - for command in commands { - pb.push( - if matches!(command, Command::Render(_)) { - // A spare keeps the budget permit it was created with; the reservation - // returns the unused credit when it drops. - let spare = self.spares.lock().pop(); - Some(match spare { - Some(epoch) if epoch.unexposed() => epoch, - _ => PbEpoch::new(&self.factory, vm, epochs.take()?)?, - }) - } else { - None - }, - GFP_KERNEL, - )?; - } - if vm.status.get() != 0 || vm.vm.is_closed() { - return Err(EIO); - } Ok(Prepared { compute, compute_ext, render, - pb, - cache: Some(self.clone()), + unpublished_renders: AtomicU32::new(render_count), + cache: render.is_some().then(|| self.clone()), }) } } @@ -312,8 +472,9 @@ pub(crate) struct Prepared { /// The VM's extension compute units when the job was prepared. pub(crate) compute_ext: Option>, pub(crate) render: Option>, - pb: KVec>>, - /// The VM cache that unused epochs return to. + /// Render commands of this job whose standby reservation has not yet been committed. + unpublished_renders: AtomicU32, + /// The VM cache holding the standby PB epoch pool. cache: Option>, } @@ -322,11 +483,8 @@ impl Drop for Prepared { let Some(cache) = self.cache.take() else { return; }; - for epoch in self.pb.iter_mut().filter_map(Option::take) { - if epoch.unexposed() { - cache.give_back(epoch); - } - } + let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); + cache.release_reserved(remaining); } } impl Prepared { @@ -366,7 +524,24 @@ impl Prepared { pub(crate) fn render(&self) -> Result<&RenderArena> { self.render.as_deref().ok_or(EINVAL) } - pub(crate) fn pb(&self, index: usize) -> Result<&Arc> { - self.pb.get(index).and_then(Option::as_ref).ok_or(EINVAL) + pub(crate) fn take_pb(&self) -> Result> { + self.cache.as_ref().ok_or(EINVAL)?.take_standby() + } + pub(crate) fn return_pb(&self, epoch: Arc) { + if let Some(cache) = &self.cache { + cache.return_standby(epoch); + } + } + /// Commits one render command's standby reservation once it reaches firmware visibility. + pub(crate) fn commit_render(&self) { + if let Some(cache) = &self.cache { + if self + .unpublished_renders + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) + .is_ok() + { + cache.release_reserved(1); + } + } } } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 01e6176bdea5e..be56ee126d4b9 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -410,6 +410,58 @@ def module(text, name): assert_eq!(sync::Arc::strong_count(&a),2); } + #[test]fn standby_pool_reuses_epochs_at_depth_16_and_drains_on_close(){ + // Models Cache's Standby invariant: epochs.len() >= reserved while open or draining. + let one=vm(1);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mut epochs:Vec>=Vec::new(); + let mut reserved:u32=0; + let mut allocs:u32=0; + let prepare=|n:u32,epochs:&mut Vec>,reserved:&mut u32,allocs:&mut u32|{ + let deficit=reserved.checked_add(n).unwrap().saturating_sub(epochs.len() as u32); + if deficit!=0 { + let mut res=g16::budget::Budget::reserve(&budget,deficit).unwrap(); + for _ in 0..deficit { + epochs.push(g16::pools::PbEpoch::new(&factory,&one,res.take().unwrap()).unwrap()); + *allocs+=1; + } + } + *reserved+=n; + assert!(epochs.len()>=*reserved as usize); + }; + // Ramp to depth 16: allocates 16 standby epochs once. + for _ in 0..16 { prepare(1,&mut epochs,&mut reserved,&mut allocs); } + assert_eq!((allocs,epochs.len(),reserved),(16,16,16)); + // Steady-state d=16 with PB reuse: 64 more submits allocate zero new epochs. + for _ in 0..64 { + reserved-=1; // previous render committed with reused PB + prepare(1,&mut epochs,&mut reserved,&mut allocs); + } + assert_eq!((allocs,epochs.len(),reserved),(16,16,16)); + // One fresh InitBM consumes 1 standby epoch and commits 1 reservation; next submit refills 1. + let fresh=epochs.pop().unwrap(); + assert!(fresh.unexposed()); + fresh.prepare(0,0x70c0000000,2048).unwrap(); + fresh.expose(); + reserved-=1; + assert_eq!((epochs.len(),reserved),(15,15)); + prepare(1,&mut epochs,&mut reserved,&mut allocs); + assert_eq!((allocs,epochs.len(),reserved),(17,16,16)); + // Unpublished rollback returns the unexposed epoch without losing capacity. + let rolled=epochs.pop().unwrap(); + assert!(rolled.unexposed()); + epochs.push(rolled); + assert_eq!(epochs.len(),16); + // Closing trims surplus immediately while preserving reserved epochs until jobs finish. + reserved=2; + epochs.truncate(reserved as usize); + assert_eq!(epochs.len(),2); + reserved=0; + epochs.truncate(reserved as usize); + assert!(epochs.is_empty()); + drop(fresh); + assert_eq!(sync::Arc::strong_count(&one),1); + } + } ''' budget=(production/'budget.rs').read_text() From a8444b4edc176f8258d1f3f363d34117b0014f5a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:46:15 -0500 Subject: [PATCH 10/19] drm/asahi: g16: skip redundant same-VM WC scrubs and use word-width WC reads Previously every compute dispatch zeroed 288.8 KiB of write-combined memory (256 KiB context_store, 16 KiB aux, 16 KiB preempt, unused seq, and 16 B its) and read back the 160-byte UMA descriptor byte by byte with read_volatile(). Every render pass zeroed ~530 KiB to >1 MiB of WC memory (including dead-code ta_scratch/fs_scratch, work/seq images immediately overwritten by prefix_render(), aux, scene_user, full 48 KiB preemption buffers, and tpc_dirty) synchronously under Shared::state. Track per-slot full-scrub necessity in Slots: - First use, cross-VM switch, cancelled preparation, affected error receipts, and firmware recovery (invalidate_scrub) perform the full scrub so no client or faulted state can ever leak. - Clean same-VM compute reuse zeroes only the 16-byte internal timestamp pair (its). - Clean same-VM render reuse zeroes only its (32 B), active heap header (4 KiB), tilemap_dirty, and active preemption record headers (2 KiB), preserving the tpc_dirty high-water mark until the next full scrub. - Upgrade FwObject::read() to 64-bit volatile word loads for aligned spans, reducing compute descriptor WC bus reads by 8x. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 5 +- drivers/gpu/drm/asahi/g16/object.rs | 18 ++- drivers/gpu/drm/asahi/g16/poll.rs | 1 + drivers/gpu/drm/asahi/g16/recovery.rs | 4 +- drivers/gpu/drm/asahi/g16/slots.rs | 111 ++++++++++++++++-- .../drivers/gpu/asahi-m4/test-resources.py | 75 ++++++++++++ 6 files changed, 199 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 75caf7a98ecd3..06d435e764602 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1350,7 +1350,7 @@ impl Firmware { let target = encode::stamp(n); let index = self .slots - .claim_compute(&job.resources, &mut f.claims, 0)? + .claim_compute_for(&job.resources, &mut f.claims, Some(job.vm.id))? .ok_or(EAGAIN)?; let generation = job.vm.generation; self.slots.hold_vm(&f.claims, &job.vm)?; @@ -1449,7 +1449,8 @@ impl Firmware { let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); // Claim performs only a qualified per-use scrub, never allocator/list reset. - self.slots.claim_pass(job.resources.render()?, k)?; + self.slots + .claim_pass_for(job.resources.render()?, k, Some(job.vm.id))?; self.slots.hold_vm(&f.claims, &job.vm)?; self.slots.hold_arenas(&f.claims, &job.resources); let (refs, init_buffer, epoch, binding) = self.render_refs(k, job, draw)?; diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 24b8dd2de3fb0..767df69e03f3e 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -214,9 +214,23 @@ impl FwObject { pub(crate) fn read(&self, offset: usize, out: &mut [u8]) -> Result { let p = self.ptr(offset, out.len())?; rmb(); - for (index, byte) in out.iter_mut().enumerate() { + let mut index = 0; + let len = out.len(); + while index < len && (p as usize + index) % 8 != 0 { // SAFETY: ptr() bounds the complete range; WC memory permits byte accesses. - *byte = unsafe { p.add(index).read_volatile() }; + out[index] = unsafe { p.add(index).read_volatile() }; + index += 1; + } + while index + 8 <= len { + // SAFETY: ptr() bounds the range and `p.add(index)` is 8-byte aligned. + let word = unsafe { p.add(index).cast::().read_volatile() }; + out[index..index + 8].copy_from_slice(&word.to_ne_bytes()); + index += 8; + } + while index < len { + // SAFETY: ptr() bounds the complete range; WC memory permits byte accesses. + out[index] = unsafe { p.add(index).read_volatile() }; + index += 1; } rmb(); Ok(()) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index d9dabde95472b..bf036bc95f14d 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -601,6 +601,7 @@ impl Firmware { return; } if result.is_err() { + self.slots.mark_dirty(×tamp_claims); self.recovery.affected_full_receipts = self.recovery.affected_full_receipts.saturating_add(1); } diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 70e250a3b8ef7..15f86bd2b5b99 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -424,10 +424,12 @@ impl Firmware { u32::MAX }; // Firmware is now halted in phase 1: invalidate bound PB state and - // capture stage frontiers and fault-bank state before answering 2 + // force a full scrub on the next claim of every compute and render slot, + // then capture stage frontiers and fault-bank state before answering 2 // (firmware may force stage targets while aborting work, and fault_scan // writes the fault-bank selector so it must not run against active FW). self.pools.invalidate(); + self.slots.invalidate_scrub(); self.events.grow.clear(); let stage = self.recovery_snapshot()?; // Powered down, the GPU holds no fault to read. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index f04d6add674f8..b345b944197c5 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -105,9 +105,17 @@ impl ComputeSlot { )?; Ok(unit) } - /// Only command-local scratch is reset. Pool/list/counter/descriptor state is preserved. - fn scrub(&self) -> Result { + /// Resets command-local state before reuse. Pool/list/counter/descriptor state is preserved. + /// + /// Clean same-VM reuse only zeroes the 16-byte internal timestamp pair so retirement + /// checks cannot observe stale ticks; `work` (including its embedded sequence) is + /// overwritten completely by `prefix_compute`. First use, cross-VM retarget, cancelled + /// preparation, or post-recovery/error reuse runs the full scrub of all scratch areas. + fn scrub(&self, full: bool) -> Result { self.its.fill(0, 0, 16)?; + if !full { + return Ok(()); + } self.seq.fill(0, 0, 0x300)?; self.aux.fill(0, 0, 0x4000)?; self.context_store.fill(0, 0, 0x40000)?; @@ -253,18 +261,36 @@ impl PassSlot { }) } - /// Per-use reset of a pass slot's storage: work images, microsequences, scratch, stage - /// stamps, the TPC/tilemap spans its last use wrote, auxiliary, heap metadata and - /// scene-user and the preemption save areas. The slot is neither - /// published nor claimed; the dirty spans are passed in. + /// Per-use reset of a pass slot's storage. The slot is neither published nor claimed; the + /// dirty spans are passed in. + /// + /// Clean same-VM reuse skips the work/sequence images (immediately overwritten by + /// `prefix_render`), unused scratch objects (`ta_scratch`, `fs_scratch`), bulk scratch + /// (`aux`, `scene_user`), and `tpc` (overwritten by TA hardware), zeroing only the stage + /// timestamp cells, active `heap` header (`0x1000`), `tilemap_dirty`, and active + /// preemption record headers. First use, cross-VM switch, cancelled preparation, or + /// post-recovery/error reuse runs the full scrub including `tpc_dirty`. fn scrub( &self, pre_records: u32, tpc_dirty: u64, tilemap_dirty: u64, + full: bool, stats: &mut SlotStats, ) -> Result { - let _ = pre_records; + let r = pre_records as usize; + + if !full { + self.its.fill(0, 0, 32)?; + self.tilemap.fill(0, 0, tilemap_dirty as usize)?; + stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_dirty); + self.heap.fill(0, 0, 0x1000)?; + self.pre[0].fill(0, 0, r * 0x540)?; + self.pre[1].fill(0, 0, r * 0x280)?; + self.pre[2].fill(0, 0, r * 0x40)?; + stats.pass_scrubs = stats.pass_scrubs.saturating_add(1); + return Ok(()); + } self.ta_work.fill(0, 0, ta::WORK_SIZE)?; self.fs_work.fill(0, 0, fs::WORK_SIZE)?; @@ -280,7 +306,7 @@ impl PassSlot { self.aux.fill(0, 0, 0x20000)?; self.heap.fill(0, 0, 0x4000)?; self.scene_user.fill(0, 0, 0x10000)?; - // Preemption save areas start zeroed on every use. + // Preemption save areas start zeroed on every full reset. self.pre[0].fill(0, 0, 0x4000)?; self.pre[1].fill(0, 0, 0x4000)?; self.pre[2].fill(0, 0, 0x4000)?; @@ -381,6 +407,8 @@ pub(crate) struct ComputeOwners { /// descriptor when a later owner displaces it, after its VM's client closed. arena: [Option>; sizes::COMPUTE_UNITS], pending_arena: [Option>; sizes::COMPUTE_UNITS], + /// Force a full scrub on next claim (first use, cancel, error, or firmware recovery). + scrub_full: [bool; sizes::COMPUTE_UNITS], } pub(crate) struct Slots { @@ -400,6 +428,8 @@ pub(crate) struct Slots { /// The render arena of each pass slot's owner (see [`ComputeOwners::arena`]). pass_arena: [Option>; 2], pending_pass_arena: [Option>; 2], + /// Force a full scrub on next pass claim (first use, cancel, error, or firmware recovery). + pass_scrub_full: [bool; 2], } impl Slots { pub(crate) fn new() -> Result { @@ -416,6 +446,7 @@ impl Slots { pending_owner: [const { None }; sizes::COMPUTE_UNITS], arena: [const { None }; sizes::COMPUTE_UNITS], pending_arena: [const { None }; sizes::COMPUTE_UNITS], + scrub_full: [true; sizes::COMPUTE_UNITS], }, GFP_KERNEL, )?, @@ -425,6 +456,7 @@ impl Slots { pending_pass_owner: [None, None], pass_arena: [None, None], pending_pass_arena: [None, None], + pass_scrub_full: [true; 2], }) } pub(crate) fn init(&self) -> Result { @@ -474,11 +506,43 @@ impl Slots { .filter(|&k| self.compute.lifetime.available(k)) .count() as u32 } + /// Forces a full scrub on the next claim of every slot (after firmware recovery). + #[allow(dead_code)] + pub(crate) fn invalidate_scrub(&mut self) { + self.compute.scrub_full = [true; sizes::COMPUTE_UNITS]; + self.pass_scrub_full = [true; 2]; + } + + /// Forces a full scrub on the next claim of the units in `f` (after an affected error). + #[allow(dead_code)] + pub(crate) fn mark_dirty(&mut self, f: &Claims) { + for &k in &f.slot[..(f.slot_count as usize).min(f.slot.len())] { + if let Some(dirty) = self.compute.scrub_full.get_mut(k as usize) { + *dirty = true; + } + } + for k in 0..2 { + if f.pass_mask & (1 << k) != 0 { + self.pass_scrub_full[k] = true; + } + } + } + + #[allow(dead_code)] pub(crate) fn claim_compute( &mut self, units: &super::resources::Prepared, f: &mut Claims, _j: u32, + ) -> Result> { + self.claim_compute_for(units, f, None) + } + + pub(crate) fn claim_compute_for( + &mut self, + units: &super::resources::Prepared, + f: &mut Claims, + vm_id: Option, ) -> Result> { if f.slot_count != 0 { return Ok(None); @@ -489,7 +553,13 @@ impl Slots { for i in 0..n { let k = (self.cursor as usize + i) % n; if self.compute.lifetime.claim(k) { - if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub()) { + let full = self.compute.scrub_full[k] + || vm_id.is_none_or(|id| { + self.compute.owner[k] + .as_ref() + .is_none_or(|prev| prev.id != id) + }); + if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub(full)) { self.compute.lifetime.cancel(k); return Err(e); } @@ -520,22 +590,37 @@ impl Slots { } None } + #[allow(dead_code)] pub(crate) fn claim_pass(&mut self, arena: &super::resources::RenderArena, k: usize) -> Result { + self.claim_pass_for(arena, k, None) + } + + pub(crate) fn claim_pass_for( + &mut self, + arena: &super::resources::RenderArena, + k: usize, + vm_id: Option, + ) -> Result { if k >= 2 || !self.pass_lifetime.claim(k) { return Err(EBUSY); } // Only a retired displaced owner may reach here; no in-flight storage is reset. + let full = self.pass_scrub_full[k] + || vm_id.is_none_or(|id| self.pass_owner[k].as_ref().is_none_or(|prev| prev.id != id)); let p = &arena.passes[k]; if let Err(e) = p.scrub( 1, arena.tpc_dirty[k].load(Ordering::Relaxed), arena.tilemap_dirty[k].load(Ordering::Relaxed), + full, &mut self.stats, ) { self.pass_lifetime.cancel(k); return Err(e); } - arena.tpc_dirty[k].store(0, Ordering::Relaxed); + if full { + arena.tpc_dirty[k].store(0, Ordering::Relaxed); + } arena.tilemap_dirty[k].store(0, Ordering::Relaxed); self.pass_cursor = (1 - k) as u32; Ok(()) @@ -663,11 +748,13 @@ impl Slots { for &k in &f.slot[..f.slot_count as usize] { self.compute.owner[k as usize] = self.compute.pending_owner[k as usize].take(); self.compute.arena[k as usize] = self.compute.pending_arena[k as usize].take(); + self.compute.scrub_full[k as usize] = false; } for k in 0..2 { if f.pass_mask & (1 << k) != 0 { self.pass_owner[k] = self.pending_pass_owner[k].take(); self.pass_arena[k] = self.pending_pass_arena[k].take(); + self.pass_scrub_full[k] = false; } } self.pass_busy &= !f.pass_mask; @@ -680,11 +767,13 @@ impl Slots { for &k in &f.slot[..f.slot_count as usize] { self.compute.lifetime.quarantine(k as usize); self.compute.pending_retarget[k as usize] = None; + self.compute.scrub_full[k as usize] = true; } for k in 0..2 { if f.pass_mask & (1 << k) != 0 { self.pass_lifetime.quarantine(k); self.pending_pass_retarget[k] = None; + self.pass_scrub_full[k] = true; } } self.pass_busy &= !f.pass_mask; @@ -699,6 +788,7 @@ impl Slots { self.compute.pending_retarget[k as usize] = None; self.compute.pending_owner[k as usize] = None; self.compute.pending_arena[k as usize] = None; + self.compute.scrub_full[k as usize] = true; } for k in 0..2 { if f.pass_mask & (1 << k) != 0 { @@ -706,6 +796,7 @@ impl Slots { self.pending_pass_retarget[k] = None; self.pending_pass_owner[k] = None; self.pending_pass_arena[k] = None; + self.pass_scrub_full[k] = true; } } self.pass_busy &= !f.pass_mask; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index be56ee126d4b9..12f9d498866c9 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -462,6 +462,81 @@ def module(text, name): assert_eq!(sync::Arc::strong_count(&one),1); } + #[test]fn compute_same_vm_reuse_skips_bulk_scrub_and_cross_vm_or_recovery_full_scrubs(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let a=vm(1);let b=vm(2);let mut c=Claims::new(); + // First use of units 0 and 1 runs full scrub (context_store + aux + preempt + seq + its). + for _ in 0..2 { + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(arena.compute.compute[k].context_store.fills.lock().unwrap().len(),1); + assert_eq!(arena.compute.compute[k].its.fills.lock().unwrap().len(),1); + s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + } + // Same-VM clean reuse of unit 0 clears ONLY its (16 B), skipping context_store/aux/preempt/seq. + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert_eq!(arena.compute.compute[0].its.fills.lock().unwrap().len(),2); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),1); + assert_eq!(arena.compute.compute[0].preempt.fills.lock().unwrap().len(),1); + assert_eq!(arena.compute.compute[0].aux.fills.lock().unwrap().len(),1); + s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + // Cross-VM switch on unit 1 runs full scrub. + let k=s.claim_compute_for(&arena.compute,&mut c,Some(b.id)).unwrap().unwrap(); + assert_eq!(k,1); + assert_eq!(arena.compute.compute[1].context_store.fills.lock().unwrap().len(),2); + assert_eq!(arena.compute.compute[1].preempt.fills.lock().unwrap().len(),2); + s.hold_vm(&c,&b).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + // Firmware recovery forces full scrub even for same VM. + s.invalidate_scrub(); + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),2); + // Cancelled preparation forces full scrub on next claim. + s.release(&mut c); + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),3); + s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + } + + #[test]fn pass_same_vm_reuse_skips_bulk_scrub_and_preserves_tpc_dirty_for_full_scrub(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let a=vm(1);let b=vm(2); + let retire=|s:&mut Slots,k:usize,owner:&sync::Arc|{ + let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1< Date: Sat, 21 Nov 2026 16:46:17 -0500 Subject: [PATCH 11/19] drm/asahi: g16: pipeline timed compute commands and expand compute unit ring can_queue_behind() previously refused to pipeline behind any in-flight compute command carrying timestamp_outputs, forcing depth-4+ timed compute workloads down to depth-1 serialization. Each compute flight already owns its own private ComputeSlot (its/work), and retire_oldest() publishes timestamps in FIFO publication order before signalling the flight's fence, so timed same-VM compute commands can pipeline freely. Expand hw::sizes::COMPUTE_UNITS and params::compute_units() from 8/6 to 16 (placing extension units at 0x7080000000..0x70b8000000, clear of the 0x7040000000..0x7080000000 dynamic PB page-list aperture and below PB_HEAP at 0x70c0000000, using hardware UMA slots 1..=16). With displacement lifetime tracking, 16 units sustain up to 15 in-flight compute commands per bursting VM instead of 5. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 20 ++------- drivers/gpu/drm/asahi/g16/hw.rs | 10 ++--- drivers/gpu/drm/asahi/g16/params.rs | 2 +- .../drivers/gpu/asahi-m4/test-publication.py | 45 +++++++++++++++++++ 4 files changed, 55 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 06d435e764602..975a977463899 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -936,6 +936,10 @@ impl Firmware { /// [`params::compute_flights`]. Renders, another VM's commands and every failure path /// need an empty engine: under several clients, compute queued behind another VM's /// lost its writes and stalled the firmware compute queue. + /// + /// Timed compute commands pipeline freely: each flight owns a private `ComputeSlot` + /// (`its`/`work`) and `retire_oldest` publishes timestamps in FIFO publication order + /// before signalling the flight's fence. fn can_queue_behind(&self, job: &Arc) -> bool { let e = &self.engine; if e.flights.len() >= params::compute_flights() @@ -944,7 +948,6 @@ impl Firmware { || f.doomed || f.recovery_suspect || !Arc::ptr_eq(&f.job.vm, &job.vm) - || Self::writes_timestamps(f) }) || job.vm.status.get() != 0 || self.slots.compute_exhausted() @@ -961,21 +964,6 @@ impl Firmware { && job.check_command_dependencies(sent).is_ok() } - /// Whether a flight's commands have user timestamps. The host writes them when the - /// command retires, so a command queued behind it (a query copy, possibly waiting on - /// availability) could run before they exist; it waits for the retirement instead. - fn writes_timestamps(f: &Flight) -> bool { - f.job - .commands - .get(f.first..f.first + f.count) - .is_none_or(|commands| { - commands.iter().any(|command| match command { - Command::Compute(c) => !c.timestamp_outputs.is_empty(), - Command::Render(r) => !r.timestamp_outputs.is_empty(), - }) - }) - } - /// Whether some of `job`'s commands were published: such a job is retained after a /// fail-stop. pub(crate) fn job_partly_published(&self, job: &Job) -> bool { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 4c30ad932be62..c840f3c7d92f9 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -573,14 +573,14 @@ pub(crate) mod client { // Persistent compute units, each in its own 64 MiB interval and reused across // application queues. Units 0 and 1 keep their original placement below the render - // allocators; further units (up to [`super::sizes::COMPUTE_UNITS`]) live between the - // unused CT window and the PB heap, clear of the dynamic PB page-list range - // 0x7040000000..0x7080000000. Every alias is inside Mesa's reserved driver hole. + // allocators; further units (up to [`super::sizes::COMPUTE_UNITS`]) live from + // 0x7080000000 up to the PB heap (0x70c0000000), clear of the dynamic PB page-list + // range 0x7040000000..0x7080000000. Every alias is inside Mesa's reserved driver hole. pub(crate) const fn compute_base(k: u64) -> u64 { if k < 2 { 0x7001000000 + k * 0x04000000 } else { - 0x7090000000 + (k - 2) * 0x04000000 + 0x7080000000 + (k - 2) * 0x04000000 } } pub(crate) const fn compute_pool(k: u64) -> u64 { @@ -683,7 +683,7 @@ pub(crate) mod sizes { /// Retained compute units per VM at most; each unit owns its own hardware UMA slot /// (`COMPUTE_UMA_SLOT + index`). A unit is reused only after a later publication retired /// (it displaced the unit), so `n` units keep up to `n - 1` compute commands in flight. - pub(crate) const COMPUTE_UNITS: usize = 8; + pub(crate) const COMPUTE_UNITS: usize = 16; const _: () = assert!(super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP); /// Inherited diagnostic histogram width; M4 does not fold jobs into a compute horizon. pub(crate) const HORIZON_JOBS: u32 = 1; diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index bcf52a272ca92..9e9389f497315 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -40,7 +40,7 @@ pub(crate) fn pb_posted_blocks(heap_blocks: u32) -> u32 { /// Compute units of a VM that submits compute back to back. pub(crate) fn compute_units() -> usize { - 6usize.clamp(2, hw::sizes::COMPUTE_UNITS) + 16usize.clamp(2, hw::sizes::COMPUTE_UNITS) } /// Compute commands in flight at most. diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index d59521d36719b..c9b23923cebf6 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -237,6 +237,50 @@ def item(declaration): } } +struct QueueBehindJob{id:u32,vm:Arc,progress:Progress,commands:Vec,dependency:Result,resources:Resources} +impl QueueBehindJob{fn check_command_dependencies(&self,_index:u32)->Result{self.dependency}} +struct QueueBehindFlight{job:Arc,renders:u32,doomed:bool,recovery_suspect:bool} +struct QueueBehindEngine{ordinal:u64,flights:Vec} +struct QueueBehindSlots{exhausted:bool,available:bool} +impl QueueBehindSlots{fn compute_exhausted(&self)->bool{self.exhausted}fn compute_available(&self,_n:usize)->bool{self.available}} +struct QueueBehindHost{engine:QueueBehindEngine,slots:QueueBehindSlots} +mod queue_behind_scope { + use super::*; + type Job = QueueBehindJob; + fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} + mod params { pub fn compute_flights()->usize{16} } + impl QueueBehindHost { + __CAN_QUEUE_BEHIND__ + } + #[test]fn timed_compute_queues_behind_same_vm_and_blocks_cross_vm_or_render(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:2}); + let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ + id,vm,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(())}], + dependency:Ok(()),resources:Resources, + }); + let j1=mk(1,vm1.clone(),false); + let j2=mk(2,vm1.clone(),false); + let j_other_vm=mk(3,vm2.clone(),false); + let j_render=mk(4,vm1.clone(),true); + let mut p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,flights:vec![QueueBehindFlight{job:j1,renders:0,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{exhausted:false,available:true}, + }; + assert!(p.can_queue_behind(&j2)); + assert!(!p.can_queue_behind(&j_other_vm)); + assert!(!p.can_queue_behind(&j_render)); + p.engine.flights[0].doomed=true; + assert!(!p.can_queue_behind(&j2)); + p.engine.flights[0].doomed=false; + p.engine.flights[0].renders=1; + assert!(!p.can_queue_behind(&j2)); + p.engine.flights[0].renders=0; + p.slots.available=false; + assert!(!p.can_queue_behind(&j2)); + } +} ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) for token, declaration in { @@ -248,6 +292,7 @@ def item(declaration): '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', + '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', }.items(): harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::")) unit = output / 'publication.rs' From 8a125d5cbfe340b427f4bdf2ba2690eca30d9df7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:47:16 -0500 Subject: [PATCH 12/19] drm/asahi: g16: inline ready submit, pin completion worker, and tighten poll cadence Eliminate four layers of host-side latency on the G16 submit/completion round trip while preserving sleep-transition safety: 1. Direct inline submit from SUBMIT ioctl: when the previous job on the logical queue has already started, all input fences are signalled, and Shared::state is uncontended (try_lock), Scheduler::push() publishes immediately on the submitting CPU before pushing to drm_sched (whose subsequent run() observes started == true as a no-op while preserving credits, fence ownership, and QUEUE_DESTROY drain semantics). Contended or dependency-blocked jobs fall back to drm_sched in strict queue order. 2. Submitter-pinned dedicated completion worker: replace WORK_CPU_UNBOUND on system_highpri_wq for EP 0x20 / hrtimer wakeups with a per-CPU high-priority reclaim OwnedQueue (aurora_g16_events) enqueued on the last submitting CPU, keeping WC receipt reads and fence wakeups hot on the submitting core; join cleanly in sleep::join_workers(). 3. Tighten post-event retirement tail: extend post-EP-0x20 trailing 5 us polls from 4 (20 us) to 10 (50 us) to absorb firmware's WC receipt tail without falling into a 100 us resnap hrtimer sleep, and rearm at repoll_us (15 us) if an evented flight is still settling. 4. Split fast completion drain from 1 ms housekeeping and stop hrtimer / delayed-work thrash: throttle power-governor updates, host-window health checks, full Session::check(), and administrative hang checks to 1 ms cadence while keeping transport checks, ring drains, and recovery/fault checks immediate; avoid cancelling/reprogramming the hrtimer or re-arming the 1-jiffy backup when a sufficient timer is already armed. Guard run_poll(), submit_locked(), and try_submit_inline() with lock-held sleeping.load(Ordering::Acquire) checks so suspend never races inline or polled publication. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 3 + drivers/gpu/drm/asahi/g16/job.rs | 49 ++++- drivers/gpu/drm/asahi/g16/mod.rs | 55 ++++- drivers/gpu/drm/asahi/g16/poll.rs | 189 +++++++++++++----- drivers/gpu/drm/asahi/g16/sleep.rs | 3 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 39 +++- 6 files changed, 281 insertions(+), 57 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 975a977463899..c96d68cffc52b 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -423,6 +423,8 @@ pub(crate) struct Engine { pub(crate) ta_registered: bool, /// A ready prefix waits only for a record's consumption: repoll sooner. pub(crate) chan_wait: bool, + /// An EP 0x20 event arrived with a flight still settling its final receipt: repoll sooner. + pub(crate) short_repoll: bool, /// Progress tracking of the oldest prefix. pub(crate) progress_flight: u64, pub(crate) progress: [Option; 3], @@ -460,6 +462,7 @@ impl Engine { render_registered: false, ta_registered: false, chan_wait: false, + short_repoll: false, progress_flight: 0, progress: [None; 3], stats: KBox::new(Stats::default(), GFP_KERNEL)?, diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index d79d5892d31f4..15740f7d5ee9c 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -232,10 +232,45 @@ impl Job { self.fence.signal(result); } + /// Whether this job has already been handed to the engine (inline or by drm_sched). + pub(crate) fn is_started(&self) -> bool { + self.started.load(Ordering::Acquire) + } + + /// Attempts to submit a ready job directly from SUBMIT ioctl context without waiting for + /// the drm_sched worker wakeup. Only runs when all input fences are already signalled, + /// the device and VM are healthy, and `Shared::state` is uncontended (`try_lock`); on + /// contention or pending dependencies it returns without setting `started` so drm_sched + /// runs the job in queue order. + pub(crate) fn try_start_inline(self: &Arc, shared: &Arc) { + if shared.crashed.load(Ordering::Acquire) + || shared.sleeping.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { + return; + } + if let Some(order) = self.orders.first() { + if self.queue.check(order).is_err() { + return; + } + } + if super::fence::check_dependencies(&self.inputs).is_err() { + return; + } + if let Some(result) = shared.try_submit_inline(self.clone()) { + self.started.store(true, Ordering::Release); + if let Err(error) = result { + self.finish(Err(if error == ENODEV { EIO } else { error }), false); + } + } + } + /// Hands the job to the engine, or refuses a failed GPU or VM. A queued /// job may have been accepted before another command made its VM sticky. fn start(self: &Arc, shared: &Arc) { - self.started.store(true, Ordering::Release); + if self.started.swap(true, Ordering::AcqRel) { + return; + } if shared.crashed.load(Ordering::Acquire) { self.finish(Err(EIO), false); return; @@ -474,6 +509,9 @@ pub(crate) struct Scheduler { // drains), and only then the scheduler is finalized. entity: sched::Entity, _scheduler: sched::Scheduler, + /// Most recently accepted job of this queue; an inline submit is permitted only once + /// this predecessor has already started so queue-local ordering is strictly preserved. + last_job: Option>, } impl Scheduler { @@ -491,19 +529,26 @@ impl Scheduler { Ok(Self { entity, _scheduler: scheduler, + last_job: None, }) } /// Pushes a job that waits for its retained inputs. On failure the job is cancelled (not counted as /// submitted work of its VM) and the error is returned. pub(crate) fn push(&mut self, job: Arc, shared: Arc) -> Result { + shared.note_submitter(); + let prev_started = self.last_job.as_ref().is_none_or(|prev| prev.is_started()); let handle = job.clone(); - let mut pending = self.entity.new_job(1, SchedJob { job, shared })?; + let mut pending = self.entity.new_job(1, SchedJob { job, shared: shared.clone() })?; for fence in handle.inputs.iter() { pending.add_dependency(fence.clone())?; } let armed = pending.arm(); handle.accepted.store(true, Ordering::Release); + if prev_started { + handle.try_start_inline(&shared); + } + self.last_job = Some(handle); armed.push(); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index b3dbc6bd3c73b..dfef940d5b25a 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -81,12 +81,12 @@ use core::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicU64, use kernel::{ c_str, device::{self, Core}, - impl_has_delayed_work, new_delayed_work, new_mutex, of, platform, + impl_has_delayed_work, impl_has_work, new_delayed_work, new_mutex, new_work, of, platform, prelude::*, sync::{aref::ARef, Arc, Mutex}, time::hrtimer::{ArcHrTimerHandle, HrTimer}, uapi, - workqueue::{DelayedWork, WorkItem}, + workqueue::{DelayedWork, OwnedQueue, Work, WorkItem}, }; use crate::driver::{AsahiDrmDevice, AsahiPlatformDriver}; @@ -187,8 +187,10 @@ impl platform::Driver for Driver { } } -/// Work item ID of the poll work. +/// Work item ID of the backup delayed poll work. const POLL_WORK: u64 = 0; +/// Work item ID of the submitter-pinned fast event poll work. +const FAST_POLL_WORK: u64 = 1; /// Device state shared with the RTKit callbacks and the poll work. #[pin_data] @@ -204,6 +206,12 @@ pub(crate) struct Shared { pub(crate) crashed: AtomicBool, /// Set by the firmware's EP 0x20 event message; consumed by the poll work. pub(crate) evented: AtomicBool, + /// CPU that last submitted work, for placing the per-CPU completion worker. + pub(crate) submitter: AtomicU32, + /// Next armed hrtimer expiry (monotonic ns, 0 when disarmed). + pub(crate) resnap_deadline_ns: AtomicU64, + /// Next 1-jiffy backup delayed-work schedule bound (monotonic ns). + pub(crate) backup_deadline_ns: AtomicU64, // --- RTKit callback state and a retained failed session. --- /// The first latched error, as a negative errno. pub(crate) error: AtomicI32, @@ -222,10 +230,14 @@ pub(crate) struct Shared { sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. sleep_commit: AtomicPtr, + /// Dedicated high-priority per-CPU workqueue for immediate completion polling. + pub(crate) events: OwnedQueue, #[pin] pub(crate) orphan: Mutex>>, #[pin] pub(crate) poll: DelayedWork, + #[pin] + pub(crate) fast_poll: Work, // --- The completion/repoll hrtimer and the handle of its current expiry (dropping it // cancels the expiry; see `Shared::rearm`). --- #[pin] @@ -241,6 +253,10 @@ impl_has_delayed_work! { impl HasDelayedWork for Shared { self.poll } } +impl_has_work! { + impl HasWork for Shared { self.fast_poll } +} + impl WorkItem for Shared { type Pointer = Arc; fn run(this: Arc) { @@ -252,12 +268,32 @@ impl WorkItem for Shared { } } +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + if this.orphaned.load(Ordering::Acquire) { + this.drain_orphan(); + return; + } + this.run_poll(); + } +} + impl Shared { + /// Records the submitting CPU so completion work runs on the same core. + pub(crate) fn note_submitter(&self) { + self.submitter + .store(kernel::cpu::CpuId::current().as_u32(), Ordering::Relaxed); + } + + /// Last recorded submitting CPU, if valid. + pub(crate) fn submitter_cpu(&self) -> Option { + kernel::cpu::CpuId::from_u32(self.submitter.load(Ordering::Relaxed)) + } + /// Queues the poll work immediately. Callable from any context. pub(crate) fn kick(self: &Arc) { self.evented.store(true, Ordering::Release); - // `mod_delayed_work(.., 0)` so that a kick also runs a poll whose 1-jiffy backup is - // pending (a plain enqueue is refused then). self.poll_now(); } @@ -355,6 +391,8 @@ pub(crate) struct Firmware { pub(crate) pools: pools::Pools, /// Live VMs and their exclusive TTBAT slots, and the client aliases of every user VM. pub(crate) vms: Arc, + /// Monotonic timestamp (ns) of the last full housekeeping pass (power, health, hang poll). + pub(crate) last_housekeeping_ns: u64, } /// A G16 GPU. @@ -390,6 +428,7 @@ impl Gpu { // pin_init exposes initialized fields by name, so `dev` is shadowed after // the platform-device field. Retain the typed DRM device before that point. let drm_device: ARef = dev.into(); + let events = OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -398,6 +437,9 @@ impl Gpu { wedged_notified: AtomicBool::new(false), crashed: AtomicBool::new(false), evented: AtomicBool::new(false), + submitter: AtomicU32::new(u32::MAX), + resnap_deadline_ns: AtomicU64::new(0), + backup_deadline_ns: AtomicU64::new(0), error: AtomicI32::new(0), started: AtomicBool::new(false), data, @@ -406,8 +448,10 @@ impl Gpu { sleeping: AtomicBool::new(false), sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), + events, orphan <- new_mutex!(None, "g16::Shared::orphan"), poll <- new_delayed_work!("g16::Shared::poll"), + fast_poll <- new_work!("g16::Shared::fast_poll"), resnap <- HrTimer::new(), resnap_handle <- new_mutex!(None, "g16::Shared::resnap_handle"), state <- new_mutex!(None, "g16::Shared::state"), @@ -527,6 +571,7 @@ impl Firmware { power, pools, vms, + last_housekeeping_ns: 0, }, ); if let Err(e) = firmware.init_graphs() { diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index bf036bc95f14d..72f897fd6b8f1 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -36,9 +36,16 @@ use super::fw::work::compute; use super::job::{self, Completions, Job}; use super::recovery::logic::Retirement; use super::regs::EngineState; -use super::{params, Firmware, Shared, POLL_WORK}; +use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK}; use crate::module_parameters; +/// Cadence of periodic housekeeping (power governor, window health, administrative hang check). +const HOUSEKEEPING_NS: u64 = 1_000_000; +/// Maximum trailing 5 us receipt polls after an EP 0x20 event (50 us covers firmware WC tails). +const EVENT_RETIRE_POLLS: u32 = 10; +/// Minimum interval between 1-jiffy delayed-work safety backup rearms (2 ms). +const BACKUP_REARM_NS: u64 = 2_000_000; + impl_has_hr_timer! { impl HasHrTimer for Shared { mode: RelativeMode, field: self.resnap @@ -51,6 +58,7 @@ impl HrTimerCallback for Shared { /// Runs the poll now. fn run(this: ArcBorrow<'_, Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart { let this: Arc = this.into(); + this.resnap_deadline_ns.store(0, Ordering::Release); this.poll_now(); HrTimerRestart::NoRestart } @@ -76,13 +84,18 @@ impl Shared { let mut done = Completions::new(); { let mut state = self.state.lock(); + if self.sleeping.load(Ordering::Acquire) { + return; + } if let Some(firmware) = state.as_deref_mut() { if firmware.engine.shared.is_none() { firmware.engine.shared = Some(self.clone()); } let evented = self.evented.swap(false, Ordering::AcqRel); match firmware.poll(evented, &mut done) { - Ok(true) => self.rearm(firmware.engine.chan_wait), + Ok(true) => { + self.rearm(firmware.engine.chan_wait || firmware.engine.short_repoll) + } // Idle: one more pass after a window gives the state back. A failed // engine's poll no longer services power, so it has nothing to give back. Ok(false) @@ -91,10 +104,12 @@ impl Shared { { self.mod_poll(kernel::time::msecs_to_jiffies( (super::power::policy::WINDOW_NS / 1_000_000) as u32, - )) + )); + self.cancel_resnap(); } - Ok(false) => {} + Ok(false) => self.cancel_resnap(), Err(error) => { + self.cancel_resnap(); firmware.fail_stop(error, &mut done); self.fail_stop(error); } @@ -106,6 +121,48 @@ impl Shared { self.notify_wedged(); } + fn submit_locked( + self: &Arc, + firmware: &mut Firmware, + job: Arc, + done: &mut Completions, + ) -> Result { + if firmware.engine.shared.is_none() { + firmware.engine.shared = Some(self.clone()); + } + let accepted = firmware.enqueue(job); + // Nothing is published while a render is in flight: the poll pass after its + // retirement publishes this job. Skipping the pass here keeps queued submissions + // from holding the device lock (ring drains, health checks) on that path. + let render_busy = firmware.engine.flights.iter().any(|f| f.renders != 0); + if accepted.is_ok() && !render_busy && !self.sleeping.load(Ordering::Acquire) { + let now = now_ns(); + let full = now.wrapping_sub(firmware.last_housekeeping_ns) >= HOUSEKEEPING_NS + || self.evented.load(Ordering::Acquire) + || firmware.recovery_pending().unwrap_or(true); + let pub_res = if full { + let r = firmware.publish(done); + if r.is_ok() { + firmware.last_housekeeping_ns = now; + } + r + } else { + firmware + .session + .transport() + .and_then(|()| firmware.publish_checked(done)) + }; + if let Err(error) = pub_res { + firmware.fail_stop(error, done); + self.fail_stop(error); + } + if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { + self.rearm(firmware.engine.chan_wait); + } + } + accepted + } + /// Hands a job to the engine and publishes what can be published. Err: the job was not /// accepted (the engine failed: EIO) and the caller fails it; once accepted, its fence is /// signalled by the engine, also on failure. @@ -115,29 +172,33 @@ impl Shared { let accepted = { let mut state = self.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; - if firmware.engine.shared.is_none() { - firmware.engine.shared = Some(self.clone()); + self.submit_locked(firmware, job, &mut done) + }; + job::complete_all(done); + drop(signalling); + self.notify_wedged(); + accepted + } + + /// Non-blocking variant of [`Self::submit`] for inline SUBMIT ioctl publication: returns + /// `None` without sleeping when `Shared::state` is contended so `drm_sched` publishes instead. + pub(crate) fn try_submit_inline(self: &Arc, job: Arc) -> Option { + let signalling = kernel::dma_fence::SignallingGuard::new(); + let mut done = Completions::new(); + let accepted = { + let mut state = self.state.try_lock()?; + if self.sleeping.load(Ordering::Acquire) { + return None; } - let accepted = firmware.enqueue(job); - // Nothing is published while a render is in flight: the poll pass after its - // retirement publishes this job. Skipping the pass here keeps queued submissions - // from holding the device lock (ring drains, health checks) on that path. - let render_busy = firmware.engine.flights.iter().any(|f| f.renders != 0); - if accepted.is_ok() && !render_busy { - if let Err(error) = firmware.publish(&mut done) { - firmware.fail_stop(error, &mut done); - self.fail_stop(error); - } - if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { - self.rearm(firmware.engine.chan_wait); - } + match state.as_deref_mut() { + Some(firmware) => self.submit_locked(firmware, job, &mut done), + None => Err(ENODEV), } - accepted }; job::complete_all(done); drop(signalling); self.notify_wedged(); - accepted + Some(accepted) } /// Deliver userspace notification outside the device mutex and fence completion path. @@ -154,12 +215,25 @@ impl Shared { } } - /// Queues the poll work now, or brings a pending one forward. Callable from any context. + /// Queues the fast poll work immediately on the submitting CPU. Callable from any context. pub(crate) fn poll_now(self: &Arc) { - self.mod_poll(0); + let _ = match self.submitter_cpu() { + Some(cpu) => self + .events + .enqueue_on::, FAST_POLL_WORK>(cpu, self.clone()), + None => self + .events + .enqueue::, FAST_POLL_WORK>(self.clone()), + }; } - /// Queues the poll on `system_highpri_wq` after `delay` jiffies, or moves an already + /// Disarms the completion hrtimer when idle or entering system sleep. + pub(crate) fn cancel_resnap(&self) { + self.resnap_deadline_ns.store(0, Ordering::Release); + drop(self.resnap_handle.lock().take()); + } + + /// Queues the backup poll on `system_highpri_wq` after `delay` jiffies, or moves an already /// pending one to that expiry. fn mod_poll(self: &Arc, delay: Jiffies) { // SAFETY: The closure returns false only when `mod_delayed_work_on` found the work @@ -178,21 +252,28 @@ impl Shared { }; } - /// Re-checks a published command soon: hrtimer, with a one-jiffy backup; sooner while a - /// ready prefix waits for a channel record's consumption. - pub(crate) fn rearm(self: &Arc, chan_wait: bool) { + /// Re-checks a published command soon: hrtimer, with a throttled 1-jiffy backup; sooner while + /// a ready prefix waits for record consumption or a post-event receipt tail is settling. + pub(crate) fn rearm(self: &Arc, soon: bool) { let mut us = params::resnap_us(); - if chan_wait && module_parameters::g16_repoll_us.value() != 0 { + if soon && module_parameters::g16_repoll_us.value() != 0 { us = params::repoll_us(); } - { + let now = now_ns(); + let target_ns = now.saturating_add(u64::from(us) * 1000); + let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); + if armed_ns == 0 || armed_ns <= now || target_ns.saturating_add(5_000) < armed_ns { let mut handle = self.resnap_handle.lock(); - // Dropping the previous handle cancels a still pending expiry before the timer - // is started again. drop(handle.take()); + self.resnap_deadline_ns.store(target_ns, Ordering::Release); *handle = Some(self.clone().start(Delta::from_micros(i64::from(us)))); } - self.mod_poll(1); + let backup_ns = self.backup_deadline_ns.load(Ordering::Acquire); + if now >= backup_ns { + self.backup_deadline_ns + .store(now.saturating_add(BACKUP_REARM_NS), Ordering::Release); + self.mod_poll(1); + } } /// Starts what the engine needs besides the firmware state: the `aurora-g16/stats` file. @@ -228,9 +309,17 @@ impl Firmware { if self.recovery.failed().is_some() { return Ok(false); } - self.session.check()?; - self.objects.health()?; - self.service_power()?; + self.engine.short_repoll = false; + self.session.transport()?; + let now = now_ns(); + let housekeeping = self.engine.flights.is_empty() + || now.wrapping_sub(self.last_housekeeping_ns) >= HOUSEKEEPING_NS; + if housekeeping { + self.session.check()?; + self.objects.health()?; + self.service_power()?; + self.last_housekeeping_ns = now; + } // With nothing published only a pending firmware recovery notification needs this // pass: one that arrived after its prefix's receipts is answered // here (the firmware halted and waits for the resume) instead of being taken for a @@ -248,10 +337,14 @@ impl Firmware { self.retire(evented, done)?; lap.lap(&mut self.engine.prof.retire_ns); self.answer_growth()?; - self.check_hangs(done)?; - let published = self - .service_power() - .and_then(|()| self.publish_checked(done)); + if housekeeping || self.recovery.receipt_fault || self.recovery_pending()? { + self.check_hangs(done)?; + } + let published = if self.engine.pending.is_empty() { + Ok(()) + } else { + self.publish_checked(done) + }; let s = &mut self.engine.stats; if self.engine.flights.is_empty() && s.idle_from_ns != 0 { // Idle with nothing ready is not a gap: the clients are late. @@ -263,18 +356,22 @@ impl Firmware { self.engine.prof.poll_ns += now_ns().wrapping_sub(start); } published?; + // If an EP 0x20 event arrived and a flight still did not finish its final receipt + // within the trailing spin, repoll at `repoll_us` instead of sleeping `resnap_us`. + self.engine.short_repoll = evented && !self.engine.flights.is_empty(); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() || self.engine.frozen) } - /// Drains the rings and retires finished flights, with up to four trailing 5 us polls - /// after an event. A receipt fault is left in `Recovery::receipt_fault` for the hang - /// checks. + /// Drains the rings and retires finished flights, with up to [`EVENT_RETIRE_POLLS`] + /// trailing 5 us polls after an event. A receipt fault is left in + /// `Recovery::receipt_fault` for the hang checks. pub(crate) fn retire(&mut self, evented: bool, done: &mut Completions) -> Result { - // After an event, a few short trailing polls catch the final receipts. - let mut tail = if evented { 4 } else { 0 }; + // After an event, short trailing polls catch firmware's final WC receipt writes + // before falling back to a timer repoll. + let mut tail = if evented { EVENT_RETIRE_POLLS } else { 0 }; let mut ret; loop { @@ -282,7 +379,9 @@ impl Firmware { self.drain_rings()?; lap.lap(&mut self.engine.prof.drain_ns); // Recovery may force stage progress: authenticate it before any receipt. - self.check_hangs(done)?; + if self.recovery.receipt_fault || self.recovery_pending()? { + self.check_hangs(done)?; + } ret = self.retired(); while let Ok(receipt) = ret { if !receipt.complete() { diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index a383a09b8d971..bb4069ec02171 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -100,7 +100,7 @@ impl Shared { /// With the sleeping flag set, joins whatever may be reading the firmware's registers. fn join_workers(self: &Arc) { // Dropping the handle cancels an expiry that's still pending. - drop(self.resnap_handle.lock().take()); + self.cancel_resnap(); // SAFETY: An initialized, pinned delayed work of this Shared. A pending callback owned // one Arc that it can no longer reclaim. Later enqueues run into the sleeping check. let cancelled = unsafe { @@ -112,6 +112,7 @@ impl Shared { // SAFETY: See above. drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); } + self.events.drain(); } /// Waits for what's been published to retire. The poll work keeps running meanwhile. diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py index efe5a60fd2cfd..b2a4cc45ac7d3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py @@ -30,7 +30,7 @@ def function(text, name): return text[start:at] queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check']) -methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired']) +methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired']) fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies']) harness = r''' #![allow(dead_code)] @@ -99,14 +99,18 @@ def function(text, name): struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2] } impl QueueState { QUEUE_METHODS } struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,orders:Vec,queue:Arc,full_retired:AtomicU32,terminal_retired:AtomicBool } -struct Shared { crashed:AtomicBool,submitted:Mutex>,submit_result:Result } +struct Shared { crashed:AtomicBool,sleeping:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } impl Shared { fn new()->Arc { - Arc::new(Self{crashed:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) + Arc::new(Self{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) } fn submit(&self,job:Arc)->Result { self.submitted.lock().unwrap().push(job.id); self.submit_result } + fn try_submit_inline(&self,job:Arc)->Option { + if self.contended.load(Ordering::Acquire) { return None; } + Some(self.submit(job)) + } } impl Job { METHODS @@ -370,7 +374,7 @@ def function(text, name): #[test] fn never_published_capacity_failure_closes_only_its_queue() { let status=Arc::new(Status::new());let failed=job(1,status.clone()); - let shared=Arc::new(Shared{crashed:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Err(ENOMEM)}); + let shared=Arc::new(Shared{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Err(ENOMEM)}); failed.start(&shared); assert_eq!(failed.fence.signals.lock().unwrap()[0],(Err(ENOMEM),-12)); assert_eq!(failed.queue.check(&failed.orders[0]),Err(ECANCELED));assert_eq!(status.get(),0); @@ -391,6 +395,33 @@ def function(text, name): assert_eq!(queued.note_full_retirement(u32::MAX,1),Err(EOVERFLOW)); queued.note_full_retirement(1,1).unwrap(); } +#[test] +fn inline_start_submits_once_and_falls_back_on_pending_input_or_contention() { + let status=Arc::new(Status::new()); + let shared=Shared::new(); + // Ready job with signalled input submits inline; subsequent drm_sched start() is a no-op. + let ready=job_with_inputs(10,status.clone(),vec![InputFence::new(1)]); + ready.try_start_inline(&shared); + assert!(ready.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + ready.start(&shared); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + // Unsignalled input defers to drm_sched without marking started. + let pending=job_with_inputs(11,status.clone(),vec![InputFence::new(0)]); + pending.try_start_inline(&shared); + assert!(!pending.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + // Contended device mutex defers to drm_sched without blocking or marking started. + shared.contended.store(true,Ordering::Release); + let contended=job(12,status.clone()); + contended.try_start_inline(&shared); + assert!(!contended.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + shared.contended.store(false,Ordering::Release); + contended.start(&shared); + assert!(contended.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10,12]); +} '''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::')) with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory: From 4c0aaf1e1b3eeb629ce6b017b4d4c0d0775419b7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:47:41 -0500 Subject: [PATCH 13/19] drm/asahi: g16: expand render pass slots to 8, isolate scene_list, and decouple PB/UMA slots Compact the per-pass render VA layout from 256 MiB to 64 MiB stride within 0x7020000000..0x7040000000 (verified by compile-time overlap assertions), expanding RENDER_SLOTS from 2 to 8, and move scene_list (0x4000 bytes) from the shared per-allocator Allocator into per-pass PassSlot (client VA client::SCENE_LIST + i * PASS_STRIDE, 0x7020180000). Giving each PassSlot its own scene_list matches G15's per-pass storage and prevents TA(N)/FS(N-1) overlap corruption when render pipelining is enabled. This commit is bisect-safe on its own with render overlap still off: Order::ready() and Firmware::can_queue_behind() still serialize renders at depth 1 until the following commit, so the compacted 64 MiB pass stride and per-PassSlot scene_list run cleanly under single-flight render execution. Keep base RenderArena at 2 pass slots for single-pass or light VMs and lazily allocate extension pass slots 2..8 in RenderExtArena on render bursts (mirroring compute_ext). Box RenderOwners in Slots alongside ComputeOwners and switch its displacement ledger to pipelined mode (Lifetime::<8>::new(true)), keeping up to 7 concurrent passes in flight. Decouple the two device-wide PB/UMA allocator slots (parameter_id 0/1, hardware UMA slot 33) from PassSlot index 0..8: same-VM renders stay on their active reusable allocator slot with cumulative uma_submitted tracking (PoolSet::prepare_in_flight / retired_at), while cross-VM switches and post-recovery/error renders drain and switch to the displaced alternate slot. Aborted receipts permanently quarantine the affected allocator slot and retain its VM and arena leases. Check Pools::exhausted(), per-VM Pools::exhausted_for(), and Slots::render_exhausted_within() in publish_checked() so blocked render VMs cancel immediately with ECANCELED instead of spinning on EAGAIN and stalling unrelated compute. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/encode/render.rs | 23 +- drivers/gpu/drm/asahi/g16/engine.rs | 132 +++++++--- drivers/gpu/drm/asahi/g16/hw.rs | 24 +- drivers/gpu/drm/asahi/g16/poll.rs | 32 ++- drivers/gpu/drm/asahi/g16/pools.rs | 220 ++++++++++++++-- drivers/gpu/drm/asahi/g16/resources.rs | 156 +++++++++++- drivers/gpu/drm/asahi/g16/slots.rs | 235 +++++++++++++----- .../drivers/gpu/asahi-m4/check-render.rs | 11 + .../drivers/gpu/asahi-m4/test-resources.py | 162 +++++++++++- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 14 +- .../drivers/gpu/asahi-m4/test-timestamps.py | 2 +- 11 files changed, 835 insertions(+), 176 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index d949013e46206..064b297f75bc5 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -21,7 +21,8 @@ pub(crate) struct RenderRefs { pub(crate) uma_aux: [u64; 2], pub(crate) uma_gpu: u64, pub(crate) pb_mgr: u64, - /// GPU VA of the scene list, not its firmware alias. + /// Fallback GPU VA of the scene list when `PassRefs::scene_list` is zero (ABI tests). + #[allow(dead_code)] pub(crate) scene_list: u64, #[allow(dead_code)] pub(crate) mgr_misc: u64, @@ -55,6 +56,8 @@ pub(crate) struct PassRefs { pub(crate) heap_gva: u64, /// Scratch GPU VA; scratch_fw is a same-backing firmware alias. pub(crate) scene_user_gva: u64, + /// Per-pass scene list GPU VA, not its firmware alias. + pub(crate) scene_list: u64, pub(crate) scratch_fw: u64, pub(crate) pre_gva: [u64; 3], #[allow(dead_code)] @@ -66,6 +69,14 @@ pub(crate) struct PassRefs { pub(crate) ta_scratch: u64, } +fn scene_list_va(r: &RenderRefs, p: &PassRefs) -> u64 { + if p.scene_list != 0 { + p.scene_list + } else { + r.scene_list + } +} + fn metadata(w: &mut [u8], off: usize, r: &RenderRefs, engine: usize, target: u32) { put64(w, off, r.user_stamp[engine]); put64(w, off + 8, r.fw_stamp[engine]); @@ -229,8 +240,8 @@ pub(crate) fn encode_ta_for( 8, 0xff0000, u64::from(r.parameter_id), - compact(r.scene_list), - compact(r.scene_list), + compact(scene_list_va(r, p)), + compact(scene_list_va(r, p)), scratch_word, 0x6000400020, 0x200000001, @@ -427,7 +438,7 @@ pub(crate) fn encode_fs_for( u64::from(r.uuid), u64::from(r.uuid), u64::from(r.parameter_id), - compact(r.scene_list), + compact(scene_list_va(r, p)), usc, ]; regs(&mut w[fs::REGS..], &fs::SEL, &val); @@ -586,7 +597,7 @@ pub(crate) fn fill_scene(r: &RenderRefs, p: &PassRefs, out: &mut [u8]) { out.fill(0); put64(out, 0, p.scene_user_gva); put64(out, 8, p.scratch_fw); - put64(out, 0x28, compact(r.scene_list)); + put64(out, 0x28, compact(scene_list_va(r, p))); put64(out, 0x40, p.scene + 0x200); put64(out, 0x500, r.uma_submitted); } @@ -597,7 +608,7 @@ pub(crate) fn scene(r: &RenderRefs, p: &PassRefs, _n: u64) -> [u8; 0x80] { let mut out = [0u8; 0x80]; put64(&mut out, 0, p.scene_user_gva); put64(&mut out, 8, p.scratch_fw); - put64(&mut out, 0x28, compact(r.scene_list)); + put64(&mut out, 0x28, compact(scene_list_va(r, p))); put64(&mut out, 0x40, p.scene + 0x200); out } diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index c96d68cffc52b..6936b40afd35c 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -187,10 +187,14 @@ pub(crate) struct Flight { pub(crate) published_ns: u64, /// Published behind another flight. pub(crate) behind: bool, - /// The PB epoch this render prefix uses (its own, or a reused pass-slot epoch). + /// The PB epoch this render prefix uses (its own, or a reused allocator-slot epoch). pub(crate) pb: Option>, - /// Its pass slot binding (`Pools::bind`). + /// Its allocator slot (`0` or `1`, decoupled from `claims.pass[0]`). + pub(crate) pb_slot: u32, + /// Its allocator slot binding (`Pools::bind`). pub(crate) pb_binding: u64, + /// Whether this render carries InitBM (priming renders always drain before pipelining). + pub(crate) initbm: bool, } impl Flight { @@ -222,7 +226,9 @@ impl Flight { published_ns: 0, behind: false, pb: None, + pb_slot: 0, pb_binding: 0, + initbm: false, } } } @@ -668,7 +674,7 @@ impl Firmware { && !super::poll::stamp_reached(stage[0], f.ta_target, self.engine.ta_target) { let k = f.claims.pass[0] as usize; - let pass = f.job.resources.render()?.passes.get(k).ok_or(EINVAL)?; + let pass = f.job.resources.render_pass(k)?; let bytes = pass.ta_work.r64(work::ta::TPC_BYTES)?; if bytes == 0 || bytes > pass.tpc.size as u64 { return Err(ERANGE); @@ -817,7 +823,7 @@ impl Firmware { } } Some(Command::Render(_)) => { - if self.slots.render_exhausted() { + if self.slots.render_exhausted() || self.pools.exhausted() { Some((super::command::RENDER, EIO)) } else if super::recovery::logic::next_ordinal(self.engine.draw).is_none() { Some((super::command::RENDER, EOVERFLOW)) @@ -841,6 +847,23 @@ impl Firmware { complete(done, &job, Err(ECANCELED)); continue; } + // A VM whose render pass slots were all quarantined, or that cannot acquire a + // physical PB allocator slot because the alternate slot is quarantined and the + // active slot belongs to another VM, cannot render again: cancel its queue + // immediately instead of spinning on EAGAIN and stalling unrelated compute. + if class_error.is_none() + && matches!(command(&job, job.progress.sent()), Some(Command::Render(_))) + && (self.pools.exhausted_for(&job.vm) + || job + .resources + .render_passes() + .is_ok_and(|n| self.slots.render_exhausted_within(n))) + { + self.engine.unpend(&job); + let _ = job.mark_terminal_retired(); + complete(done, &job, Err(ECANCELED)); + continue; + } if let Some((class, error)) = class_error { self.mark_class_unavailable(class, error); self.engine.unpend(&job); @@ -973,27 +996,34 @@ impl Firmware { job.progress.sent() != 0 } - /// Addresses and cumulative allocator state of the selected retained render unit. + /// Addresses and cumulative allocator state of the selected retained render allocator slot. fn render_refs( &mut self, - k: usize, + alloc_slot: usize, job: &Job, draw: u64, + pipelined: bool, ) -> Result<(RenderRefs, bool, Arc, u64)> { let generation = job.vm.generation; let arena = job.resources.render()?; - let mut a = arena.pools.prepare(k, draw)?; - // Reuse this VM's retired epoch of the slot when still bound: no reseed, no InitBM. - let (epoch, reused) = match self.pools.reusable(k, &job.vm) { + let mut a = arena.pools.prepare_in_flight(alloc_slot, draw, pipelined)?; + // Reuse this VM's retired epoch of the allocator slot when still bound (no reseed/InitBM). + let (epoch, reused) = match self.pools.reusable(alloc_slot, &job.vm) { Some(e) => { self.pools.stats.reused += 1; a.init_buffer = false; (e, true) } None => { + if pipelined { + return Err(EAGAIN); + } let e = job.resources.take_pb()?; - if let Err(err) = e.prepare(k, arena.pools.heap_gva(k)?, arena.pools.heap_blocks()) - { + if let Err(err) = e.prepare( + alloc_slot, + arena.pools.heap_gva(alloc_slot)?, + arena.pools.heap_blocks(), + ) { job.resources.return_pb(e); return Err(err); } @@ -1001,7 +1031,7 @@ impl Firmware { (e, false) } }; - let binding = self.pools.bind(k, reused); + let binding = self.pools.bind(alloc_slot, reused); a.pb_mgr = epoch.manager.va; a.mgr_misc = epoch.misc.va; let r = &self.graph.render; @@ -1020,7 +1050,7 @@ impl Firmware { uma_aux: a.uma_aux, uma_gpu: a.uma_gpu, pb_mgr: a.pb_mgr, - scene_list: a.scene_list, + scene_list: 0, mgr_misc: a.mgr_misc, pb_init_blocks: a.init_blocks, parameter_id: a.parameter_id, @@ -1072,6 +1102,9 @@ impl Firmware { ) -> Result { let result = self.publish_prefix_body(job, f, visible); if result.is_err() && !*visible { + if f.pb.is_some() { + self.pools.cancel_alloc(f.pb_slot as usize); + } if let Some(epoch) = f.pb.take() { if epoch.unexposed() { job.resources.return_pb(epoch); @@ -1098,7 +1131,7 @@ impl Firmware { return Err(EIO); } if if render { - self.slots.render_exhausted() + self.slots.render_exhausted() || self.pools.exhausted() } else { self.slots.compute_exhausted() } { @@ -1113,7 +1146,7 @@ impl Firmware { let pipe = self.channels.channel(channel); let producer = self.channels.producer(channel); let busy = if behind { - // Behind in-flight compute: post after its unconsumed records, with room. + // Behind in-flight commands: post after their unconsumed records, with room. pipe.write()? != producer || producer.wrapping_sub(pipe.read()?) % RING_SLOTS >= sizes::AHEAD_RECORDS } else { @@ -1142,12 +1175,26 @@ impl Firmware { return Err(super::boot::eproto()); } if behind { - // Room for one more compute entry behind the unconsumed ones. - let read = self.graph.compute.qstate.r32(qstate::READ)?; - if read >= 256 - || prefix.c_head.wrapping_sub(read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 2 - { - return Err(EAGAIN); + if render { + let ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; + let fs_read = self.graph.render.qstate[1].r32(qstate::READ)?; + if ta_read >= 256 + || fs_read >= 256 + || prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP + >= sizes::QUEUE_CAP - 4 + || prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP + >= sizes::QUEUE_CAP - 4 + { + return Err(EAGAIN); + } + } else { + // Room for one more compute entry behind the unconsumed ones. + let read = self.graph.compute.qstate.r32(qstate::READ)?; + if read >= 256 + || prefix.c_head.wrapping_sub(read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 2 + { + return Err(EAGAIN); + } } } f.c_start = prefix.c_head; @@ -1157,21 +1204,25 @@ impl Firmware { Command::Compute(c) => self.prefix_compute(job, c, &mut prefix, f, false)?, Command::Render(r) => { let geometry = Geometry::new(&r.cmd, 0); - if job.resources.render()?.passes.iter().all(|slot| { - geometry - .validate_capacity(slot.tpc.size as u64, slot.tilemap.size as u64) - .is_err() + let n = job.resources.render_passes()?; + if (0..n).all(|k| { + job.resources.render_pass(k).is_err_and(|_| true) + || job.resources.render_pass(k).is_ok_and(|slot| { + geometry + .validate_capacity(slot.tpc.size as u64, slot.tilemap.size as u64) + .is_err() + }) }) { return Err(E2BIG); } let k = self .slots - .pick_pass(job.resources.render()?, &geometry, 0) + .pick_pass_in(&job.resources, &geometry, 0) .ok_or(EAGAIN)?; f.claims.pass[0] = k as u32; f.claims.pass_mask = 1 << k; self.slots.pass_busy |= 1 << k; - self.prefix_render(job, r, &mut prefix, f)?; + self.prefix_render(job, r, &mut prefix, f, behind)?; } } f.first = index as usize; @@ -1194,7 +1245,12 @@ impl Firmware { if render { f.pb.as_ref() .ok_or(EINVAL)? - .check_assignment(f.claims.pass[0] as usize)?; + .check_assignment(f.pb_slot as usize)?; + self.pools.hold_alloc( + f.pb_slot as usize, + &job.vm, + job.resources.render_arena(), + )?; } // Reserve lifetime ownership before any counter or producer becomes reachable. job.vm.vm.mark_binding_published()?; @@ -1206,10 +1262,11 @@ impl Firmware { *visible = true; let publication = (|| -> Result { if render { - let k = f.claims.pass[0] as usize; + let a = f.pb_slot as usize; f.pb.as_ref().ok_or(EINVAL)?.expose(); job.resources.commit_render(); - job.resources.render()?.pools.publish(k, f.uma_submitted)?; + job.resources.render()?.pools.publish(a, f.uma_submitted)?; + self.pools.publish_flight(a); // Notifier service dereferences u32 counters; the host ordering ledger // remains u64. Eight-byte spacing is retained allocation padding. self.graph.render.threshold.w32(0, prefix.draw as u32)?; @@ -1428,32 +1485,35 @@ impl Firmware { } /// Encodes paired TA/FS work and the fragment's explicit TA dependency in one retained - /// pass unit. The preceding command already has a complete wire receipt. + /// pass unit. fn prefix_render( &mut self, job: &Arc, cmd: &RenderCommand, pf: &mut Prefix, f: &mut Flight, + behind: bool, ) -> Result { let k = f.claims.pass[0] as usize; + let alloc_slot = self.pools.pick_slot(&job.vm, behind).ok_or(EAGAIN)?; let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots - .claim_pass_for(job.resources.render()?, k, Some(job.vm.id))?; + .claim_pass_in(&job.resources, k, Some(job.vm.id))?; self.slots.hold_vm(&f.claims, &job.vm)?; self.slots.hold_arenas(&f.claims, &job.resources); - let (refs, init_buffer, epoch, binding) = self.render_refs(k, job, draw)?; + let (refs, init_buffer, epoch, binding) = self.render_refs(alloc_slot, job, draw, behind)?; f.pb = Some(epoch); + f.pb_slot = alloc_slot as u32; f.pb_binding = binding; - let p = &job.resources.render()?.passes[k]; + f.initbm = init_buffer; + let p = job.resources.render_pass(k)?; let pass = p.refs(); let geometry = Geometry::new(&cmd.cmd, pass.heap_gva); geometry.validate_capacity(p.tpc.size as u64, p.tilemap.size as u64)?; job.resources - .render()? - .set_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes)?; + .set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes)?; let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; encode::encode_ta_for( self.init.abi.ta(), diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index c840f3c7d92f9..f92bea3be3d37 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -633,12 +633,12 @@ pub(crate) mod client { pub(crate) const PB_PAGE_LIST: u64 = 0x7012040000; pub(crate) const PB_PAGE_LIST_SIZE: u64 = 0x8000; - // Render pass resources, each in a distinct 256 MiB interval. + // Render pass resources, each in a distinct 64 MiB interval within 0x7020000000..0x7040000000. pub(crate) const FS_WORK_PAGE: u64 = 0x7020000000; pub(crate) const FS_WORK_OFF: u64 = 0; pub(crate) const TA_WORK_PAGE: u64 = 0x7020004000; pub(crate) const TA_WORK_OFF: u64 = 0; - pub(crate) const WORK_STRIDE: u64 = 0x10000000; + pub(crate) const WORK_STRIDE: u64 = 0x04000000; pub(crate) const PASS_STRIDE: u64 = WORK_STRIDE; pub(crate) const PRE0_PAGE: u64 = 0x7020080000; pub(crate) const PRE1_PAGE: u64 = 0x70200a0000; @@ -648,9 +648,10 @@ pub(crate) mod client { pub(crate) const FS_SCRATCH: u64 = 0x7020140000; pub(crate) const AUX: u64 = 0x7020160000; pub(crate) const AUX_STRIDE: u64 = WORK_STRIDE; - pub(crate) const TPC: u64 = 0x7024000000; + pub(crate) const SCENE_LIST: u64 = 0x7020180000; + pub(crate) const TPC: u64 = 0x7020400000; pub(crate) const TPC_SIZE: u64 = 0x1000000; - pub(crate) const TILEMAP: u64 = 0x7026000000; + pub(crate) const TILEMAP: u64 = 0x7021400000; pub(crate) const TILEMAP_SIZE: u64 = 0x800000; pub(crate) const TPC_SLOT_SIZE: u64 = TPC_SIZE; pub(crate) const TILEMAP_SLOT_SIZE: u64 = TILEMAP_SIZE; @@ -667,7 +668,20 @@ pub(crate) mod sizes { pub(crate) const FREELIST_SEED: u32 = 8192; pub(crate) const QUEUE_CAP: u32 = 256; pub(crate) const COMPUTE_SLOTS: usize = 2; - pub(crate) const RENDER_SLOTS: usize = 2; + /// Retained render pass slots per VM at most. A slot is reused only after a later render + /// retired (displacing it), so `n` slots keep up to `n - 1` renders in flight. + pub(crate) const RENDER_SLOTS: usize = 8; + const _: () = assert!(super::client::AUX + 0x20000 <= super::client::SCENE_LIST); + const _: () = assert!(super::client::SCENE_LIST + 0x4000 <= super::client::TPC); + const _: () = assert!(super::client::TPC + super::client::TPC_SIZE <= super::client::TILEMAP); + const _: () = assert!( + super::client::TILEMAP + super::client::TILEMAP_SIZE + <= super::client::FS_WORK_PAGE + super::client::PASS_STRIDE + ); + const _: () = assert!( + super::client::FS_WORK_PAGE + (RENDER_SLOTS as u64) * super::client::PASS_STRIDE + <= 0x7040000000 + ); pub(crate) const CT_BUFS: usize = 0; pub(crate) const CLUSTER_PB_PAGES: u32 = 0x3c; pub(crate) const MAX_ATTACHMENTS: usize = 16; diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 72f897fd6b8f1..a655094bfd139 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -590,7 +590,8 @@ impl Firmware { return Ok(Retirement::Pending); } let k = f.claims.pass[0] as usize; - let unit = f.job.resources.render()?.passes.get(k).ok_or(EINVAL)?; + let a = f.pb_slot as usize; + let unit = f.job.resources.render_pass(k)?; let ta_start = unit.scene.r64(0x600)?; let ta_end = unit.scene.r64(0x608)?; let fs_start = unit.scene.r64(0x620)?; @@ -601,7 +602,7 @@ impl Firmware { && g.notifier .r32(notifier_page::FS_RECORD + notifier::CONTEXT)? == f.job.vm.slot - && f.job.resources.render()?.pools.retired(k)? + && f.job.resources.render()?.pools.retired(a)? && ta_start != 0 && ta_end > ta_start && fs_start != 0 @@ -681,10 +682,12 @@ impl Firmware { self.recovery.last_retired[1] = Some(f.ta_target); self.recovery.last_retired[2] = Some(f.fs_target); let committed = f.pb.as_ref().ok_or(EINVAL).and_then(|epoch| { - let k = timestamp_claims.pass[0] as usize; - self.pools.retire_binding(k, epoch)?; - self.pools.retire_epoch(k, f.pb_binding, result.is_ok()); - Ok(()) + self.pools.retire_flight( + f.pb_slot as usize, + epoch, + f.pb_binding, + result.is_ok(), + ) }); if let Err(error) = committed { self.retain(&f.job); @@ -708,8 +711,8 @@ impl Firmware { // Only an actual passed abort lacks the full owner receipt. An affected job // with a full normal receipt fails its fence without poisoning healthy storage. if f.renders != 0 { - // The quarantined slot is not picked again, but keep no epoch of it for reuse. - self.pools.forget(timestamp_claims.pass[0] as usize); + // Quarantine the aborted allocator slot permanently and keep no epoch for reuse. + self.pools.quarantine_flight(f.pb_slot as usize); } self.slots.quarantine(&mut f.claims); self.retain(&f.job); @@ -718,7 +721,7 @@ impl Firmware { if self.slots.compute_exhausted() { self.mark_class_unavailable(super::command::COMPUTE, EIO); } - if self.slots.render_exhausted() { + if self.slots.render_exhausted() || self.pools.exhausted() { self.mark_class_unavailable(super::command::RENDER, EIO); } if result.is_ok() { @@ -865,13 +868,7 @@ impl Firmware { } super::command::Command::Render(command) => { let index = *passes.get(render).ok_or(EINVAL)? as usize; - let pass = flight - .job - .resources - .render()? - .passes - .get(index) - .ok_or(EINVAL)?; + let pass = flight.job.resources.render_pass(index)?; let ticks = [ pass.scene.r64(0x600)?, pass.scene.r64(0x608)?, @@ -928,10 +925,9 @@ impl Firmware { hi = hi.max(end); }; for k in 0..f.renders as usize { - let Some(arena) = f.job.resources.render.as_ref() else { + let Ok(p) = f.job.resources.render_pass(f.claims.pass[k] as usize) else { return; }; - let p = &arena.passes[f.claims.pass[k] as usize]; stage( &p.scene, 0x600, diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 739cfd1510de4..3eeb2cf794f21 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -35,7 +35,6 @@ pub(crate) struct AllocatorRefs { pub(crate) uma_aux: [u64; 2], pub(crate) uma_gpu: u64, pub(crate) pb_mgr: u64, - pub(crate) scene_list: u64, pub(crate) mgr_misc: u64, pub(crate) init_blocks: u32, pub(crate) parameter_id: u32, @@ -58,7 +57,6 @@ struct Allocator { list: Arc, submitted: Arc, heap: Arc, - scene_list: Arc, published: AtomicBool, id: u32, } @@ -133,7 +131,6 @@ fn write_records( } impl Allocator { fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { - let base = client::render_base(k); let nc = |va| Some((va, pte::LEAF_NC)); // Native UMA software metadata is ASC-owned and never needs a client GPU alias. // In particular its firmware pointers, +0x54 completion and +0x5c exclusion flag @@ -157,13 +154,6 @@ impl Allocator { let list = alloc(o, 0x4000, Class::Shared, nc(client::render_list(k)), true)?; let submitted = alloc(o, 0x40, Class::Fw, None, true)?; let heap = heap.clone(); - let scene_list = alloc( - o, - buffer::SCENE_LIST_SIZE, - Class::Shared, - nc(base + 0x2070000), - true, - )?; super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; descriptor.write( 0, @@ -183,7 +173,6 @@ impl Allocator { list, submitted, heap, - scene_list, published: AtomicBool::new(false), id: k as u32, }) @@ -199,7 +188,6 @@ impl Allocator { uma_aux: [self.auxiliary.va + 0x100, self.auxiliary.va + 0x200], uma_gpu: gva(&self.auxiliary)?, pb_mgr: 0, - scene_list: gva(&self.scene_list)?, mgr_misc: 0, init_blocks: buffer::MAX_BLOCKS, parameter_id: self.id, @@ -214,6 +202,10 @@ impl Allocator { let completed = read64(&self.descriptor, uma_manager::COMPLETED)?; Ok(submitted != 0 && submitted == completed) } + fn retired_at(&self, target: u64) -> Result { + let completed = read64(&self.descriptor, uma_manager::COMPLETED)?; + Ok(target != 0 && completed >= target) + } } impl PoolSet { pub(crate) fn new(o: &mut Objects) -> Result { @@ -237,9 +229,21 @@ impl PoolSet { pub(crate) fn allocator_refs_for(&self, k: usize) -> Result { self.units.get(k).ok_or(EINVAL)?.refs() } - pub(crate) fn prepare(&self, k: usize, _draw: u64) -> Result { + #[allow(dead_code)] + pub(crate) fn prepare(&self, k: usize, draw: u64) -> Result { + self.prepare_in_flight(k, draw, false) + } + /// Prepares UMA/PB allocator slot `k` (`0` or `1`). When `pipelined` is true, earlier + /// same-VM renders are still in flight on the same active descriptor and PB manager, so + /// the submitted counter advances cumulatively while descriptor identity is still verified. + pub(crate) fn prepare_in_flight( + &self, + k: usize, + _draw: u64, + pipelined: bool, + ) -> Result { let u = self.units.get(k).ok_or(EINVAL)?; - if u.published.load(Ordering::Acquire) && !u.retired()? { + if !pipelined && u.published.load(Ordering::Acquire) && !u.retired()? { return Err(EBUSY); } // Descriptor pointer/counter and slot must still identify this exact retained unit. @@ -263,6 +267,10 @@ impl PoolSet { pub(crate) fn retired(&self, k: usize) -> Result { self.units.get(k).ok_or(EINVAL)?.retired() } + #[allow(dead_code)] + pub(crate) fn retired_at(&self, k: usize, target: u64) -> Result { + self.units.get(k).ok_or(EINVAL)?.retired_at(target) + } pub(crate) fn heap_gva(&self, k: usize) -> Result { gva(&self.units.get(k).ok_or(EINVAL)?.heap) } @@ -271,16 +279,35 @@ impl PoolSet { } } -/// Device-wide physical PB-slot leases. Replacement requires a complete normal receipt. +/// Device-wide physical PB-slot leases (`parameter_id` 0 and 1, hardware UMA slot 33). +/// +/// Decoupled from per-pass storage (`PassSlot 0..RENDER_SLOTS`): same-VM renders stay on one +/// active `pb_slot` and reuse its exposed `PbEpoch` (including pipelined renders in flight), +/// while cross-VM switches or post-recovery/error renders drain and switch to the displaced +/// alternate `pb_slot` so the previous VM's UMA/PB storage remains mapped through displacement. pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, owners: [Option>; 2], - /// Per pass slot, a binding count, bumped by each fresh epoch (its InitBM rebinds the + #[allow(dead_code)] + owner_vms: [Option>; 2], + #[allow(dead_code)] + owner_arenas: [Option>; 2], + pending_vms: [Option>; 2], + pending_arenas: [Option>; 2], + /// Per allocator slot, a binding count, bumped by each fresh epoch (its InitBM rebinds the /// slot) and by a firmware recovery. It identifies a binding without holding the epoch. binds: [u64; 2], - /// Per pass slot: `owners[k]` may serve the next render of its VM. + /// Per allocator slot: `owners[k]` may serve the next render of its VM without InitBM. keep: [bool; 2], + /// Most recently published allocator slot (`0` or `1`). + active: Option, + /// Most recently cleanly retired allocator slot (proves the alternate slot is displaced). + last_clean_retired: Option, + /// Live in-flight render count per allocator slot. + inflight: [u32; 2], + /// Permanently quarantined allocator slots after an aborted receipt. + quarantined: [bool; 2], } impl Pools { pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { @@ -288,22 +315,164 @@ impl Pools { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), owners: [None, None], + owner_vms: [None, None], + owner_arenas: [None, None], + pending_vms: [None, None], + pending_arenas: [None, None], binds: [0, 0], keep: [false, false], + active: None, + last_clean_retired: None, + inflight: [0, 0], + quarantined: [false, false], } } - /// Slot `k`'s owner epoch, if its render retired normally while the slot was still bound to - /// it, it belongs to `vm` and was exposed (its InitBM ran). InitBM binds the device-wide - /// slot to one epoch and VM; a fresh epoch handed to the slot rebinds it, so the owner is - /// then stale and the render starts fresh. Adds no reference beyond the owner lease itself. + /// Allocator slot `k`'s owner epoch, if its render retired normally while the slot was still + /// bound to it, it belongs to `vm` and was exposed (its InitBM ran). InitBM binds the + /// device-wide slot to one epoch and VM; a fresh epoch handed to the slot rebinds it, so + /// the owner is then stale and the render starts fresh. Adds no reference beyond the owner + /// lease itself. pub(crate) fn reusable(&self, k: usize, vm: &Arc) -> Option> { - if !*self.keep.get(k)? { + if *self.quarantined.get(k)? || !*self.keep.get(k)? { return None; } let owner = self.owners.get(k)?.as_ref()?; (Arc::ptr_eq(&owner._vm, vm) && owner.exposed.load(Ordering::Acquire)) .then(|| owner.clone()) } + /// Selects the physical PB/UMA allocator slot (`0` or `1`) for `vm`. + /// + /// When `behind` is true (pipelining behind in-flight same-VM renders), the active slot must + /// be healthy and reusable for `vm`. When `behind` is false (engine drained), a same-VM + /// render stays on its reusable active slot; otherwise it switches to the alternate slot + /// only once that alternate is fresh or displaced by a clean retirement of the active slot. + #[allow(dead_code)] + pub(crate) fn pick_slot(&self, vm: &Arc, behind: bool) -> Option { + if behind { + let a = self.active?; + return (!self.quarantined[a] && self.reusable(a, vm).is_some()).then_some(a); + } + match self.active { + None => (!self.quarantined[0]) + .then_some(0) + .or_else(|| (!self.quarantined[1]).then_some(1)), + Some(a) => { + if !self.quarantined[a] && self.reusable(a, vm).is_some() { + return Some(a); + } + let other = 1 - a; + let displaced = + self.owners[other].is_none() || self.last_clean_retired == Some(a); + (!self.quarantined[other] && displaced).then_some(other) + } + } + } + /// Whether `vm` can pipeline another render behind the currently active same-VM renders. + #[allow(dead_code)] + pub(crate) fn can_pipeline(&self, vm: &Arc) -> bool { + self.pick_slot(vm, true).is_some() + } + /// Whether no allocator slot can ever accept another render (even after draining). + #[allow(dead_code)] + pub(crate) fn exhausted(&self) -> bool { + if self.inflight != [0, 0] { + return false; + } + if self.quarantined[0] && self.quarantined[1] { + return true; + } + match self.active { + None => false, + Some(a) => { + let other = 1 - a; + let can_reuse_active = !self.quarantined[a] + && self.keep[a] + && self.owners[a] + .as_ref() + .is_some_and(|o| o.exposed.load(Ordering::Acquire)); + let can_switch_other = !self.quarantined[other] + && (self.owners[other].is_none() || self.last_clean_retired == Some(a)); + !can_reuse_active && !can_switch_other + } + } + } + /// Whether no allocator slot can accept a render for `vm` once the engine is drained. + /// + /// When one slot is quarantined and the surviving slot is owned by another VM, the global + /// render class stays alive for that owner while other VMs must be cancelled immediately + /// instead of spinning on `EAGAIN` until the administrative publication deadline fails the GPU. + #[allow(dead_code)] + pub(crate) fn exhausted_for(&self, vm: &Arc) -> bool { + self.inflight == [0, 0] && self.pick_slot(vm, false).is_none() + } + /// Retains the candidate VM and render arena (holding the `PoolSet` UMA descriptors) before + /// publication visibility. + #[allow(dead_code)] + pub(crate) fn hold_alloc( + &mut self, + k: usize, + vm: &Arc, + arena: Option>, + ) -> Result { + if k >= 2 || self.quarantined[k] { + return Err(EINVAL); + } + self.pending_vms[k] = Some(vm.clone()); + self.pending_arenas[k] = arena; + Ok(()) + } + /// Cancels unpublished candidate retention for allocator slot `k`. + #[allow(dead_code)] + pub(crate) fn cancel_alloc(&mut self, k: usize) { + if k < 2 { + self.pending_vms[k] = None; + self.pending_arenas[k] = None; + } + } + /// Records a render reaching firmware visibility on allocator slot `k`. + #[allow(dead_code)] + pub(crate) fn publish_flight(&mut self, k: usize) { + if k < 2 { + self.active = Some(k); + self.inflight[k] = self.inflight[k].saturating_add(1); + } + } + /// Retires one render flight on allocator slot `k` after a full normal receipt. + #[allow(dead_code)] + pub(crate) fn retire_flight( + &mut self, + k: usize, + epoch: &Arc, + binding: u64, + completed: bool, + ) -> Result { + if k >= 2 { + return Err(EINVAL); + } + self.inflight[k] = self.inflight[k].saturating_sub(1); + if self.quarantined[k] { + return Ok(()); + } + self.owners[k] = Some(epoch.clone()); + if let Some(vm) = self.pending_vms[k].take() { + self.owner_vms[k] = Some(vm); + } + if let Some(arena) = self.pending_arenas[k].take() { + self.owner_arenas[k] = Some(arena); + } + self.last_clean_retired = Some(k); + self.retire_epoch(k, binding, completed); + Ok(()) + } + /// Quarantines allocator slot `k` permanently after a passed abort, retaining all leases. + #[allow(dead_code)] + pub(crate) fn quarantine_flight(&mut self, k: usize) { + if k < 2 { + self.inflight[k] = self.inflight[k].saturating_sub(1); + self.quarantined[k] = true; + self.keep[k] = false; + } + } /// Slot `k` is handed to a render's epoch, `reused` or fresh (with InitBM). Returns the /// binding the render retires with. pub(crate) fn bind(&mut self, k: usize, reused: bool) -> u64 { @@ -319,17 +488,15 @@ impl Pools { /// A render on slot `k` with `binding` retired, after its `retire_binding`. If no other /// epoch was bound and no recovery started since, the next render of the same VM may reuse /// its epoch after a `completed` render; after a failed one it starts fresh. - /// Renders are bound, published and retired one at a time (`sizes::FLIGHTS` is 1, enforced - /// in `Engine::new`), so `keep[k]` always refers to the epoch the slot is bound to: - /// `owners[k]`. pub(crate) fn retire_epoch(&mut self, k: usize, binding: u64, completed: bool) { if self.binds.get(k) == Some(&binding) { if let Some(keep) = self.keep.get_mut(k) { - *keep = completed; + *keep = completed && !self.quarantined[k]; } } } /// Reuse nothing on slot `k` (its render was aborted). + #[allow(dead_code)] pub(crate) fn forget(&mut self, k: usize) { if let Some(keep) = self.keep.get_mut(k) { *keep = false; @@ -343,6 +510,7 @@ impl Pools { *keep = false; } } + #[allow(dead_code)] pub(crate) fn retire_binding(&mut self, k: usize, epoch: &Arc) -> Result { *self.owners.get_mut(k).ok_or(EINVAL)? = Some(epoch.clone()); Ok(()) diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index c7461db6b643e..98165ef4abe69 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -79,6 +79,12 @@ impl ComputeArena { } } +/// Render pass slots every VM gets with its first render command; extension slots +/// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are added lazily once it submits renders +/// back to back. +pub(crate) const BASE_RENDER_SLOTS: usize = 2; +const EXT_RENDER_SLOTS: usize = super::hw::sizes::RENDER_SLOTS - BASE_RENDER_SLOTS; + pub(crate) struct RenderArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderArena { type Target = RenderInner; @@ -89,8 +95,8 @@ impl core::ops::Deref for RenderArena { pub(crate) struct RenderInner { pub(crate) passes: KVec, pub(crate) pools: PoolSet, - pub(crate) tpc_dirty: [AtomicU64; 2], - pub(crate) tilemap_dirty: [AtomicU64; 2], + pub(crate) tpc_dirty: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) tilemap_dirty: [AtomicU64; BASE_RENDER_SLOTS], _objects: Objects, _bind: mmu::VmBind, _live: Arc, @@ -103,9 +109,9 @@ impl RenderArena { live: &Arc, ) -> Result> { let mut objects = factory.objects(vm); - let mut passes = KVec::with_capacity(2, GFP_KERNEL)?; - for k in 0..2 { - passes.push(PassSlot::new(&mut objects, k, 1)?, GFP_KERNEL)?; + let mut passes = KVec::with_capacity(BASE_RENDER_SLOTS, GFP_KERNEL)?; + for k in 0..BASE_RENDER_SLOTS { + passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; } let pools = PoolSet::new(&mut objects)?; objects.finish_private()?; @@ -113,8 +119,8 @@ impl RenderArena { Self(crate::cleanup::Deferred::new(RenderInner { passes, pools, - tpc_dirty: [const { AtomicU64::new(0) }; 2], - tilemap_dirty: [const { AtomicU64::new(0) }; 2], + tpc_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + tilemap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -133,15 +139,72 @@ impl RenderArena { } } +/// Extension render pass slots (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`), allocated lazily +/// for VMs that submit renders back to back so idle or single-pass VMs keep only the two base +/// pass slots. +pub(crate) struct RenderExtArena(crate::cleanup::Deferred); +impl core::ops::Deref for RenderExtArena { + type Target = RenderExtInner; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +pub(crate) struct RenderExtInner { + pub(crate) passes: KVec, + pub(crate) tpc_dirty: [AtomicU64; EXT_RENDER_SLOTS], + pub(crate) tilemap_dirty: [AtomicU64; EXT_RENDER_SLOTS], + _objects: Objects, + _bind: mmu::VmBind, + _live: Arc, +} +impl RenderExtArena { + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + ) -> Result> { + let mut objects = factory.objects(vm); + let mut passes = KVec::with_capacity(EXT_RENDER_SLOTS, GFP_KERNEL)?; + for k in BASE_RENDER_SLOTS..super::hw::sizes::RENDER_SLOTS { + passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; + } + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(RenderExtInner { + passes, + tpc_dirty: [const { AtomicU64::new(0) }; EXT_RENDER_SLOTS], + tilemap_dirty: [const { AtomicU64::new(0) }; EXT_RENDER_SLOTS], + _objects: objects, + _bind: bind.clone(), + _live: live.clone(), + })?), + GFP_KERNEL, + )?) + } +} + +/// Keeps the arena owning a retained pass slot alive through displacement. +#[derive(Clone)] +pub(crate) enum PassOwnerArena { + Base(Arc), + Ext(Arc), +} + #[derive(Default)] struct Ready { compute: Option>, /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. compute_ext: Option>, render: Option>, + /// Pass slots from [`BASE_RENDER_SLOTS`] on, for a VM that keeps renders queued. + render_ext: Option>, /// Last compute submission and the back-to-back run it continues. last_compute_ns: u64, burst: u32, + /// Last render submission and the back-to-back run it continues. + last_render_ns: u64, + render_burst: u32, } struct Standby { /// Never-exposed epochs kept on standby for this VM's queued renders. @@ -297,6 +360,7 @@ impl Cache { ready.compute.take(), ready.compute_ext.take(), ready.render.take(), + ready.render_ext.take(), ) }; drop(ready); @@ -318,7 +382,7 @@ impl Cache { .count() .try_into()?; let render = render_count != 0; - let (compute, compute_ext, render) = { + let (compute, compute_ext, render, render_ext) = { // Never held by publication, completion, recovery or fence signalling. // Serializing standby top-up under `ready` prevents concurrent SUBMITs on the // same VM from over-allocating or racing each other's deficit calculation. @@ -369,6 +433,23 @@ impl Cache { )?); } if render { + // SAFETY: ktime_get has no preconditions. + let now = unsafe { kernel::bindings::ktime_get() } as u64; + ready.render_burst = if now.wrapping_sub(ready.last_render_ns) < BURST_GAP_NS { + ready.render_burst.saturating_add(1) + } else { + 0 + }; + ready.last_render_ns = now; + if ready.render_ext.is_none() + && EXT_RENDER_SLOTS != 0 + && (ready.render_burst >= BURST_SUBMITS + || render_count as usize >= BURST_COMMANDS) + { + // Best effort: without extension slots the VM keeps two base pass slots. + ready.render_ext = + RenderExtArena::new(&self.factory, &self.bind, &vm.vm, &self.live).ok(); + } if render_count > super::budget::LIMIT { return Err(E2BIG); } @@ -454,14 +535,16 @@ impl Cache { if compute { ready.compute.clone() } else { None }, if compute { ready.compute_ext.clone() } else { None }, if render { ready.render.clone() } else { None }, + if render { ready.render_ext.clone() } else { None }, ) }; Ok(Prepared { compute, compute_ext, render, + render_ext, unpublished_renders: AtomicU32::new(render_count), - cache: render.is_some().then(|| self.clone()), + cache: (render_count != 0).then(|| self.clone()), }) } } @@ -472,6 +555,8 @@ pub(crate) struct Prepared { /// The VM's extension compute units when the job was prepared. pub(crate) compute_ext: Option>, pub(crate) render: Option>, + /// The VM's extension render pass slots when the job was prepared. + pub(crate) render_ext: Option>, /// Render commands of this job whose standby reservation has not yet been committed. unpublished_renders: AtomicU32, /// The VM cache holding the standby PB epoch pool. @@ -505,10 +590,61 @@ impl Prepared { self.compute_ext.clone() } } - /// The render arena. + /// The base render arena (owning the PB/UMA `PoolSet`). pub(crate) fn render_arena(&self) -> Option> { self.render.clone() } + /// Render pass slots this job can use. + pub(crate) fn render_passes(&self) -> Result { + Ok(self.render()?.passes.len() + + self.render_ext.as_deref().map_or(0, |e| e.passes.len())) + } + /// Render pass slot `k`: the VM's base slots, then its extension slots. + pub(crate) fn render_pass(&self, k: usize) -> Result<&PassSlot> { + let base = &self.render()?.passes; + match base.get(k) { + Some(pass) => Ok(pass), + None => self + .render_ext + .as_deref() + .and_then(|e| e.passes.get(k - base.len())) + .ok_or(EINVAL), + } + } + /// The dirty high-water marks (`tpc_dirty`, `tilemap_dirty`) for pass slot `k`. + pub(crate) fn render_pass_dirty(&self, k: usize) -> Result<(&AtomicU64, &AtomicU64)> { + let base = self.render()?; + if k < base.passes.len() { + Ok((&base.tpc_dirty[k], &base.tilemap_dirty[k])) + } else { + let ext = self.render_ext.as_deref().ok_or(EINVAL)?; + let idx = k - base.passes.len(); + if idx >= ext.passes.len() { + return Err(EINVAL); + } + Ok((&ext.tpc_dirty[idx], &ext.tilemap_dirty[idx])) + } + } + /// Updates dirty high-water marks for pass slot `k` (base or extension). + pub(crate) fn set_pass_dirty(&self, k: usize, tpc: u64, tilemap: u64) -> Result { + let pass = self.render_pass(k)?; + if tpc > pass.tpc.size as u64 || tilemap > pass.tilemap.size as u64 { + return Err(E2BIG); + } + let (tpc_dirty, tilemap_dirty) = self.render_pass_dirty(k)?; + tpc_dirty.fetch_max(tpc, Ordering::Relaxed); + tilemap_dirty.fetch_max(tilemap, Ordering::Relaxed); + Ok(()) + } + /// The arena owning render pass slot `k`. + pub(crate) fn pass_owner_arena(&self, k: usize) -> Option { + let base = self.render.as_ref()?; + if k < base.passes.len() { + Some(PassOwnerArena::Base(base.clone())) + } else { + self.render_ext.as_ref().map(|e| PassOwnerArena::Ext(e.clone())) + } + } /// Compute unit `k`: the VM's base units, then its extension units. pub(crate) fn compute_unit(&self, k: usize) -> Result<&ComputeSlot> { let base = &self.compute()?.compute; diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index b345b944197c5..ba26665434302 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -131,6 +131,7 @@ pub(crate) struct PassSlot { pub(crate) tilemap: Arc, pub(crate) heap: Arc, pub(crate) scene_user: Arc, + pub(crate) scene_list: Arc, pub(crate) fs_scratch: Arc, pub(crate) fs_work: Arc, pub(crate) ta_work: Arc, @@ -218,6 +219,14 @@ impl PassSlot { 0, false, )?; + let scene_list = alloc( + o, + super::fw::buffer::SCENE_LIST_SIZE, + sh, + Client::nc(client::SCENE_LIST + ps), + 0, + false, + )?; let fs_scratch = alloc( o, 0x10000, @@ -245,6 +254,7 @@ impl PassSlot { tilemap, heap, scene_user, + scene_list, fs_scratch, fs_work, ta_work, @@ -306,6 +316,8 @@ impl PassSlot { self.aux.fill(0, 0, 0x20000)?; self.heap.fill(0, 0, 0x4000)?; self.scene_user.fill(0, 0, 0x10000)?; + self.scene_list + .fill(0, 0, super::fw::buffer::SCENE_LIST_SIZE)?; // Preemption save areas start zeroed on every full reset. self.pre[0].fill(0, 0, 0x4000)?; self.pre[1].fill(0, 0, 0x4000)?; @@ -328,6 +340,7 @@ impl PassSlot { tilemap_gva: self.tilemap.gva.unwrap_or(0), heap_gva: self.heap.gva.unwrap_or(0), scene_user_gva: self.scene_user.gva.unwrap_or(0), + scene_list: self.scene_list.gva.unwrap_or(0), pre_gva: [ self.pre[0].gva.unwrap_or(0), self.pre[1].gva.unwrap_or(0), @@ -411,25 +424,33 @@ pub(crate) struct ComputeOwners { scrub_full: [bool; sizes::COMPUTE_UNITS], } +/// Bitmask of valid render pass slot indices (`0..sizes::RENDER_SLOTS`). +const PASS_MASK: u32 = (1u32 << sizes::RENDER_SLOTS) - 1; + +/// Displacement ledger and VM leases of the render pass slots (see [`Slots`]). +pub(crate) struct RenderOwners { + lifetime: Lifetime<{ sizes::RENDER_SLOTS }>, + // Last-owner leases remain bound through retirement and displacement. Replaced only + // when the displaced unit is safely rebound to a new publication. + owner: [Option>; sizes::RENDER_SLOTS], + pending_retarget: [Option; sizes::RENDER_SLOTS], + pending_owner: [Option>; sizes::RENDER_SLOTS], + /// The render arena (base or extension) holding each pass slot's owner. + arena: [Option; sizes::RENDER_SLOTS], + pending_arena: [Option; sizes::RENDER_SLOTS], + /// Force a full scrub on next pass claim (first use, cancel, error, or firmware recovery). + scrub_full: [bool; sizes::RENDER_SLOTS], +} + pub(crate) struct Slots { pub(crate) cursor: u32, pub(crate) pass_busy: u32, pub(crate) pass_cursor: u32, pub(crate) stats: SlotStats, - /// The compute owners, on the heap: `Firmware` (and so `Slots`) is built on the probe's - /// stack, which has no room for it. + /// The compute and render owners, on the heap: `Firmware` (and so `Slots`) is built on the + /// probe's stack, which has no room for them. compute: KBox, - pass_lifetime: Lifetime<2>, - // Last-owner leases remain bound through retirement and displacement. Replaced only - // when the displaced unit is safely rebound to a new publication. - pass_owner: [Option>; 2], - pending_pass_retarget: [Option; 2], - pending_pass_owner: [Option>; 2], - /// The render arena of each pass slot's owner (see [`ComputeOwners::arena`]). - pass_arena: [Option>; 2], - pending_pass_arena: [Option>; 2], - /// Force a full scrub on next pass claim (first use, cancel, error, or firmware recovery). - pass_scrub_full: [bool; 2], + render: KBox, } impl Slots { pub(crate) fn new() -> Result { @@ -450,13 +471,18 @@ impl Slots { }, GFP_KERNEL, )?, - pass_lifetime: Lifetime::new(false), - pass_owner: [None, None], - pending_pass_retarget: [None, None], - pending_pass_owner: [None, None], - pass_arena: [None, None], - pending_pass_arena: [None, None], - pass_scrub_full: [true; 2], + render: KBox::new( + RenderOwners { + lifetime: Lifetime::new(true), + owner: [const { None }; sizes::RENDER_SLOTS], + pending_retarget: [None; sizes::RENDER_SLOTS], + pending_owner: [const { None }; sizes::RENDER_SLOTS], + arena: [const { None }; sizes::RENDER_SLOTS], + pending_arena: [const { None }; sizes::RENDER_SLOTS], + scrub_full: [true; sizes::RENDER_SLOTS], + }, + GFP_KERNEL, + )?, }) } pub(crate) fn init(&self) -> Result { @@ -471,10 +497,10 @@ impl Slots { } #[allow(dead_code)] pub(crate) fn pass_generation(&self, k: usize) -> Result { - if k >= 2 { + if k >= sizes::RENDER_SLOTS { return Err(EINVAL); } - Ok(self.pass_lifetime.generation(k)) + Ok(self.render.lifetime.generation(k)) } pub(crate) fn compute_exhausted(&self) -> bool { // Ledger indices above the most units a VM gets never have an owner. @@ -487,19 +513,34 @@ impl Slots { self.compute.lifetime.exhausted_within(n) } pub(crate) fn render_exhausted(&self) -> bool { - self.pass_lifetime.exhausted() + self.render.lifetime.exhausted() + } + /// Whether none of the first `n` render pass slots (a VM's own) can ever be claimed again. + pub(crate) fn render_exhausted_within(&self, n: usize) -> bool { + self.render.lifetime.exhausted_within(n) } pub(crate) fn lifetime_counts(&self) -> [super::pools::lifetime::Counts; 2] { - [self.compute.lifetime.counts(), self.pass_lifetime.counts()] + [self.compute.lifetime.counts(), self.render.lifetime.counts()] } /// Whether one of the first `n` compute units can be claimed now. pub(crate) fn compute_available(&self, n: usize) -> bool { (0..n.min(sizes::COMPUTE_UNITS)).any(|k| self.compute.lifetime.available(k)) } + /// Whether one of the first `n` render pass slots can be claimed now. + #[allow(dead_code)] + pub(crate) fn pass_available(&self, n: usize) -> bool { + (0..n.min(sizes::RENDER_SLOTS)) + .any(|k| self.pass_busy & (1 << k) == 0 && self.render.lifetime.available(k)) + } /// Compute units published and not yet retired. pub(crate) fn compute_published(&self) -> u32 { self.compute.lifetime.published() } + /// Render pass slots published and not yet retired. + #[allow(dead_code)] + pub(crate) fn render_published(&self) -> u32 { + self.render.lifetime.published() + } #[allow(dead_code)] pub(crate) fn free_compute(&self) -> u32 { (0..super::params::compute_units()) @@ -510,7 +551,7 @@ impl Slots { #[allow(dead_code)] pub(crate) fn invalidate_scrub(&mut self) { self.compute.scrub_full = [true; sizes::COMPUTE_UNITS]; - self.pass_scrub_full = [true; 2]; + self.render.scrub_full = [true; sizes::RENDER_SLOTS]; } /// Forces a full scrub on the next claim of the units in `f` (after an affected error). @@ -521,9 +562,9 @@ impl Slots { *dirty = true; } } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { - self.pass_scrub_full[k] = true; + self.render.scrub_full[k] = true; } } } @@ -571,17 +612,42 @@ impl Slots { } Ok(None) } + #[allow(dead_code)] pub(crate) fn pick_pass( &self, arena: &super::resources::RenderArena, geo: &Geometry, picked: u32, ) -> Option { - for i in 0..2 { - let k = (self.pass_cursor as usize + i) % 2; + let n = arena.passes.len().min(sizes::RENDER_SLOTS); + for i in 0..n { + let k = (self.pass_cursor as usize + i) % n; let p = &arena.passes[k]; if (self.pass_busy | picked) & (1 << k) == 0 - && self.pass_lifetime.available(k) + && self.render.lifetime.available(k) + && geo.tpc_bytes <= p.tpc.size as u64 + && geo.tilemap_bytes <= p.tilemap.size as u64 + { + return Some(k); + } + } + None + } + #[allow(dead_code)] + pub(crate) fn pick_pass_in( + &self, + resources: &super::resources::Prepared, + geo: &Geometry, + picked: u32, + ) -> Option { + let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); + for i in 0..n { + let k = (self.pass_cursor as usize + i) % n; + let Ok(p) = resources.render_pass(k) else { + continue; + }; + if (self.pass_busy | picked) & (1 << k) == 0 + && self.render.lifetime.available(k) && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 { @@ -595,18 +661,24 @@ impl Slots { self.claim_pass_for(arena, k, None) } + #[allow(dead_code)] pub(crate) fn claim_pass_for( &mut self, arena: &super::resources::RenderArena, k: usize, vm_id: Option, ) -> Result { - if k >= 2 || !self.pass_lifetime.claim(k) { + let n = arena.passes.len().min(sizes::RENDER_SLOTS); + if k >= n || !self.render.lifetime.claim(k) { return Err(EBUSY); } // Only a retired displaced owner may reach here; no in-flight storage is reset. - let full = self.pass_scrub_full[k] - || vm_id.is_none_or(|id| self.pass_owner[k].as_ref().is_none_or(|prev| prev.id != id)); + let full = self.render.scrub_full[k] + || vm_id.is_none_or(|id| { + self.render.owner[k] + .as_ref() + .is_none_or(|prev| prev.id != id) + }); let p = &arena.passes[k]; if let Err(e) = p.scrub( 1, @@ -615,14 +687,51 @@ impl Slots { full, &mut self.stats, ) { - self.pass_lifetime.cancel(k); + self.render.lifetime.cancel(k); return Err(e); } if full { arena.tpc_dirty[k].store(0, Ordering::Relaxed); } arena.tilemap_dirty[k].store(0, Ordering::Relaxed); - self.pass_cursor = (1 - k) as u32; + self.pass_cursor = ((k + 1) % n) as u32; + Ok(()) + } + + #[allow(dead_code)] + pub(crate) fn claim_pass_in( + &mut self, + resources: &super::resources::Prepared, + k: usize, + vm_id: Option, + ) -> Result { + let n = resources.render_passes()?.min(sizes::RENDER_SLOTS); + if k >= n || !self.render.lifetime.claim(k) { + return Err(EBUSY); + } + let full = self.render.scrub_full[k] + || vm_id.is_none_or(|id| { + self.render.owner[k] + .as_ref() + .is_none_or(|prev| prev.id != id) + }); + let p = resources.render_pass(k)?; + let (tpc_dirty, tilemap_dirty) = resources.render_pass_dirty(k)?; + if let Err(e) = p.scrub( + 1, + tpc_dirty.load(Ordering::Relaxed), + tilemap_dirty.load(Ordering::Relaxed), + full, + &mut self.stats, + ) { + self.render.lifetime.cancel(k); + return Err(e); + } + if full { + tpc_dirty.store(0, Ordering::Relaxed); + } + tilemap_dirty.store(0, Ordering::Relaxed); + self.pass_cursor = ((k + 1) % n) as u32; Ok(()) } #[allow(dead_code)] @@ -655,9 +764,9 @@ impl Slots { self.stats.last_retarget[0] = proof; } } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { - if let Some(proof) = self.pending_pass_retarget[k].take() { + if let Some(proof) = self.render.pending_retarget[k].take() { self.stats.cross_vm_retargets[1] = self.stats.cross_vm_retargets[1].saturating_add(1); self.stats.last_retarget[1] = proof; @@ -673,7 +782,7 @@ impl Slots { || f.slot[..f.slot_count as usize] .iter() .any(|&k| k as usize >= sizes::COMPUTE_UNITS) - || f.pass_mask & !3 != 0 + || f.pass_mask & !PASS_MASK != 0 { return Err(EINVAL); } @@ -684,12 +793,12 @@ impl Slots { .and_then(|old| Self::vm_retarget(k, old, vm)); self.compute.pending_owner[k] = Some(vm.clone()); } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { - self.pending_pass_retarget[k] = self.pass_owner[k] + self.render.pending_retarget[k] = self.render.owner[k] .as_ref() .and_then(|old| Self::vm_retarget(k, old, vm)); - self.pending_pass_owner[k] = Some(vm.clone()); + self.render.pending_owner[k] = Some(vm.clone()); } } Ok(()) @@ -703,9 +812,9 @@ impl Slots { *cell = resources.compute_arena(k as usize); } } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { - self.pending_pass_arena[k] = resources.render_arena(); + self.render.pending_arena[k] = resources.pass_owner_arena(k); } } } @@ -714,47 +823,47 @@ impl Slots { pub(crate) fn publish(&mut self, f: &Claims) -> Result { // Validate on a private copy so a failure changes no ownership. let mut c = self.compute.lifetime.clone(); - let mut p = self.pass_lifetime.clone(); + let mut p = self.render.lifetime.clone(); for &k in &f.slot[..f.slot_count as usize] { if !c.publish(k as usize) { return Err(EBUSY); } } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 && !p.publish(k) { return Err(EBUSY); } } self.compute.lifetime = c; - self.pass_lifetime = p; + self.render.lifetime = p; Ok(()) } /// Full wire retirement is a precondition; completion fences alone are insufficient. pub(crate) fn retire(&mut self, f: &mut Claims) -> Result { let mut c = self.compute.lifetime.clone(); - let mut p = self.pass_lifetime.clone(); + let mut p = self.render.lifetime.clone(); for &k in &f.slot[..f.slot_count as usize] { if !c.retire(k as usize) { return Err(EINVAL); } } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 && !p.retire(k) { return Err(EINVAL); } } self.compute.lifetime = c; - self.pass_lifetime = p; + self.render.lifetime = p; for &k in &f.slot[..f.slot_count as usize] { self.compute.owner[k as usize] = self.compute.pending_owner[k as usize].take(); self.compute.arena[k as usize] = self.compute.pending_arena[k as usize].take(); self.compute.scrub_full[k as usize] = false; } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { - self.pass_owner[k] = self.pending_pass_owner[k].take(); - self.pass_arena[k] = self.pending_pass_arena[k].take(); - self.pass_scrub_full[k] = false; + self.render.owner[k] = self.render.pending_owner[k].take(); + self.render.arena[k] = self.render.pending_arena[k].take(); + self.render.scrub_full[k] = false; } } self.pass_busy &= !f.pass_mask; @@ -769,11 +878,11 @@ impl Slots { self.compute.pending_retarget[k as usize] = None; self.compute.scrub_full[k as usize] = true; } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { - self.pass_lifetime.quarantine(k); - self.pending_pass_retarget[k] = None; - self.pass_scrub_full[k] = true; + self.render.lifetime.quarantine(k); + self.render.pending_retarget[k] = None; + self.render.scrub_full[k] = true; } } self.pass_busy &= !f.pass_mask; @@ -790,13 +899,13 @@ impl Slots { self.compute.pending_arena[k as usize] = None; self.compute.scrub_full[k as usize] = true; } - for k in 0..2 { + for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { - self.pass_lifetime.cancel(k); - self.pending_pass_retarget[k] = None; - self.pending_pass_owner[k] = None; - self.pending_pass_arena[k] = None; - self.pass_scrub_full[k] = true; + self.render.lifetime.cancel(k); + self.render.pending_retarget[k] = None; + self.render.pending_owner[k] = None; + self.render.pending_arena[k] = None; + self.render.scrub_full[k] = true; } } self.pass_busy &= !f.pass_mask; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs index cbe759e73feb5..d93aa65b30fee 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs @@ -77,6 +77,17 @@ fn main() { for i in 0..ta.len(){if !(0x90f..0x917).contains(&i){assert_eq!(ta[i],ta_separate[i],"TA unrelated byte {i:#x}");}} for i in 0..fs.len(){if !(0xc57..0xc5f).contains(&i){assert_eq!(fs[i],fs_separate[i],"FS unrelated byte {i:#x}");}} assert_eq!(tq,tq_separate);assert_eq!(fq,fq_separate); + let mut p_sl=p;p_sl.scene_list=g+0x540000; + let mut ta_sl=[0xa5;fw::work::ta::WORK_SIZE];let mut fs_sl=[0xa5;fw::work::fs::WORK_SIZE]; + let mut tq_sl=[0xa5;fw::work::ta::SEQ_SIZE];let mut fq_sl=[0xa5;fw::work::fs::SEQ_SIZE]; + encode::encode_ta(&r,&p_sl,&u,&[0;4],ctx,target,&geo,None,&mut ta_sl,&mut tq_sl); + encode::encode_fs(&r,&p_sl,&u,&[0;4],ctx,1<<40,1,target,&geo,&mut fs_sl,&mut fq_sl); + let mut scene_r=vec![0xa5;fw::work::scene::SIZE]; + let mut scene_p=vec![0xa5;fw::work::scene::SIZE]; + encode::fill_scene(&r,&p,&mut scene_r);encode::fill_scene(&r,&p_sl,&mut scene_p); + assert_ne!(ta,ta_sl);assert_ne!(fs,fs_sl);assert_ne!(scene_r,scene_p); + assert_ne!(&scene_r[0x28..0x30],&scene_p[0x28..0x30]); + assert_eq!(tq,tq_sl);assert_eq!(fq,fq_sl); for engine in 0..2 { let att:Vec<_>=(0..counts[v][engine]).map(|i|uapi::drm_asahi_attachment {pointer:g+0x50000000+i as u64*0x10000+v as u64*13,size:(i as u64+1)*137,..Default::default()}).collect(); encode::render_attachments(if engine==0{&mut tq[..]}else{&mut fq[..]},engine,&att); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 12f9d498866c9..a4dd5e322e2ab 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -126,7 +126,7 @@ def module(text, name): } pub mod encode { pub struct Geometry{pub tpc_bytes:u64,pub tilemap_bytes:u64} - pub struct PassRefs{pub ta_work:u64,pub ta_work_gva:u64,pub fs_work:u64,pub fs_work_gva:u64,pub ta_seq:u64,pub fs_seq:u64,pub scene:u64,pub tpc_gva:u64,pub tilemap_gva:u64,pub heap_gva:u64,pub scene_user_gva:u64,pub pre_gva:[u64;3],pub fs_scratch_gva:u64,pub aux_gva:u64,pub its:u64,pub ta_scratch:u64,pub tpc_fw:u64,pub scratch_fw:u64} + pub struct PassRefs{pub ta_work:u64,pub ta_work_gva:u64,pub fs_work:u64,pub fs_work_gva:u64,pub ta_seq:u64,pub fs_seq:u64,pub scene:u64,pub tpc_gva:u64,pub tilemap_gva:u64,pub heap_gva:u64,pub scene_user_gva:u64,pub scene_list:u64,pub pre_gva:[u64;3],pub fs_scratch_gva:u64,pub aux_gva:u64,pub its:u64,pub ta_scratch:u64,pub tpc_fw:u64,pub scratch_fw:u64} } pub mod vm { use crate::{mmu,sync::Arc};use core::sync::atomic::Ordering; @@ -149,13 +149,19 @@ def module(text, name): pub struct ComputeArena{pub compute:KVec} // A job's compute units; here one arena. pub type Prepared=ComputeArena; + #[derive(Clone)] + pub enum PassOwnerArena{Base(crate::sync::Arc)} impl ComputeArena{ pub fn compute_units(&self)->Result{Ok(self.compute.len())} pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{self.compute.get(k).ok_or(EINVAL)} pub fn compute_arena(&self,_k:usize)->Option>{None} pub fn render_arena(&self)->Option>{None} + pub fn render_passes(&self)->Result{Err(EINVAL)} + pub fn render_pass(&self,_k:usize)->Result<&super::slots::PassSlot>{Err(EINVAL)} + pub fn render_pass_dirty(&self,_k:usize)->Result<(&AtomicU64,&AtomicU64)>{Err(EINVAL)} + pub fn pass_owner_arena(&self,_k:usize)->Option{None} } - pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;2],pub tilemap_dirty:[AtomicU64;2]} + pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;8],pub tilemap_dirty:[AtomicU64;8]} impl RenderArena{ __SET_DIRTY__ } } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} @@ -173,7 +179,7 @@ def module(text, name): fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} - Arenas{compute:g16::resources::ComputeArena{compute},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};2],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};2]}} + Arenas{compute:g16::resources::ComputeArena{compute},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};8],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};8]}} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<=0x7000000000 && base+a.mapped as u64<=0x7100000000); + // Must stay disjoint from the dynamic client range 0x7040000000..0x7080000000. + assert!(base+a.mapped as u64<=0x7040000000 || base>=0x7080000000, + "overlap with dynamic client range: {:#x}..{:#x}", base, base+a.mapped as u64); + aliases.push((base,base+a.mapped as u64)); + } + } + aliases.sort(); + for w in aliases.windows(2) { + assert!(w[0].1<=w[1].0,"overlap {:x?} {:x?}",w[0],w[1]); + } + } + + #[test]fn decoupled_pb_allocator_supports_same_vm_pipelining_cross_vm_displacement_and_abort(){ + let mut o=Objects::new();let pools=PoolSet::new(&mut o).unwrap(); + let vm1=vm(1);let vm2=vm(2);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let e1=g16::pools::PbEpoch::new(&factory,&vm1,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e1.prepare(0,0x70c0000000,2048).unwrap();e1.check_assignment(0).unwrap();e1.expose(); + let e2=g16::pools::PbEpoch::new(&factory,&vm2,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e2.prepare(1,0x70c0000000,2048).unwrap();e2.check_assignment(1).unwrap();e2.expose(); + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // Priming render on slot 0 (VM1). + assert_eq!(p.pick_slot(&vm1,false),Some(0)); + let b1=p.bind(0,false); + let a1=pools.prepare_in_flight(0,1,false).unwrap(); + assert_eq!(a1.uma_submitted,2); + pools.publish(0,2).unwrap();p.publish_flight(0); + let d0=o.objects.iter().find(|obj|obj.va==a1.uma_mgr[0]).unwrap(); + d0.w64(0x54,2).unwrap(); + p.retire_flight(0,&e1,b1,true).unwrap(); + // Same-VM pipelining: 3 concurrent renders share slot 0 with cumulative uma_submitted (4, 6, 8). + assert!(p.can_pipeline(&vm1)); + assert!(!p.can_pipeline(&vm2)); + for draw in 2..=4u64 { + assert_eq!(p.pick_slot(&vm1,draw>2),Some(0)); + let refs=pools.prepare_in_flight(0,draw,draw>2).unwrap(); + assert_eq!(refs.uma_submitted,draw*2); + pools.publish(0,refs.uma_submitted).unwrap(); + p.publish_flight(0); + } + assert!(!pools.retired_at(0,4).unwrap()); + d0.w64(0x54,4).unwrap(); + assert!(pools.retired_at(0,4).unwrap()); + assert!(!pools.retired_at(0,6).unwrap()); + p.retire_flight(0,&e1,b1,true).unwrap(); + d0.w64(0x54,6).unwrap(); + assert!(pools.retired_at(0,6).unwrap()); + p.retire_flight(0,&e1,b1,true).unwrap(); + d0.w64(0x54,8).unwrap(); + assert!(pools.retired(0).unwrap()); + p.retire_flight(0,&e1,b1,true).unwrap(); + // Cross-VM switch drains and switches to slot 1 (displacing slot 0 upon clean retirement). + assert_eq!(p.pick_slot(&vm2,false),Some(1)); + let b2=p.bind(1,false); + p.publish_flight(1); + p.retire_flight(1,&e2,b2,true).unwrap(); + assert!(!p.exhausted()); + // Aborted render on slot 0 after slot 1 was previously retired leaves slot 1 undisplaced + // and slot 0 quarantined -> global pool exhaustion. + assert_eq!(p.pick_slot(&vm1,false),Some(0)); + p.publish_flight(0); + p.quarantine_flight(0); + assert!(p.reusable(0,&vm1).is_none()); + assert_eq!(p.pick_slot(&vm1,false),None); + assert!(p.exhausted()); + assert!(p.exhausted_for(&vm1)); + + // Quarantine slot 0 while slot 1 is still fresh: VM2 claims and reuses slot 1, while + // other VMs report per-VM exhaustion without tripping global exhaustion until recovery. + let vm3=vm(3); + let mut q=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + assert_eq!(q.pick_slot(&vm1,false),Some(0)); + q.publish_flight(0); + q.quarantine_flight(0); + assert!(!q.exhausted()); + assert_eq!(q.pick_slot(&vm2,false),Some(1)); + let qb2=q.bind(1,false); + q.publish_flight(1); + assert!(!q.exhausted_for(&vm3)); // in-flight: waits for drain first + q.retire_flight(1,&e2,qb2,true).unwrap(); + assert!(!q.exhausted()); + assert!(!q.exhausted_for(&vm2)); + assert_eq!(q.pick_slot(&vm2,false),Some(1)); + assert!(q.exhausted_for(&vm1)); + assert!(q.exhausted_for(&vm3)); + // Recovery invalidates the surviving slot's epoch -> global pool exhaustion. + q.invalidate(); + assert!(q.exhausted()); + assert!(q.exhausted_for(&vm2)); + } + + #[test]fn pipelined_render_pass_slots_keep_seven_in_flight(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { + passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + } + let arena=g16::resources::RenderArena{ + passes, + tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};8], + tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};8], + }; + let a=vm(1); + let mut live:Vec=Vec::new(); + // Publish 7 concurrent passes in flight (slots 0..7). + for k in 0..7usize { + let mut c=Claims::new(); + c.pass[0]=k as u32;c.pass_mask=1< slot 0 is displaced and reusable while 5 others remain in flight. + s.retire(&mut live[0]).unwrap(); + assert!(!s.pass_available(7)); // slot 0 not displaced yet + s.retire(&mut live[1]).unwrap(); + assert!(s.pass_available(7)); // slot 0 displaced by slot 1! + for c in live.iter_mut().skip(2) { + s.retire(c).unwrap(); + } + assert_eq!(s.render_published(),0); + } + } ''' budget=(production/'budget.rs').read_text() diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py index 41a8c1a9dd217..fe522d3c800c5 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py @@ -43,18 +43,18 @@ def function(text, name): struct Graph{compute:CGraph,render:RGraph} struct Vm{slot:u32}struct Job{vm:Vm,resources:Resources} struct Resources{compute:Vec,passes:Vec,pools:Pools} -impl Resources{fn compute(&self)->Result<&Self>{Ok(self)}fn render(&self)->Result<&Self>{Ok(self)}fn compute_unit(&self,k:usize)->Result<&CUnit>{self.compute.get(k).ok_or(EINVAL)}} +impl Resources{fn compute(&self)->Result<&Self>{Ok(self)}fn render(&self)->Result<&Self>{Ok(self)}fn compute_unit(&self,k:usize)->Result<&CUnit>{self.compute.get(k).ok_or(EINVAL)}fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.get(k).ok_or(EINVAL)}} struct Claims{slot:[u32;1],pass:[u32;1]} -struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} -struct Engine{flights:Vec,target:u32} +struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],pb_slot:u32,uma_submitted:u64,recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} +struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32} fn stamp_reached(observed:u32,own:u32,tail:u32)->bool{logic::stamp_reached(observed,own,tail)} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} struct CUnit{counter:Object,its:Object,work:Object} struct RUnit{scene:Object} struct Scrub{compute:Vec,passes:Vec} struct Slots{scrub:Scrub} -struct Pools{full:bool} -impl Pools{fn retired(&self,_k:usize)->Result{Ok(self.full)}} +struct Pools{full:bool,completed:u64} +impl Pools{fn retired(&self,_k:usize)->Result{Ok(self.full)}fn retired_at(&self,_k:usize,target:u64)->Result{Ok(self.full && target!=0 && self.completed>=target)}} struct Firmware{graph:Graph,engine:Engine,slots:Slots,pools:Pools,queue_passed:bool} fn rmb(){}fn now_ns()->u64{100_000_000} impl Firmware{ @@ -70,9 +70,9 @@ def function(text, name): let mut f=Firmware{ graph:Graph{compute:CGraph{fw_stamp:Object::default(),qstate:Object::default(),qinfo:Object::default(),notifier:Object::default()}, render:RGraph{fw_stamp:Default::default(),qstate:Default::default(),qinfo:Default::default(),notifier:Object::default()}}, - engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true}}},claims:Claims{slot:[0],pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],recovery_suspect:false,recovery_started_ns:0,doomed:false}],target}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true,completed:2}}},claims:Claims{slot:[0],pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,recovery_suspect:false,recovery_started_ns:0,doomed:false}],target,ta_target:target,fs_target:target}, slots:Slots{scrub:Scrub{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}]}}, - pools:Pools{full:true},queue_passed:true, + pools:Pools{full:true,completed:2},queue_passed:true, }; f.graph.compute.fw_stamp.set(0,u64::from(target)); f.graph.compute.notifier.set(notifier_page::COMPUTE_STAMP,u64::from(target)); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py index 2abd69cf194e1..064f8b3921583 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -161,7 +161,7 @@ def function(source, marker): pub struct Scrub{pub compute:Vec,pub passes:Vec} pub struct Slots{pub scrub:Scrub}pub struct Firmware{pub slots:Slots} pub struct Resources{pub compute:Vec,pub passes:Vec} - impl Resources{pub fn compute(&self)->Result<&Self>{Ok(self)}pub fn render(&self)->Result<&Self>{Ok(self)}pub fn compute_unit(&self,k:usize)->Result<&Compute>{self.compute.get(k).ok_or(super::EINVAL)}} + impl Resources{pub fn compute(&self)->Result<&Self>{Ok(self)}pub fn render(&self)->Result<&Self>{Ok(self)}pub fn compute_unit(&self,k:usize)->Result<&Compute>{self.compute.get(k).ok_or(super::EINVAL)}pub fn render_pass(&self,k:usize)->Result<&Pass>{self.passes.get(k).ok_or(super::EINVAL)}} pub struct Job{pub commands:Vec,pub resources:Resources} pub struct Flight{pub job:Job,pub first:usize,pub count:usize,pub renders:u32} pub mod poll{use super::*;impl Firmware{ __RETIRE__ }} From fee0f3edbb4ddedb04bd8c469dcac1f51ba868f4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:47:43 -0500 Subject: [PATCH 14/19] drm/asahi: g16: enable multi-flight same-VM render pipelining, fragment barriers, and deeper queues Lift depth-1 render serialization so same-VM renders pipeline across PassSlot 0..RENDER_SLOTS while sharing the active exposed PB/UMA allocator slot, and remove remaining host-side queue-depth and wakeup-placement caps: - Allow same-engine render orders in Order::ready() to follow the queue's published render frontier while keeping cross-engine dependencies gated on full completion. - Extend Firmware::can_queue_behind() to admit healthy same-VM renders behind in-flight non-InitBM renders of the same VM (up to params::render_flights() = RENDER_SLOTS - 1), while still draining across VM switches, cross-engine transitions, InitBM priming renders, and error/recovery paths. - Emit explicit TA/FS hardware barriers in prefix_render() for queued renders: fragment-only or barrier-free renders overlap TA(N) with FS(N-1) (advertising DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS); full render barriers hold TA(N) on FS(N-1) in hardware. - Remove the render_busy skip in Shared::submit_locked() so queued renders publish immediately on submit, and extend queue_passed() and retired_snapshot() for in-order passed receipts across Channel::Ta, Channel::Fs, shared notifier stamps, and cumulative PoolSet::retired_at() UMA completion. - Bound clean same-VM tilemap scrubbing in Slots::claim_pass_in() to tilemap_dirty.min(current_tilemap_bytes) while retaining the high-water mark for larger subsequent passes and cross-VM/recovery full scrubs. - Raise FLIGHTS (16 -> 32), SCHEDULER_CREDITS (16 -> 32), AHEAD_RECORDS (64 -> 128), and params::compute_flights() (16 -> 32), give each logical queue's drm_sched a creator-cluster-restricted ordered reclaimable workqueue, and implement gpu::Gpu::syncobj_wait_hint() with a lock-free active-burst uclamp hint (matching G17). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 11 +- drivers/gpu/drm/asahi/g16/engine.rs | 112 ++++++++++++++---- drivers/gpu/drm/asahi/g16/hw.rs | 16 +-- drivers/gpu/drm/asahi/g16/job.rs | 21 +++- drivers/gpu/drm/asahi/g16/mod.rs | 31 ++++- drivers/gpu/drm/asahi/g16/params.rs | 16 ++- drivers/gpu/drm/asahi/g16/poll.rs | 63 +++++++--- drivers/gpu/drm/asahi/g16/slots.rs | 14 ++- .../gpu/asahi-m4/test-command-stream.py | 7 +- .../drivers/gpu/asahi-m4/test-publication.py | 90 ++++++++++++-- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 31 +++++ 11 files changed, 334 insertions(+), 78 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index ea6f6882eff6a..6d905e6354688 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -113,13 +113,12 @@ impl Order { /// Cross-engine historical dependencies end at the named prefix, even while later /// commands in that older submission remain pending. pub(crate) fn ready(&self, completed: [u64; 2], published: [u64; 2]) -> bool { - // Same-engine compute order and barriers are kept by the firmware compute queue, - // which finishes each command before it starts the next: its published frontier - // suffices. Renders, and every cross-engine dependency, need the completed one. + // Same-engine order and barriers are kept by the firmware engine rings (in-order + // CDM execution for compute, explicit TA/FS barriers for pipelined renders): the + // same-engine published frontier suffices. Every cross-engine dependency still waits + // for the other engine's completed frontier. let mut frontier = completed; - if self.engine == COMPUTE { - frontier[COMPUTE] = published[COMPUTE].max(completed[COMPUTE]); - } + frontier[self.engine] = published[self.engine].max(completed[self.engine]); frontier[self.engine].checked_add(1) == Some(self.sequence) && self .wait_through diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 6936b40afd35c..444dc69da3dce 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -956,38 +956,55 @@ impl Firmware { result } - /// Whether `job`'s next command may be published behind the flights in flight: it is a - /// healthy compute command whose dependencies are met, every flight is a healthy - /// compute-only prefix of the same VM, and the compute depth is below - /// [`params::compute_flights`]. Renders, another VM's commands and every failure path - /// need an empty engine: under several clients, compute queued behind another VM's - /// lost its writes and stalled the firmware compute queue. + /// Whether `job`'s next command may be published behind the flights in flight: /// - /// Timed compute commands pipeline freely: each flight owns a private `ComputeSlot` - /// (`its`/`work`) and `retire_oldest` publishes timestamps in FIFO publication order - /// before signalling the flight's fence. + /// - Compute queues behind healthy same-VM compute flights (up to + /// [`params::compute_flights`]), each in its own `ComputeSlot` (`its`/`work`). + /// - Render queues behind healthy same-VM non-InitBM render flights (up to + /// [`params::render_flights`]), rotating `PassSlot` (`0..RENDER_SLOTS`) while sharing the + /// active exposed PB/UMA allocator slot (`Pools::can_pipeline`). Hardware barriers on the + /// TA/FS rings preserve exact prior-render ordering (or TA/FS overlap for fragment-only + /// barriers). + /// - Cross-VM switches, cross-engine transitions, InitBM priming renders, and every failure + /// or recovery path still drain the engine first. fn can_queue_behind(&self, job: &Arc) -> bool { let e = &self.engine; - if e.flights.len() >= params::compute_flights() + if job.vm.status.get() != 0 || e.flights.iter().any(|f| { - f.renders != 0 - || f.doomed - || f.recovery_suspect - || !Arc::ptr_eq(&f.job.vm, &job.vm) + f.doomed || f.recovery_suspect || !Arc::ptr_eq(&f.job.vm, &job.vm) }) - || job.vm.status.get() != 0 - || self.slots.compute_exhausted() - || super::recovery::logic::next_ordinal(e.ordinal).is_none() - || !job - .resources - .compute_units() - .is_ok_and(|units| self.slots.compute_available(units)) { return false; } let sent = job.progress.sent(); - matches!(command(job, sent), Some(Command::Compute(_))) - && job.check_command_dependencies(sent).is_ok() + if job.check_command_dependencies(sent).is_err() { + return false; + } + match command(job, sent) { + Some(Command::Compute(_)) => { + e.flights.len() < params::compute_flights() + && e.flights.iter().all(|f| f.renders == 0) + && !self.slots.compute_exhausted() + && super::recovery::logic::next_ordinal(e.ordinal).is_some() + && job + .resources + .compute_units() + .is_ok_and(|units| self.slots.compute_available(units)) + } + Some(Command::Render(_)) => { + e.flights.len() < params::render_flights() + && e.flights.iter().all(|f| f.computes == 0 && !f.initbm) + && !self.slots.render_exhausted() + && !self.pools.exhausted() + && super::recovery::logic::next_ordinal(e.draw).is_some() + && self.pools.can_pipeline(&job.vm) + && job + .resources + .render_passes() + .is_ok_and(|passes| self.slots.pass_available(passes)) + } + None => false, + } } /// Whether some of `job`'s commands were published: such a job is retained after a @@ -1498,9 +1515,10 @@ impl Firmware { let alloc_slot = self.pools.pick_slot(&job.vm, behind).ok_or(EAGAIN)?; let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); + let tilemap_bytes = Geometry::new(&cmd.cmd, 0).tilemap_bytes; // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots - .claim_pass_in(&job.resources, k, Some(job.vm.id))?; + .claim_pass_in(&job.resources, k, Some(job.vm.id), tilemap_bytes)?; self.slots.hold_vm(&f.claims, &job.vm)?; self.slots.hold_arenas(&f.claims, &job.resources); let (refs, init_buffer, epoch, binding) = self.render_refs(alloc_slot, job, draw, behind)?; @@ -1572,8 +1590,50 @@ impl Firmware { r.ring[0].w64(8 * pf.ta_head as usize, epoch.initbm.va)?; pf.ta_head = (pf.ta_head + 1) % cap; } - // Every previous command has its complete receipt before this publication. - // The paired fragment still requires the native explicit TA dependency. + // When pipelining behind an in-flight same-VM render, insert explicit hardware ordering + // barriers on the TA/FS rings. Fragment-only or barrier-free renders overlap TA(N) with + // FS(N-1) (TA waits on prior TA; FS waits on prior FS then own TA); otherwise TA(N) + // waits on prior FS to preserve full vertex-stage visibility. + let frag_only = cmd.cmd.flags + & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS + != 0; + let no_render_barrier = job + .command_order(job.progress.sent()) + .is_some_and(|o| o.wait_through[super::command::RENDER].is_none()); + let early = behind && params::early_tiling() && (frag_only || no_render_barrier); + if behind { + let (wait_va, wait_stamp, wait_event) = if early { + (r.fw_stamp[0].va, self.engine.ta_target, 0x70) + } else { + (r.fw_stamp[1].va, self.engine.fs_target, 0x71) + }; + let prev = encode::barrier( + wait_va, + wait_stamp, + wait_event, + target, + work::barrier::RENDER_WAIT_UUID, + BarrierType::Hold, + ); + p.prev_barrier.write(0, &prev)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.prev_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + if early { + let dep = encode::barrier( + r.fw_stamp[1].va, + self.engine.fs_target, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + BarrierType::Hold, + ); + p.fs_dep.write(0, &dep)?; + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_dep.va)?; + pf.fs_head = (pf.fs_head + 1) % cap; + self.engine.stats.early += 1; + } + } + // The paired fragment always requires the native explicit TA dependency. let own = encode::barrier( r.fw_stamp[0].va, target, diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index f92bea3be3d37..3aa108e85827f 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -690,10 +690,9 @@ pub(crate) mod sizes { pub(crate) const PB_BLOCKS: u32 = 2048; pub(crate) const PB_LIST_RECORDS: u32 = 4096; pub(crate) const PB_GROW_STEP: u32 = 10; - /// Published prefixes at most. A render is published only with nothing else in flight; - /// compute commands may queue behind each other on the one firmware compute queue, each - /// in its own retained unit ([`COMPUTE_UNITS`]). - pub(crate) const FLIGHTS: usize = 16; + /// Published prefixes at most. Same-VM compute or render commands may pipeline behind + /// each other on their engine rings while cross-VM and cross-engine transitions drain. + pub(crate) const FLIGHTS: usize = 32; /// Retained compute units per VM at most; each unit owns its own hardware UMA slot /// (`COMPUTE_UMA_SLOT + index`). A unit is reused only after a later publication retired /// (it displaced the unit), so `n` units keep up to `n - 1` compute commands in flight. @@ -701,11 +700,12 @@ pub(crate) mod sizes { const _: () = assert!(super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP); /// Inherited diagnostic histogram width; M4 does not fold jobs into a compute horizon. pub(crate) const HORIZON_JOBS: u32 = 1; - /// Jobs admitted to the engine per logical queue: enough to keep a queue's compute - /// commands in flight back to back; exact prior-command dependencies still gate each one. - pub(crate) const SCHEDULER_CREDITS: u32 = 16; + /// Jobs admitted to the engine per logical queue: enough to keep a queue's commands + /// in flight back to back without scheduler backpressure stalls; exact prior-command + /// dependencies still gate each one. + pub(crate) const SCHEDULER_CREDITS: u32 = 32; /// Unconsumed records per 256-entry channel ring a prefix may be posted behind. - pub(crate) const AHEAD_RECORDS: u32 = 64; + pub(crate) const AHEAD_RECORDS: u32 = 128; /// Policy bound on logical queues reported in QUEUE_LIMITS (not a firmware limit). pub(crate) const MAX_QUEUES: u32 = 58; /// TTBAT user slots: user VMs hold one each for their lifetime (ASIDs 1..63). diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 15740f7d5ee9c..1068c0b0a668f 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -31,12 +31,16 @@ use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use kernel::{ - c_str, device, + c_str, + cpu::CpuId, + cpumask::Cpumask, + device, dma_fence::Fence, drm::sched, new_mutex, prelude::*, sync::{Arc, Mutex}, + workqueue, }; use super::{ @@ -303,6 +307,11 @@ impl Job { } } + /// Returns the immutable dependency order for command `index`. + pub(crate) fn command_order(&self, index: u32) -> Option { + self.orders.get(index as usize).copied() + } + /// Checks the retained dependency set for each command immediately before publication. /// Never waits or signals fences under the device lock. The scheduler and start() have /// already waited; a pending fence asks the engine to defer rather than publish early. @@ -516,13 +525,21 @@ pub(crate) struct Scheduler { impl Scheduler { pub(crate) fn new(dev: &device::Device) -> Result { - let scheduler = sched::Scheduler::new( + // Keep drm_sched run/free work in the creating CPU's cluster (matching g17/job.rs). + // Completion work still follows the per-submit submitter_cpu, not queue creation, and + // an unbound workqueue restricted via apply_workqueue_attrs() falls back to + // wq_unbound_cpumask if the cluster goes offline (failing soft if restrict() errors). + let submit = workqueue::OwnedQueue::new_ordered_reclaim(c_str!("aurora_g16"))?; + let _ = submit.restrict(Cpumask::cluster_of(CpuId::current())); + let scheduler = sched::Scheduler::new_with_queues( dev, 1, hw::sizes::SCHEDULER_CREDITS, 0, hw::tuning::SCHED_TIMEOUT_MS, c_str!("aurora_g16"), + Some(submit), + None, )?; // With one run queue, only the kernel priority is valid. let entity = sched::Entity::new(&scheduler, sched::Priority::Kernel)?; diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index dfef940d5b25a..cf2bf38f38799 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -191,6 +191,10 @@ impl platform::Driver for Driver { const POLL_WORK: u64 = 0; /// Work item ID of the submitter-pinned fast event poll work. const FAST_POLL_WORK: u64 = 1; +/// Capacity hint for `drm_syncobj_wait` during active submit bursts (mirroring G17's wait hint). +const WAIT_UTIL_MIN: u32 = 512; +const WAIT_HINT_MS: u32 = 8; +const WAIT_HINT_ACTIVE_NS: u64 = 50_000_000; /// Device state shared with the RTKit callbacks and the poll work. #[pin_data] @@ -208,6 +212,10 @@ pub(crate) struct Shared { pub(crate) evented: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, + /// Monotonic timestamp (ns) of the previous submit, for active-burst wait hints. + pub(crate) last_submit_ns: AtomicU64, + /// Whether the most recent submit continued an active burst within [`WAIT_HINT_ACTIVE_NS`]. + pub(crate) wait_hint_active: AtomicBool, /// Next armed hrtimer expiry (monotonic ns, 0 when disarmed). pub(crate) resnap_deadline_ns: AtomicU64, /// Next 1-jiffy backup delayed-work schedule bound (monotonic ns). @@ -280,10 +288,25 @@ impl WorkItem for Shared { } impl Shared { - /// Records the submitting CPU so completion work runs on the same core. + /// Records the submitting CPU and burst cadence for completion placement and wait hints. pub(crate) fn note_submitter(&self) { self.submitter .store(kernel::cpu::CpuId::current().as_u32(), Ordering::Relaxed); + let now = engine::now_ns(); + let prev = self.last_submit_ns.swap(now, Ordering::Relaxed); + self.wait_hint_active.store( + prev != 0 && now.wrapping_sub(prev) <= WAIT_HINT_ACTIVE_NS, + Ordering::Relaxed, + ); + } + + /// Temporary `drm_syncobj_wait` capacity hint while a client is submitting back to back. + pub(crate) fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { + if cfg!(CONFIG_UCLAMP_TASK) && self.wait_hint_active.load(Ordering::Relaxed) { + Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) + } else { + None + } } /// Last recorded submitting CPU, if valid. @@ -438,6 +461,8 @@ impl Gpu { crashed: AtomicBool::new(false), evented: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), + last_submit_ns: AtomicU64::new(0), + wait_hint_active: AtomicBool::new(false), resnap_deadline_ns: AtomicU64::new(0), backup_deadline_ns: AtomicU64::new(0), error: AtomicI32::new(0), @@ -590,6 +615,10 @@ impl Firmware { } impl gpu::Gpu for Gpu { + fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { + self.shared.syncobj_wait_hint() + } + fn max_cmdbuf_size(&self) -> usize { command::MAX_CMDBUF } diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 9e9389f497315..d122bc6fef82d 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -45,7 +45,14 @@ pub(crate) fn compute_units() -> usize { /// Compute commands in flight at most. pub(crate) fn compute_flights() -> usize { - 16usize.clamp(1, hw::sizes::FLIGHTS) + 32usize.clamp(1, hw::sizes::FLIGHTS) +} + +/// Render commands in flight at most (`RENDER_SLOTS - 1` so one slot holds displacement). +pub(crate) fn render_flights() -> usize { + hw::sizes::RENDER_SLOTS + .saturating_sub(1) + .clamp(1, hw::sizes::FLIGHTS) } /// Repoll while a ready prefix waits for record consumption, us. @@ -68,9 +75,9 @@ pub(crate) fn stream_gate() -> bool { module_parameters::g16_stream_gate.value() != 0 } -/// Fragment-only dependency publication has not been qualified on this backend. +/// Fragment-only render barriers overlap a pipelined render's TA with the prior render's FS. pub(crate) fn early_tiling() -> bool { - false + true } /// Fills the generation part of GET_PARAMS group 0. @@ -81,7 +88,8 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res return Err(ENODEV); } params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS) - | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS); + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS); params.gpu_generation = GPU_GENERATION; params.gpu_variant = gpu.cfg.gpu_variant as u32; params.gpu_revision = gpu.cfg.gpu_revision; diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index a655094bfd139..2c10b565b602b 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -131,11 +131,7 @@ impl Shared { firmware.engine.shared = Some(self.clone()); } let accepted = firmware.enqueue(job); - // Nothing is published while a render is in flight: the poll pass after its - // retirement publishes this job. Skipping the pass here keeps queued submissions - // from holding the device lock (ring drains, health checks) on that path. - let render_busy = firmware.engine.flights.iter().any(|f| f.renders != 0); - if accepted.is_ok() && !render_busy && !self.sleeping.load(Ordering::Acquire) { + if accepted.is_ok() && !self.sleeping.load(Ordering::Acquire) { let now = now_ns(); let full = now.wrapping_sub(firmware.last_housekeeping_ns) >= HOUSEKEEPING_NS || self.evented.load(Ordering::Acquire) @@ -472,9 +468,9 @@ impl Firmware { Ok(true) } - /// In-order receipt of compute flight `f` with later flights queued behind it: the NC - /// READ cursor (and with uncached queue info its consumers) passed its ring entries, - /// and the submit pipe's read and completion cursors passed its record. + /// In-order receipt of flight `f` with later flights queued behind it: the NC READ cursor + /// (and with uncached queue info its consumers) passed its ring entries, and the submit + /// pipe's read and completion cursors passed its record. fn queue_passed( &self, channel: Channel, @@ -483,22 +479,25 @@ impl Firmware { f: &Flight, ) -> Result { let cap = super::hw::sizes::QUEUE_CAP; - let tail = self.engine.head; - if f.head >= cap || f.c_start >= cap || tail >= cap { + let (start, head, tail, record) = match channel { + Channel::Compute => (f.c_start, f.head, self.engine.head, f.rec[2]), + Channel::Ta => (f.ta_start, f.ta_head, self.engine.ta_head, f.rec[0]), + Channel::Fs => (f.fs_start, f.fs_head, self.engine.fs_head, f.rec[1]), + }; + if head >= cap || start >= cap || tail >= cap { return Err(EINVAL); } - if !ring_passed(state.r32(qstate::READ)?, f.c_start, f.head, tail, cap) { + if !ring_passed(state.r32(qstate::READ)?, start, head, tail, cap) { return Ok(false); } if !super::hw::tuning::FW_CACHED { for offset in [0x20, 0x24, 0x28] { - if !ring_passed(info.r32(offset)?, f.c_start, f.head, tail, cap) { + if !ring_passed(info.r32(offset)?, start, head, tail, cap) { return Ok(false); } } } let slots = super::fw::channels::RING_SLOTS; - let record = f.rec[2]; let first = (record + slots - 1) % slots; let producer = self.channels.producer(channel); let pipe = self.channels.channel(channel); @@ -568,7 +567,43 @@ impl Firmware { && start != 0 && end > start; } - if f.renders != 0 { + if f.renders != 0 && behind { + let g = &self.graph.render; + let e = &self.engine; + if !stamp_reached(g.fw_stamp[0].r32(0)?, f.ta_target, e.ta_target) + || !stamp_reached(g.fw_stamp[1].r32(0)?, f.fs_target, e.fs_target) + || !self.queue_passed(Channel::Ta, &g.qstate[0], &g.qinfo[0], f)? + || !self.queue_passed(Channel::Fs, &g.qstate[1], &g.qinfo[1], f)? + { + return Ok(Retirement::Pending); + } + let k = f.claims.pass[0] as usize; + let a = f.pb_slot as usize; + let unit = f.job.resources.render_pass(k)?; + let ta_start = unit.scene.r64(0x600)?; + let ta_end = unit.scene.r64(0x608)?; + let fs_start = unit.scene.r64(0x620)?; + let fs_end = unit.scene.r64(0x628)?; + let ta_stamp = g.notifier.r32(notifier_page::TA_STAMP)?; + let fs_stamp = g.notifier.r32(notifier_page::FS_STAMP)?; + full &= stamp_reached(ta_stamp, f.ta_target, e.ta_target) + && (ta_stamp != f.ta_target + || g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot) + && stamp_reached(fs_stamp, f.fs_target, e.fs_target) + && (fs_stamp != f.fs_target + || g.notifier + .r32(notifier_page::FS_RECORD + notifier::CONTEXT)? + == f.job.vm.slot) + && f.job + .resources + .render()? + .pools + .retired_at(a, f.uma_submitted)? + && ta_start != 0 + && ta_end > ta_start + && fs_start != 0 + && fs_end > fs_start; + } else if f.renders != 0 { let g = &self.graph.render; if g.fw_stamp[0].r32(0)? != f.ta_target || g.fw_stamp[1].r32(0)? != f.fs_target diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index ba26665434302..cdc9a931b087b 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -704,6 +704,7 @@ impl Slots { resources: &super::resources::Prepared, k: usize, vm_id: Option, + tilemap_bytes: u64, ) -> Result { let n = resources.render_passes()?.min(sizes::RENDER_SLOTS); if k >= n || !self.render.lifetime.claim(k) { @@ -717,10 +718,19 @@ impl Slots { }); let p = resources.render_pass(k)?; let (tpc_dirty, tilemap_dirty) = resources.render_pass_dirty(k)?; + // On clean same-VM reuse, zero only the overlap with the current pass's tilemap so a + // small render never scrubs leftover bytes from an earlier large render; preserve the + // high-water mark in `tilemap_dirty` for cross-VM or recovery full scrubs. + let prev_tilemap = tilemap_dirty.load(Ordering::Relaxed); + let clear_tilemap = if full { + prev_tilemap + } else { + prev_tilemap.min(tilemap_bytes) + }; if let Err(e) = p.scrub( 1, tpc_dirty.load(Ordering::Relaxed), - tilemap_dirty.load(Ordering::Relaxed), + clear_tilemap, full, &mut self.stats, ) { @@ -729,8 +739,8 @@ impl Slots { } if full { tpc_dirty.store(0, Ordering::Relaxed); + tilemap_dirty.store(0, Ordering::Relaxed); } - tilemap_dirty.store(0, Ordering::Relaxed); self.pass_cursor = ((k + 1) % n) as u32; Ok(()) } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py index 22ff751a2e415..5c3daf85881ce 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py @@ -358,14 +358,17 @@ assert_eq!(order.wait_through,[Some(5),Some(7)]); assert!(!order.ready([6,6],[6,6])); assert!(order.ready([6,7],[6,7])); - // A compute command may follow published compute predecessors (the firmware compute - // queue runs them in order); every cross-engine dependency still needs completion. + // Same-engine commands may follow published predecessors (ordered on the hardware + // engine rings); every cross-engine dependency still needs completion. let compute=Order::new([0,2],[0,0],[NONE,NONE],[0,2],COMPUTE).unwrap(); assert!(!compute.ready([0,1],[0,1])); assert!(compute.ready([0,1],[0,2])); let render=Order::new([0,2],[0,0],[NONE,NONE],[0,2],RENDER).unwrap(); assert!(!render.ready([0,1],[0,2])); assert!(render.ready([0,2],[0,2])); + let render_next=Order::new([2,0],[0,0],[NONE,NONE],[2,0],RENDER).unwrap(); + assert!(!render_next.ready([1,0],[1,0])); + assert!(render_next.ready([1,0],[2,0])); } #[test] fn geometry_capacity_boundary_uses_the_real_encoder() { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index c9b23923cebf6..584d4bd161e6b 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -39,7 +39,7 @@ def item(declaration): fn count(&self)->u32{self.count} fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } -struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}} struct Job { id:u32,vm:Vm,queue:Queue,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -66,9 +66,15 @@ def item(declaration): fn compute_exhausted(&self)->bool{self.compute_exhausted} fn render_exhausted(&self)->bool{self.render_exhausted} fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted} + fn render_exhausted_within(&self,_passes:usize)->bool{self.render_exhausted} fn release(&mut self,_claims:&mut Claims){self.releases+=1;} fn quarantine(&mut self,_claims:&mut Claims){self.quarantines+=1;} } +struct Pools{exhausted:bool,exhausted_vm:Option} +impl Pools{ + fn exhausted(&self)->bool{self.exhausted} + fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} +} mod encode { pub struct ComputeRefs{pub invalid:bool} // Fault injection replaces the descriptor reader, while the actual production @@ -111,7 +117,7 @@ def item(declaration): #[derive(Default)]struct Power{work:Vec} impl Power{fn report_work(&mut self,in_flight:bool){self.work.push(in_flight);}} struct Firmware{ - session:Session,objects:Checks,recovery:Recovery,engine:Engine,slots:Slots,power:Power, + session:Session,objects:Checks,recovery:Recovery,engine:Engine,slots:Slots,pools:Pools,power:Power, unavailable:Vec<(usize,Error)>,stages:VecDeque,retained:Vec,attempted:Vec,fail_stops:u32, } impl Firmware { @@ -155,7 +161,7 @@ def item(declaration): fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)}},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false}, - slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},power:Power::default(), + slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), retained:vec![],attempted:vec![],fail_stops:0} } @@ -186,6 +192,21 @@ def item(declaration): let mut f=firmware(vec![job(1,true,0,Ok(())),job(2,false,0,Ok(()))],vec![(Ok(()),true)]);f.slots.render_exhausted=true; let mut done=vec![];assert_eq!(f.publish(&mut done),Ok(()));assert_eq!(done,[(1,Err(ECANCELED))]);assert_eq!(f.attempted,[2]);assert_eq!(f.fail_stops,0); } + #[test]fn exhausted_render_pools_cancels_render_and_allows_compute(){ + let mut f=firmware(vec![job(1,true,0,Ok(())),job(2,false,0,Ok(()))],vec![(Ok(()),true)]);f.pools.exhausted=true; + let mut done=vec![];assert_eq!(f.publish(&mut done),Ok(()));assert_eq!(done,[(1,Err(ECANCELED))]); + assert_eq!(f.unavailable,[(command::RENDER,EIO)]);assert_eq!(f.attempted,[2]);assert_eq!(f.fail_stops,0); + } + #[test]fn per_vm_exhausted_render_pools_cancels_only_blocked_vm_without_stalling_compute(){ + let mut f=firmware(vec![job(1,true,0,Ok(())),job(2,false,0,Ok(()))],vec![(Ok(()),true)]); + f.pools.exhausted_vm=Some(1); + let mut done=vec![];assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(done,[(1,Err(ECANCELED))]); + assert!(f.unavailable.is_empty()); + assert!(!f.engine.chan_wait); + assert_eq!(f.recovery.publication_wait_deadline,None); + assert_eq!(f.attempted,[2]);assert_eq!(f.fail_stops,0); + } #[test]fn logical_u64_overflow_is_explicit_and_class_local(){ let mut f=firmware(vec![job(1,false,0,Ok(())),job(2,true,0,Ok(()))],vec![(Ok(()),true)]); f.engine.ordinal=u64::MAX; @@ -239,16 +260,26 @@ def item(declaration): } struct QueueBehindJob{id:u32,vm:Arc,progress:Progress,commands:Vec,dependency:Result,resources:Resources} impl QueueBehindJob{fn check_command_dependencies(&self,_index:u32)->Result{self.dependency}} -struct QueueBehindFlight{job:Arc,renders:u32,doomed:bool,recovery_suspect:bool} -struct QueueBehindEngine{ordinal:u64,flights:Vec} -struct QueueBehindSlots{exhausted:bool,available:bool} -impl QueueBehindSlots{fn compute_exhausted(&self)->bool{self.exhausted}fn compute_available(&self,_n:usize)->bool{self.available}} -struct QueueBehindHost{engine:QueueBehindEngine,slots:QueueBehindSlots} +struct QueueBehindFlight{job:Arc,computes:u32,renders:u32,initbm:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindEngine{ordinal:u64,draw:u64,flights:Vec} +struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} +impl QueueBehindSlots{ + fn compute_exhausted(&self)->bool{self.compute_exhausted} + fn render_exhausted(&self)->bool{self.render_exhausted} + fn compute_available(&self,_n:usize)->bool{self.compute_available} + fn pass_available(&self,_n:usize)->bool{self.pass_available} +} +struct QueueBehindPools{exhausted:bool,can_pipeline:bool} +impl QueueBehindPools{ + fn exhausted(&self)->bool{self.exhausted} + fn can_pipeline(&self,_vm:&Arc)->bool{self.can_pipeline} +} +struct QueueBehindHost{engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { use super::*; type Job = QueueBehindJob; fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} - mod params { pub fn compute_flights()->usize{16} } + mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{7} } impl QueueBehindHost { __CAN_QUEUE_BEHIND__ } @@ -265,8 +296,9 @@ def item(declaration): let j_other_vm=mk(3,vm2.clone(),false); let j_render=mk(4,vm1.clone(),true); let mut p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,flights:vec![QueueBehindFlight{job:j1,renders:0,doomed:false,recovery_suspect:false}]}, - slots:QueueBehindSlots{exhausted:false,available:true}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:j1,computes:1,renders:0,initbm:false,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; assert!(p.can_queue_behind(&j2)); assert!(!p.can_queue_behind(&j_other_vm)); @@ -277,9 +309,41 @@ def item(declaration): p.engine.flights[0].renders=1; assert!(!p.can_queue_behind(&j2)); p.engine.flights[0].renders=0; - p.slots.available=false; + p.slots.compute_available=false; assert!(!p.can_queue_behind(&j2)); } + #[test]fn render_queues_behind_same_vm_and_blocks_initbm_cross_vm_or_compute(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:2}); + let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ + id,vm,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(())}], + dependency:Ok(()),resources:Resources, + }); + let r1=mk(1,vm1.clone(),true); + let r2=mk(2,vm1.clone(),true); + let r_other_vm=mk(3,vm2.clone(),true); + let c1=mk(4,vm1.clone(),false); + let mut p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:r1,computes:0,renders:1,initbm:false,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true}, + }; + assert!(p.can_queue_behind(&r2)); + assert!(!p.can_queue_behind(&r_other_vm)); + assert!(!p.can_queue_behind(&c1)); + p.engine.flights[0].initbm=true; + assert!(!p.can_queue_behind(&r2)); + p.engine.flights[0].initbm=false; + p.pools.can_pipeline=false; + assert!(!p.can_queue_behind(&r2)); + p.pools.can_pipeline=true; + p.slots.pass_available=false; + assert!(!p.can_queue_behind(&r2)); + p.slots.pass_available=true; + p.engine.flights[0].recovery_suspect=true; + assert!(!p.can_queue_behind(&r2)); + } } ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) @@ -307,7 +371,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 21, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 23, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production publication wrapper, selection, error isolation and descriptor-error containment branch; wire encoder, descriptor failure injection and transport replaced by CPU recorders.', 'source_sha256': sha(production), }, indent=2)+'\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py index fe522d3c800c5..1ff81b81410d8 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py @@ -136,6 +136,37 @@ def function(text, name): assert_eq!(f.retired(),Ok(Retirement::Pending)); } } +#[test]fn queued_render_flight_retires_on_passed_receipts_in_order(){ + for n in [0x7fffff,0x800000,0xffffff,0x1000000,0x1000001]{ + let mut f=firmware(true,n); + let mut later=firmware(true,n+1).engine.flights.remove(0); + later.uma_submitted=4; + f.engine.flights.push(later); + f.engine.ta_target=encode::stamp(n+1); + f.engine.fs_target=encode::stamp(n+1); + // The render behind it finished too: shared TA/FS stamps and notifier moved on. + for stage in 0..2 { f.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(n+1))); } + f.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(n+1))); + f.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(n+1))); + f.graph.render.notifier.set(notifier::CONTEXT,9); + f.graph.render.notifier.set(notifier_page::FS_RECORD+notifier::CONTEXT,9); + f.engine.flights[0].job.resources.pools.completed=4; + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Unreached FS stamp keeps it pending. + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(n-1))); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(n))); + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Unreached UMA completion keeps it pending. + f.engine.flights[0].job.resources.pools.completed=1; + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.engine.flights[0].job.resources.pools.completed=2; + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Unpassed TA/FS queue keeps it pending. + f.queue_passed=false; + assert_eq!(f.retired(),Ok(Retirement::Pending)); + } +} #[test]fn changing_packed_receipt_remains_pending_and_stable_retry_can_retire(){ let mut f=firmware(false,1);f.engine.flights[0].job.resources.compute[0].its.unstable=true; assert_eq!(f.retired(),Ok(Retirement::Pending)); From 4f44fd665d2ffcb6ea5bded3a4dd80ad18557296 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:11:54 -0500 Subject: [PATCH 15/19] drm/asahi: g16: drop Shared::state across retire tail delay and signal fences early Firmware::retire() previously ran up to EVENT_RETIRE_POLLS (10) x 5 us udelay() loops while holding Shared::state whenever flights remained non-empty after an EP 0x20 interrupt. At queue depth d > 1, retiring the oldest flight left subsequent flights in self.engine.flights, causing every EP 0x20 interrupt to spin for 50 us under Shared::state (bouncing concurrent try_submit_inline() submissions onto drm_sched) and to arm a 15 us short_repoll hrtimer even though retirement had succeeded. Periodic 1 ms housekeeping also ran before retiring and signalling completed fences. Split polling into a non-sleeping Firmware::poll_step() and Firmware::retire_once() that report whether any flight retired: - Stop the EP 0x20 trailing retry loop immediately as soon as any flight retires (or flights drain, a receipt fault occurs, or the engine freezes/fails), and set short_repoll only when an event with active flights still retired nothing after the trailing retries. - Release Shared::state and complete any ready jobs before each 5 us udelay() retry so concurrent inline submissions can acquire the lock without contention. - Retire and publish ready work before periodic 1 ms housekeeping, deferring housekeeping until after job::complete_all() wakes userspace whenever jobs retired on that pass. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/job.rs | 4 + drivers/gpu/drm/asahi/g16/poll.rs | 209 +++++++++++++++++++++--------- 2 files changed, 152 insertions(+), 61 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 1068c0b0a668f..858efa71b4f7e 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -433,6 +433,10 @@ impl Completions { } } + pub(crate) fn is_empty(&self) -> bool { + self.head.is_none() + } + /// Queues the first completion of `job`; subsequent attempts have no effect. pub(crate) fn push(&mut self, job: &Arc, result: Result) { { diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 2c10b565b602b..784c2fa3915eb 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -4,14 +4,16 @@ //! //! Order of one pass, under the device lock: drain the receive rings; authenticate recovery; //! retire flights using stage stamps, NC queue READ/WRITE and submit-pipe frontiers, normal -//! notifier/UMA receipts and internal timestamps; renew the progress deadline. Up to four -//! trailing 5 us polls follow an EP 0x20 event. Then answer PB -//! growth ([`Firmware::answer_growth`]); check hangs and recover ([`Firmware::check_hangs`], -//! which calls [`Firmware::progress`]); publish ([`Firmware::publish`]). Then drop the lock -//! and complete the retired jobs ([`super::job::complete_all`]). Wakeups: the EP 0x20 event -//! kick, then an hrtimer re-poll every `g16_resnap_us` (100) while anything is published, or -//! `g16_repoll_us` (15) while a ready prefix waits for record consumption, with a 1-jiffy -//! delayed-work backup. +//! notifier/UMA receipts and internal timestamps; renew the progress deadline; answer PB +//! growth ([`Firmware::answer_growth`]); publish ([`Firmware::publish_checked`]). Then drop +//! the lock and complete retired jobs ([`super::job::complete_all`]) before periodic 1 ms +//! housekeeping (`session.check`, `objects.health`, `service_power`, administrative hang +//! checks). If an EP 0x20 event arrived with flights outstanding and nothing retired yet, up +//! to [`EVENT_RETIRE_POLLS`] trailing 5 us waits run with `Shared::state` dropped so concurrent +//! submissions are not blocked, stopping as soon as any flight retires. Wakeups: the EP 0x20 +//! event kick, then an hrtimer re-poll every `g16_resnap_us` (100) while anything is +//! published, or `g16_repoll_us` (15) while a ready prefix waits for record consumption or a +//! post-event receipt tail did not settle, with a 1-jiffy delayed-work backup. use core::sync::atomic::Ordering; @@ -81,18 +83,36 @@ impl Shared { return; } let signalling = kernel::dma_fence::SignallingGuard::new(); - let mut done = Completions::new(); - { - let mut state = self.state.lock(); + let mut evented = false; + let mut tail = 0u32; + let mut housekeeping_deferred = false; + let mut step = 0u32; + + loop { if self.sleeping.load(Ordering::Acquire) { - return; + break; } - if let Some(firmware) = state.as_deref_mut() { + let mut done = Completions::new(); + let mut retry_tail = false; + if let Some(firmware) = self.state.lock().as_deref_mut() { + if self.sleeping.load(Ordering::Acquire) { + return; + } if firmware.engine.shared.is_none() { firmware.engine.shared = Some(self.clone()); } - let evented = self.evented.swap(false, Ordering::AcqRel); - match firmware.poll(evented, &mut done) { + if step == 0 { + evented = self.evented.swap(false, Ordering::AcqRel); + tail = if evented { EVENT_RETIRE_POLLS } else { 0 }; + } + match firmware.poll_step( + evented, + tail, + &mut retry_tail, + &mut housekeeping_deferred, + &mut done, + ) { + Ok(true) if retry_tail => {} Ok(true) => { self.rearm(firmware.engine.chan_wait || firmware.engine.short_repoll) } @@ -115,8 +135,30 @@ impl Shared { } } } + job::complete_all(done); + if !retry_tail { + break; + } + tail -= 1; + step += 1; + delay::udelay(Delta::from_micros(5)); + } + + if housekeeping_deferred && !self.sleeping.load(Ordering::Acquire) { + let mut done = Completions::new(); + if let Some(firmware) = self.state.lock().as_deref_mut() { + if !self.sleeping.load(Ordering::Acquire) { + if let Err(error) = firmware.run_housekeeping(&mut done) { + self.cancel_resnap(); + firmware.fail_stop(error, &mut done); + self.fail_stop(error); + } else if firmware.recovery.needs_repoll() || firmware.engine.frozen { + self.rearm(false); + } + } + } + job::complete_all(done); } - job::complete_all(done); drop(signalling); self.notify_wedged(); } @@ -300,29 +342,41 @@ pub(crate) fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { } impl Firmware { - /// One poll pass under the device lock. Returns whether to re-arm the poll timers. - pub(crate) fn poll(&mut self, evented: bool, done: &mut Completions) -> Result { + /// One non-sleeping poll step under the device lock. + /// + /// Retires finished flights and publishes ready work before periodic 1 ms housekeeping so + /// completion fences wake userspace promptly. When an EP 0x20 event arrived with flights + /// outstanding and nothing retired yet, sets `*retry_tail` so [`Shared::run_poll`] drops + /// `Shared::state` across the 5 us receipt-tail delay instead of holding the device lock. + pub(crate) fn poll_step( + &mut self, + evented: bool, + tail: u32, + retry_tail: &mut bool, + housekeeping_deferred: &mut bool, + done: &mut Completions, + ) -> Result { if self.recovery.failed().is_some() { return Ok(false); } self.engine.short_repoll = false; self.session.transport()?; let now = now_ns(); - let housekeeping = self.engine.flights.is_empty() - || now.wrapping_sub(self.last_housekeeping_ns) >= HOUSEKEEPING_NS; - if housekeeping { - self.session.check()?; - self.objects.health()?; - self.service_power()?; - self.last_housekeeping_ns = now; - } + let housekeeping_due = now.wrapping_sub(self.last_housekeeping_ns) >= HOUSEKEEPING_NS; + let had_flights = !self.engine.flights.is_empty(); + let mut ran_housekeeping = false; // With nothing published only a pending firmware recovery notification needs this // pass: one that arrived after its prefix's receipts is answered // here (the firmware halted and waits for the resume) instead of being taken for a // failure of the next prefix. Drain the receive rings before deciding, published or // not, so the error count is current and idle log/trace/stats traffic is consumed. With // prefixes published the retirement loop below drains first. - if self.engine.flights.is_empty() { + if !had_flights { + self.session.check()?; + self.objects.health()?; + self.service_power()?; + self.last_housekeeping_ns = now; + ran_housekeeping = true; self.drain_rings()?; if self.recovery_idle()? && self.engine.pending.is_empty() { return Ok(false); @@ -330,10 +384,10 @@ impl Firmware { } let mut lap = Lap::start(); let start = lap.on().then(now_ns); - self.retire(evented, done)?; + let retired_any = self.retire_once(done)?; lap.lap(&mut self.engine.prof.retire_ns); self.answer_growth()?; - if housekeeping || self.recovery.receipt_fault || self.recovery_pending()? { + if self.recovery.receipt_fault || self.recovery_pending()? { self.check_hangs(done)?; } let published = if self.engine.pending.is_empty() { @@ -352,49 +406,82 @@ impl Firmware { self.engine.prof.poll_ns += now_ns().wrapping_sub(start); } published?; - // If an EP 0x20 event arrived and a flight still did not finish its final receipt - // within the trailing spin, repoll at `repoll_us` instead of sleeping `resnap_us`. - self.engine.short_repoll = evented && !self.engine.flights.is_empty(); + // After an EP 0x20 event, retry up to `EVENT_RETIRE_POLLS` times (outside the device + // lock) only while no flight has retired yet and flights remain in flight. Once any + // flight retires, stop spinning so deeper queues do not burn 50 us per interrupt. + if evented + && had_flights + && !retired_any + && tail != 0 + && !self.engine.flights.is_empty() + && !self.recovery.receipt_fault + && !self.engine.frozen + && self.recovery.failed().is_none() + { + *retry_tail = true; + return Ok(true); + } + if !ran_housekeeping && housekeeping_due { + if !done.is_empty() { + *housekeeping_deferred = true; + } else { + self.run_housekeeping(done)?; + } + } + // If an EP 0x20 event arrived with flights outstanding and nothing retired within the + // trailing polls, repoll at `repoll_us` instead of sleeping `resnap_us`. + self.engine.short_repoll = + evented && had_flights && !retired_any && !self.engine.flights.is_empty(); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() || self.engine.frozen) } - /// Drains the rings and retires finished flights, with up to [`EVENT_RETIRE_POLLS`] - /// trailing 5 us polls after an event. A receipt fault is left in - /// `Recovery::receipt_fault` for the hang checks. - pub(crate) fn retire(&mut self, evented: bool, done: &mut Completions) -> Result { - // After an event, short trailing polls catch firmware's final WC receipt writes - // before falling back to a timer repoll. - let mut tail = if evented { EVENT_RETIRE_POLLS } else { 0 }; - let mut ret; + /// Periodic 1 ms housekeeping (session/object health, power governor, administrative hang + /// checks), run after retired completion fences have been signalled when work retired. + pub(crate) fn run_housekeeping(&mut self, done: &mut Completions) -> Result { + if self.recovery.failed().is_some() { + return Ok(()); + } + self.session.transport()?; + self.session.check()?; + self.objects.health()?; + self.service_power()?; + self.last_housekeeping_ns = now_ns(); + if !self.engine.flights.is_empty() + || self.recovery.receipt_fault + || self.recovery_pending()? + { + self.check_hangs(done)?; + } + Ok(()) + } - loop { - let mut lap = Lap::start(); - self.drain_rings()?; - lap.lap(&mut self.engine.prof.drain_ns); - // Recovery may force stage progress: authenticate it before any receipt. - if self.recovery.receipt_fault || self.recovery_pending()? { - self.check_hangs(done)?; - } - ret = self.retired(); - while let Ok(receipt) = ret { - if !receipt.complete() { - break; - } - let outcome = self.retire_outcome(receipt); - self.retire_oldest(receipt, outcome, done); - ret = self.retired(); - } - if ret.is_err() || tail == 0 || self.engine.flights.is_empty() { + /// Drains the rings and retires all currently complete flights without sleeping. Returns + /// whether at least one flight retired. A receipt fault is left in + /// `Recovery::receipt_fault` for the hang checks. + pub(crate) fn retire_once(&mut self, done: &mut Completions) -> Result { + let mut lap = Lap::start(); + self.drain_rings()?; + lap.lap(&mut self.engine.prof.drain_ns); + // Recovery may force stage progress: authenticate it before any receipt. + if self.recovery.receipt_fault || self.recovery_pending()? { + self.check_hangs(done)?; + } + let mut retired_any = false; + let mut ret = self.retired(); + while let Ok(receipt) = ret { + if !receipt.complete() { break; } - tail -= 1; - delay::udelay(Delta::from_micros(5)); + let outcome = self.retire_outcome(receipt); + self.retire_oldest(receipt, outcome, done); + retired_any = true; + ret = self.retired(); } self.recovery.receipt_fault = ret.is_err(); - Ok(()) + Ok(retired_any) } #[allow(dead_code)] From 29b2312ba4928497df88e04e8d72ad157200584a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:14:21 -0500 Subject: [PATCH 16/19] drm/asahi: g16: support DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS Advertise DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS in G16 GET_PARAMS and accept DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS in compute stream/command validation. G16 publishes command timestamp outputs from the CPU during retire_oldest(). Record on each Flight whether it carries timestamp outputs and, in Firmware::can_queue_behind(), hold a same-queue compute command with a compute barrier behind an in-flight timed predecessor unless DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS is set (clearing ComputeCommand::query_access). Ordinary compute dispatches that pass NO_QUERY_ACCESS continue to pipeline freely behind timed compute work, while query copy/reset compute shaders wait for host timestamp publication. Extend test-command-stream.py and test-publication.py with host coverage for the compute flag and query-access pipelining rules. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 9 ++- drivers/gpu/drm/asahi/g16/engine.rs | 27 +++++++- drivers/gpu/drm/asahi/g16/params.rs | 11 +-- .../gpu/asahi-m4/test-command-stream.py | 8 +++ .../drivers/gpu/asahi-m4/test-publication.py | 67 ++++++++++++++----- 5 files changed, 96 insertions(+), 26 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 6d905e6354688..d798c399f2075 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -37,6 +37,8 @@ const PROCESS_EMPTY_TILES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_P const RSRC_SPEC_HI: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_RSRC_SPEC_HI; const DBIAS_IS_INT: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_DBIAS_IS_INT; const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; +const COMPUTE_NO_QUERY_ACCESS: u32 = + uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS as u32; const CMD_RENDER: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER; const CMD_COMPUTE: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_COMPUTE; @@ -146,6 +148,8 @@ pub(crate) struct ComputeCommand { pub(crate) attachments: KVec, /// Retained timestamp destinations, published after full command retirement. pub(crate) timestamp_outputs: crate::timestamp::Destinations, + /// False when userspace asserts this dispatch neither copies nor resets timestamp queries. + pub(crate) query_access: bool, } /// A validated command. @@ -360,7 +364,7 @@ pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { CMD_COMPUTE => { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; let cmd = &packet; - if cmd.flags != 0 + if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 || cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base || !inside( cmd.cdm_ctrl_stream_base, @@ -626,7 +630,7 @@ fn check_compute( ) -> Result { let vm = context.vm; let (base, end) = (cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end); - if cmd.flags != 0 + if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 || cmd.sampler_count != 0 || cmd.sampler_heap != 0 || !helper_is_empty(&cmd.helper) @@ -755,6 +759,7 @@ impl Prepared<'_> { cmd: *cmd, attachments: copy_list(&[&compute])?, timestamp_outputs: outputs, + query_access: cmd.flags & COMPUTE_NO_QUERY_ACCESS == 0, }, GFP_KERNEL, )?), diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 444dc69da3dce..62c403d9f9a8c 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -195,6 +195,8 @@ pub(crate) struct Flight { pub(crate) pb_binding: u64, /// Whether this render carries InitBM (priming renders always drain before pipelining). pub(crate) initbm: bool, + /// Whether this flight publishes CPU-written command timestamps on retirement. + pub(crate) has_timestamps: bool, } impl Flight { @@ -229,6 +231,7 @@ impl Flight { pb_slot: 0, pb_binding: 0, initbm: false, + has_timestamps: false, } } } @@ -959,7 +962,10 @@ impl Firmware { /// Whether `job`'s next command may be published behind the flights in flight: /// /// - Compute queues behind healthy same-VM compute flights (up to - /// [`params::compute_flights`]), each in its own `ComputeSlot` (`its`/`work`). + /// [`params::compute_flights`]), each in its own `ComputeSlot` (`its`/`work`), unless + /// `query_access` is set and a same-queue predecessor in its compute barrier prefix has + /// CPU-published timestamp outputs that have not retired yet + /// (`DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS` clears `query_access`). /// - Render queues behind healthy same-VM non-InitBM render flights (up to /// [`params::render_flights`]), rotating `PassSlot` (`0..RENDER_SLOTS`) while sharing the /// active exposed PB/UMA allocator slot (`Pools::can_pipeline`). Hardware barriers on the @@ -981,8 +987,22 @@ impl Firmware { return false; } match command(job, sent) { - Some(Command::Compute(_)) => { - e.flights.len() < params::compute_flights() + Some(Command::Compute(c)) => { + let waits_for_timestamps = c.query_access + && job + .command_order(sent) + .and_then(|o| o.wait_through[super::command::COMPUTE]) + .is_some_and(|last| { + e.flights.iter().any(|f| { + f.has_timestamps + && Arc::ptr_eq(&f.job.queue, &job.queue) + && f.job + .command_order(f.first as u32) + .is_none_or(|fo| fo.sequence <= last) + }) + }); + !waits_for_timestamps + && e.flights.len() < params::compute_flights() && e.flights.iter().all(|f| f.renders == 0) && !self.slots.compute_exhausted() && super::recovery::logic::next_ordinal(e.ordinal).is_some() @@ -1489,6 +1509,7 @@ impl Firmware { } s.work.write(0, w)?; f.uma_submitted = submitted; + f.has_timestamps = !cmd.timestamp_outputs.is_empty(); wmb(); g.ring.w64(8 * pf.c_head as usize, s.work.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index d122bc6fef82d..1b8bf9b6edb4e 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -3,10 +3,10 @@ //! Module parameters and the GET_PARAMS identity. //! //! With the shared `file.rs` additions (VM_STATUS and VM_STATUS_MIRROR from `supports_vm_status`, -//! SOFT_FAULTS suppressed by `soft_faults`), the feature word is 0x1c02: per-command input -//! readiness/errors and exact queue-local historical prefixes use explicit retained inputs -//! and successful command receipt frontiers. No independent hardware queue reservation, -//! fragment barriers or ray queries are advertised. +//! SOFT_FAULTS suppressed by `soft_faults`), G16 advertises per-command input readiness/errors, +//! exact queue-local historical prefixes, fragment-only render barriers, and +//! `COMPUTE_NO_QUERY_ACCESS`. No independent hardware queue reservation or ray queries are +//! advertised. use kernel::{prelude::*, uapi}; @@ -89,7 +89,8 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res } params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS) - | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS); + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS); params.gpu_generation = GPU_GENERATION; params.gpu_variant = gpu.cfg.gpu_variant as u32; params.gpu_revision = gpu.cfg.gpu_revision; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py index 5c3daf85881ce..ebb773c7b7218 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py @@ -41,6 +41,7 @@ pub const drm_asahi_cmd_type_DRM_ASAHI_SET_COMPUTE_RESOURCES: drm_asahi_cmd_type = 6; pub const drm_asahi_cmd_type_DRM_ASAHI_SET_RENDER_RESOURCES_V2: drm_asahi_cmd_type = 7; pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES: drm_asahi_render_flags = 8388608; +pub const drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: drm_asahi_compute_flags = 131072; ''' BINDINGS = OUT / 'm5-uapi.rs' BINDINGS.write_text('include!(' + json.dumps(str(FLAT)) + ');\n' + M5_UAPI) @@ -311,6 +312,13 @@ assert!(check_stream(&entry(CMD_RENDER,&data(&r)[..256],[NONE;2]),false).is_err()); } let mut c=compute(); + c.flags=COMPUTE_NO_QUERY_ACCESS; + assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_ok()); + for bad in [1u32, 1<<16, 1<<18, COMPUTE_NO_QUERY_ACCESS | 1] { + c.flags=bad; + assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); + } + let mut c=compute(); c.scs_layout=1; assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); c.scs_layout=0; c.cdm_auxiliary_allocation=8; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 584d4bd161e6b..365e670819a6c 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -29,7 +29,8 @@ def item(declaration): type Result = std::result::Result; macro_rules! dev_err {($($argument:tt)*)=>{()};} __PUBLICATION_ERROR__ -#[derive(Copy,Clone)]enum Command { Compute(()), Render(()) } +#[derive(Copy,Clone)]struct ComputeCommand { query_access: bool } +#[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(()) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} struct Vm { status:Status, slot:u32 } struct Queue { turn:AtomicU64, priority:u32 } @@ -156,7 +157,7 @@ def item(declaration): Arc::new(Job{id,vm:Vm{status:Status(AtomicU32::new(0)),slot:id}, queue:Queue{turn:AtomicU64::new(0),priority:0}, progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(())};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)}},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, @@ -258,9 +259,13 @@ def item(declaration): } } -struct QueueBehindJob{id:u32,vm:Arc,progress:Progress,commands:Vec,dependency:Result,resources:Resources} -impl QueueBehindJob{fn check_command_dependencies(&self,_index:u32)->Result{self.dependency}} -struct QueueBehindFlight{job:Arc,computes:u32,renders:u32,initbm:bool,doomed:bool,recovery_suspect:bool} +#[derive(Copy,Clone)]struct Order{sequence:u64,wait_through:[Option;2]} +struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,dependency:Result,resources:Resources} +impl QueueBehindJob{ + fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} + fn command_order(&self,_index:u32)->Option{Some(self.order)} +} +struct QueueBehindFlight{job:Arc,first:usize,computes:u32,renders:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} struct QueueBehindEngine{ordinal:u64,draw:u64,flights:Vec} struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} impl QueueBehindSlots{ @@ -286,17 +291,19 @@ def item(declaration): #[test]fn timed_compute_queues_behind_same_vm_and_blocks_cross_vm_or_render(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); let vm2=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:2}); - let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ - id,vm,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(())}], + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0}); + let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})}], + order:Order{sequence:u64::from(id),wait_through:[None,None]}, dependency:Ok(()),resources:Resources, }); - let j1=mk(1,vm1.clone(),false); - let j2=mk(2,vm1.clone(),false); - let j_other_vm=mk(3,vm2.clone(),false); - let j_render=mk(4,vm1.clone(),true); + let j1=mk(1,vm1.clone(),q1.clone(),false); + let j2=mk(2,vm1.clone(),q1.clone(),false); + let j_other_vm=mk(3,vm2.clone(),q1.clone(),false); + let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:j1,computes:1,renders:0,initbm:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:j1,first:0,computes:1,renders:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; @@ -312,12 +319,40 @@ def item(declaration): p.slots.compute_available=false; assert!(!p.can_queue_behind(&j2)); } + #[test]fn compute_query_access_waits_for_timed_predecessor_unless_no_query_access(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0}); + let q2=Arc::new(Queue{turn:AtomicU64::new(0),priority:0}); + let mk=|id:u32,queue:Arc,query_access:bool,wait_cdm:Option|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access})], + order:Order{sequence:u64::from(id),wait_through:[None,wait_cdm]}, + dependency:Ok(()),resources:Resources, + }); + let timed=mk(1,q1.clone(),true,None); + let query_copy=mk(2,q1.clone(),true,Some(1)); + let no_query=mk(2,q1.clone(),false,Some(1)); + let no_barrier=mk(2,q1.clone(),true,None); + let other_queue=mk(2,q2.clone(),true,Some(1)); + let p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed,first:0,computes:1,renders:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true}, + }; + assert!(!p.can_queue_behind(&query_copy)); + assert!(p.can_queue_behind(&no_query)); + assert!(p.can_queue_behind(&no_barrier)); + assert!(p.can_queue_behind(&other_queue)); + } #[test]fn render_queues_behind_same_vm_and_blocks_initbm_cross_vm_or_compute(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); let vm2=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:2}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0}); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ - id,vm,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(())}], + id,vm,queue:q1.clone(),progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})}], + order:Order{sequence:u64::from(id),wait_through:[None,None]}, dependency:Ok(()),resources:Resources, }); let r1=mk(1,vm1.clone(),true); @@ -325,7 +360,7 @@ def item(declaration): let r_other_vm=mk(3,vm2.clone(),true); let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:r1,computes:0,renders:1,initbm:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:r1,first:0,computes:0,renders:1,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; From 05d7362e95a8418aeccbfd9f929ed7c05f31dc24 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:16:21 -0500 Subject: [PATCH 17/19] drm/asahi: g16: coalesce mailbox doorbells across multi-command publication batches When publish_checked() publishes multiple commands in a single pass (multi-command SUBMITs or queued back-to-back submissions), each command still posts its own SubmitRecord and advances qstate::WRITE individually per the M4 firmware contract, but previously called session.ring(channel) on every iteration. Defer doorbell ringing into a per-batch channel bitmask and ring each touched channel once via Firmware::flush_doorbells() after the batch loop finishes (preserving FS-before-TA ordering for render batches and fail-stopping on any post-visibility doorbell error). Count commands that share a coalesced doorbell pass in Engine::stats.grouped. Add host tests in test-publication.py covering coalesced compute/render doorbells, deferred-follower flushing, and doorbell error fail-stop. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 51 ++++++++++++- .../drivers/gpu/asahi-m4/test-publication.py | 75 ++++++++++++++++--- 2 files changed, 113 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 62c403d9f9a8c..31bf2db0d2884 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -789,6 +789,8 @@ impl Firmware { // ordering satisfies Mesa's barriers while slot displacement and cache ownership // stay explicit. Never enable G15's submit-ahead policy on the M4 wire by accident. let mut result = Ok(()); + let mut pending_rings = 0u8; + let mut batch_published = 0u64; self.engine.chan_wait = false; while self.recovery.failed().is_none() @@ -888,8 +890,9 @@ impl Firmware { } self.engine.turn += 1; job.queue.turn.store(self.engine.turn, Ordering::Relaxed); - match self.publish_prefix(&job, done) { + match self.publish_prefix(&job, done, &mut pending_rings) { Ok(()) => { + batch_published += 1; self.recovery.publication_wait_deadline = None; if job.progress.sent() == job.progress.count() { self.engine.unpend(&job); // fully published @@ -924,6 +927,12 @@ impl Firmware { .0 }); if super::recovery::logic::expired(now_ns(), deadline) { + // `self.engine.flights.is_empty()` already implies `pending_rings == 0` + // today, but flush defensively so records posted earlier in the batch + // cannot be stranded if this error ever stops being fatal. + if pending_rings != 0 { + let _ = self.flush_doorbells(&mut pending_rings); + } return Err(ETIMEDOUT); } break; @@ -934,6 +943,7 @@ impl Firmware { complete(done, &job, Err(e)); } Err(PublicationError::Uncertain(e)) => { + pending_rings = 0; self.engine.unpend(&job); // A counter or producer may be visible: retain and stop globally. dev_err!( @@ -950,6 +960,24 @@ impl Firmware { } } } + if batch_published > 1 { + self.engine.stats.grouped = self + .engine + .stats + .grouped + .saturating_add(batch_published - 1); + } + if pending_rings != 0 { + if let Err(e) = self.flush_doorbells(&mut pending_rings) { + dev_err!( + self.graph.dev.as_ref(), + "G16: batched doorbell ring failed after visibility began ({:?})\n", + e + ); + self.fail_stop(EIO, done); + result = Err(EIO); + } + } if !self.engine.chan_wait { self.recovery.publication_wait_deadline = None; } @@ -959,6 +987,18 @@ impl Firmware { result } + /// Rings each submit channel touched during a publication batch once, preserving + /// FS-before-TA doorbell order for render batches. + fn flush_doorbells(&mut self, pending_rings: &mut u8) -> Result { + let mask = core::mem::take(pending_rings); + for channel in [Channel::Fs, Channel::Ta, Channel::Compute] { + if mask & (1u8 << (channel as u8)) != 0 { + self.session.ring(channel)?; + } + } + Ok(()) + } + /// Whether `job`'s next command may be published behind the flights in flight: /// /// - Compute queues behind healthy same-VM compute flights (up to @@ -1112,10 +1152,11 @@ impl Firmware { &mut self, job: &Arc, done: &mut Completions, + pending_rings: &mut u8, ) -> core::result::Result<(), PublicationError> { let mut f = Flight::new(job.clone()); let mut visible = false; - let result = self.publish_prefix_into(job, &mut f, &mut visible); + let result = self.publish_prefix_into(job, &mut f, &mut visible, pending_rings); match result { Err(e) if !visible => { // Never published: its storage is free again, and horizon jobs taken into it @@ -1136,8 +1177,9 @@ impl Firmware { job: &Arc, f: &mut Flight, visible: &mut bool, + pending_rings: &mut u8, ) -> Result { - let result = self.publish_prefix_body(job, f, visible); + let result = self.publish_prefix_body(job, f, visible, pending_rings); if result.is_err() && !*visible { if f.pb.is_some() { self.pools.cancel_alloc(f.pb_slot as usize); @@ -1156,6 +1198,7 @@ impl Firmware { job: &Arc, f: &mut Flight, visible: &mut bool, + pending_rings: &mut u8, ) -> Result { let behind = !self.engine.flights.is_empty(); if behind && !self.can_queue_behind(job) { @@ -1368,7 +1411,7 @@ impl Firmware { } else { self.channels.post(channel, &record)?; } - self.session.ring(channel)?; + *pending_rings |= 1u8 << (channel as u8); } Ok(()) })(); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 365e670819a6c..ba322395c26f1 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -29,6 +29,7 @@ def item(declaration): type Result = std::result::Result; macro_rules! dev_err {($($argument:tt)*)=>{()};} __PUBLICATION_ERROR__ +#[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } #[derive(Copy,Clone)]struct ComputeCommand { query_access: bool } #[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(()) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} @@ -49,7 +50,7 @@ def item(declaration): fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} type Completions=Vec<(u32,Result)>; fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} -#[derive(Default)]struct Stats{hold:[u64;3]} +#[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; struct Flight{claims:Claims,group:Vec>} impl Flight{fn new(_job:Arc)->Self{Self{claims:Claims,group:vec![]}}} @@ -60,7 +61,15 @@ def item(declaration): } struct Checks;impl Checks{fn check(&self)->Result{Ok(())}fn health(&self)->Result{Ok(())}} struct Shared{sleeping:AtomicBool} -struct Session{shared:Shared}impl Session{fn check(&self)->Result{Ok(())}} +struct Session{shared:Shared,rings:Vec,ring_fail:bool} +impl Session{ + fn check(&self)->Result{Ok(())} + fn ring(&mut self,channel:Channel)->Result{ + if self.ring_fail{return Err(EIO);} + self.rings.push(channel); + Ok(()) + } +} struct Recovery{error:Option,publication_wait_deadline:Option}impl Recovery{fn failed(&self)->Option{self.error}} struct Slots{compute_exhausted:bool,render_exhausted:bool,releases:u32,quarantines:u32} impl Slots{ @@ -120,12 +129,11 @@ def item(declaration): struct Firmware{ session:Session,objects:Checks,recovery:Recovery,engine:Engine,slots:Slots,pools:Pools,power:Power, unavailable:Vec<(usize,Error)>,stages:VecDeque,retained:Vec,attempted:Vec,fail_stops:u32, + allow_behind:bool, } impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} - // Queuing behind in-flight compute is exercised on hardware; this recorder keeps the - // serialized selection and error isolation under test. - fn can_queue_behind(&self,_job:&Arc)->bool{false} + fn can_queue_behind(&self,_job:&Arc)->bool{self.allow_behind} fn service_power(&self)->Result{Ok(())} fn drain_rings(&mut self)->Result{Ok(())} fn check_hangs(&mut self,_done:&mut Completions)->Result{Ok(())} @@ -139,16 +147,22 @@ def item(declaration): } // The wire encoder/transport is replaced only at this boundary. The production wrapper, // dependency selection and error isolation execute verbatim above and below it. - fn publish_prefix_into(&mut self,job:&Arc,_flight:&mut Flight,visible:&mut bool)->Result{ + fn publish_prefix_into(&mut self,job:&Arc,_flight:&mut Flight,visible:&mut bool,pending_rings:&mut u8)->Result{ self.attempted.push(job.id); let stage=self.stages.pop_front().expect("unexpected hardware publication"); *visible=stage.visible; if stage.result.is_ok(){ - assert!(stage.visible);job.progress.sent.fetch_add(1,Ordering::Relaxed); + assert!(stage.visible); + let idx=job.progress.sent.fetch_add(1,Ordering::Relaxed); + match command(job,idx){ + Some(Command::Render(()))=>{*pending_rings|=(1<<(Channel::Fs as u8))|(1<<(Channel::Ta as u8));} + _=>{*pending_rings|=1<<(Channel::Compute as u8);} + } self.engine.flights.push(Flight::new(job.clone())); } stage.result } + __FLUSH_DOORBELLS__ __PUBLISH_PREFIX__ __PUBLISH__ __PUBLISH_CHECKED__ @@ -160,11 +174,11 @@ def item(declaration): commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ - Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)}},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, + Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), - retained:vec![],attempted:vec![],fail_stops:0} + retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false} } #[cfg(test)]mod tests{ use super::*; @@ -257,6 +271,48 @@ def item(declaration): assert!(done.is_empty());assert!(f.attempted.is_empty());assert_eq!(f.engine.pending.len(),1);assert!(f.power.work.is_empty()); f.session.shared.sleeping.store(false,Ordering::Relaxed);assert_eq!(f.publish(&mut done),Ok(()));assert_eq!(f.attempted,[1]); } + #[test]fn batched_compute_publications_coalesce_to_one_doorbell(){ + let mut f=firmware( + vec![job(1,false,0,Ok(())),job(2,false,0,Ok(())),job(3,false,0,Ok(()))], + vec![(Ok(()),true),(Ok(()),true),(Ok(()),true)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2,3]); + assert_eq!(f.session.rings,[Channel::Compute]); + assert_eq!(f.engine.stats.grouped,2); + } + #[test]fn batched_render_publications_coalesce_in_fs_then_ta_order(){ + let mut f=firmware( + vec![job(1,true,0,Ok(())),job(2,true,0,Ok(()))], + vec![(Ok(()),true),(Ok(()),true)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2]); + assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta]); + assert_eq!(f.engine.stats.grouped,1); + } + #[test]fn batched_doorbell_flushes_after_later_deferral_and_fail_stops_on_ring_error(){ + let mut f=firmware( + vec![job(1,false,0,Ok(())),job(2,false,0,Ok(()))], + vec![(Ok(()),true),(Err(EAGAIN),false)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2]); + assert_eq!(f.session.rings,[Channel::Compute]); + assert_eq!(f.fail_stops,0); + + let mut f=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); + f.session.ring_fail=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Err(EIO)); + assert_eq!(f.fail_stops,1); + } } #[derive(Copy,Clone)]struct Order{sequence:u64,wait_through:[Option;2]} @@ -386,6 +442,7 @@ def item(declaration): '__PUBLICATION_ERROR__': 'enum PublicationError {', '__PICK__': 'fn pick(&self)', '__UNPEND__': 'fn unpend(&mut self', + '__FLUSH_DOORBELLS__': 'fn flush_doorbells(', '__PUBLISH_PREFIX__': 'fn publish_prefix(', '__PUBLISH__': 'pub(crate) fn publish(&mut self', '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', From b3d0336aa5e39b41063eb14d0fbfd6016575d1ef Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:18:48 -0500 Subject: [PATCH 18/19] drm/asahi: g16: trim redundant WC writes for compute work and render scene MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every G16 compute dispatch previously copied the full 8 KiB ComputeWork object (0x2000 bytes) into write-combined firmware memory, even though encode_compute_for() and the firmware only touch 0x000..0x150 (header plus up to 25 register records) and 0x720..0xf08 (metadata, ABI fields, embedded sequence, notifier, UMA descriptor, tail) — leaving 5,832 bytes (71%) perpetually zero. Similarly, every render pass zeroed and copied the full 16 KiB scene object (0x4000 bytes) to WC memory even though only 0x000..0x780 (rounded up to 0x800, 2 KiB) is touched by host or firmware. - Track on ComputeOwners whether each unit's latest claim required a full scrub (first use, cross-VM switch, cancelled prep, error, or firmware recovery). On clean same-VM reuse, prefix_compute() writes only the two active spans (0..0x150 and 0x720..0xf08: 2,360 bytes instead of 8,192 bytes); full-scrub claims still write all 0x2000 bytes after preserving any existing UMA descriptor. - Zero the full 16 KiB PassSlot::scene in PassSlot::scrub(full = true), size Scratch::scene to scene::ACTIVE_SIZE (0x800), and allow fill_scene() to zero and populate that active 2 KiB prefix, cutting 14,336 bytes (87.5%) of CPU memset and WC writes per render pass. - Extend test-resources.py to verify compute_needs_full_work() state transitions and PassSlot::scene full-scrub coverage. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/encode/render.rs | 6 ++++-- drivers/gpu/drm/asahi/g16/engine.rs | 12 +++++++++-- drivers/gpu/drm/asahi/g16/fw/work.rs | 4 ++++ drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 20 ++++++++++++++++++- drivers/gpu/drm/asahi/g16/slots.rs | 12 +++++++++++ .../drivers/gpu/asahi-m4/test-resources.py | 9 ++++++++- 6 files changed, 57 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index 064b297f75bc5..2ebe9f2e5ed50 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -591,9 +591,11 @@ pub(crate) fn render_attachments(q: &mut [u8], engine: usize, att: &[uapi::drm_a /// Base scene metadata in caller-owned storage. A full scene belongs to the /// retained slot and should not be placed on the kernel stack. pub(crate) fn fill_scene(r: &RenderRefs, p: &PassRefs, out: &mut [u8]) { - let Some(out) = out.get_mut(..scene::SIZE) else { + if out.len() < scene::ACTIVE_SIZE { return; - }; + } + let len = out.len().min(scene::SIZE); + let out = &mut out[..len]; out.fill(0); put64(out, 0, p.scene_user_gva); put64(out, 8, p.scratch_fw); diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 31bf2db0d2884..5b57a40a8828a 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -387,7 +387,7 @@ impl Scratch { tas: z(work::ta::SEQ_SIZE)?, fs: z(work::fs::WORK_SIZE)?, fss: z(work::fs::SEQ_SIZE)?, - scene: z(work::scene::SIZE)?, + scene: z(work::scene::ACTIVE_SIZE)?, }) } } @@ -1550,7 +1550,15 @@ impl Firmware { return Err(EIO); } } - s.work.write(0, w)?; + if self.slots.compute_needs_full_work(index) { + s.work.write(0, w)?; + } else { + s.work.write(0, &w[..work::compute::HEAD_ACTIVE_SIZE])?; + s.work.write( + work::compute::BODY_ACTIVE_START, + &w[work::compute::BODY_ACTIVE_START..work::compute::BODY_ACTIVE_END], + )?; + } f.uma_submitted = submitted; f.has_timestamps = !cmd.timestamp_outputs.is_empty(); wmb(); diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index faa407bceb4c4..11b470b52330d 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -211,4 +211,8 @@ pub(crate) mod initbm { /// Per-pass scene including UMA results and embedded prefix records. pub(crate) mod scene { pub(crate) const SIZE: usize = 0x4000; + /// Active prefix of a render scene touched by the host or firmware (`0x000..0x780`, + /// rounded up to 2 KiB). Full pass scrubs zero the entire `SIZE`; clean same-VM reuse only + /// rewrites `0..ACTIVE_SIZE`. + pub(crate) const ACTIVE_SIZE: usize = 0x800; } diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index c45d6772038f8..b6e9a734b4dad 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -3,6 +3,15 @@ //! J713/G16G 25G83 compute packet layout. All offsets are bytes. pub(crate) const WORK_SIZE: usize = 0x2000; +/// Active head span of a compute work image: header (`0x00..0x18`) plus up to 25 register +/// records (`0x20..0x14c`), rounded up to 16-byte alignment. Bytes between +/// `HEAD_ACTIVE_SIZE` and `BODY_ACTIVE_START` remain zeroed after a full write. +pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x150; +/// First active body byte of a compute work image (`work_gva + 0x20` pointer at `0x720`). +pub(crate) const BODY_ACTIVE_START: usize = 0x720; +/// Exclusive end of the active body span of a compute work image (`0xf00..0xf08` tail). +/// Bytes `BODY_ACTIVE_END..WORK_SIZE` remain zeroed after a full write. +pub(crate) const BODY_ACTIVE_END: usize = 0xf08; pub(crate) const SEQ_SIZE: usize = 0x300; pub(crate) const SEQ_OBJECT: usize = 0x1000; pub(crate) const REGS: usize = 0x20; @@ -75,7 +84,16 @@ const fn valid(l: &Layout) -> bool { && l.cached <= SEQ_EMBEDDED && SEQ_EMBEDDED + SEQ_SIZE <= NOTIFIER } -const _: () = assert!(valid(&V25G83) && valid(&V26B123)); +const _: () = assert!( + valid(&V25G83) + && valid(&V26B123) + && REGS + 25 * 12 <= HEAD_ACTIVE_SIZE + && HEAD_ACTIVE_SIZE <= BODY_ACTIVE_START + && BODY_ACTIVE_START <= GENERATION + && DESCRIPTOR + DESCRIPTOR_SIZE <= BODY_ACTIVE_END + && 0xf08 <= BODY_ACTIVE_END + && BODY_ACTIVE_END <= WORK_SIZE +); pub(crate) const SEL: [u32; 24] = [ 0x1a510, 0x1a420, 0x1a4d0, 0x1a4d8, 0x1a4e0, 0x1a4e8, 0x1a440, 0x1a458, 0x101d9, 0x1a089, diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index cdc9a931b087b..38004c8d53570 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -315,6 +315,7 @@ impl PassSlot { stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_dirty); self.aux.fill(0, 0, 0x20000)?; self.heap.fill(0, 0, 0x4000)?; + self.scene.fill(0, 0, super::fw::work::scene::SIZE)?; self.scene_user.fill(0, 0, 0x10000)?; self.scene_list .fill(0, 0, super::fw::buffer::SCENE_LIST_SIZE)?; @@ -422,6 +423,8 @@ pub(crate) struct ComputeOwners { pending_arena: [Option>; sizes::COMPUTE_UNITS], /// Force a full scrub on next claim (first use, cancel, error, or firmware recovery). scrub_full: [bool; sizes::COMPUTE_UNITS], + /// Whether the most recent claim of each compute unit required a full scrub/work write. + last_full: [bool; sizes::COMPUTE_UNITS], } /// Bitmask of valid render pass slot indices (`0..sizes::RENDER_SLOTS`). @@ -468,6 +471,7 @@ impl Slots { arena: [const { None }; sizes::COMPUTE_UNITS], pending_arena: [const { None }; sizes::COMPUTE_UNITS], scrub_full: [true; sizes::COMPUTE_UNITS], + last_full: [true; sizes::COMPUTE_UNITS], }, GFP_KERNEL, )?, @@ -579,6 +583,13 @@ impl Slots { self.claim_compute_for(units, f, None) } + /// Whether the most recent claim of compute unit `k` requires writing the entire work + /// object (first use, cross-VM switch, cancelled preparation, error, or firmware recovery) + /// rather than only the active non-zero spans. + pub(crate) fn compute_needs_full_work(&self, k: usize) -> bool { + self.compute.last_full.get(k).copied().unwrap_or(true) + } + pub(crate) fn claim_compute_for( &mut self, units: &super::resources::Prepared, @@ -604,6 +615,7 @@ impl Slots { self.compute.lifetime.cancel(k); return Err(e); } + self.compute.last_full[k] = full; f.slot[0] = k as u32; f.slot_count = 1; self.cursor = ((k + 1) % n) as u32; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index a4dd5e322e2ab..bbfac08651d44 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -482,6 +482,7 @@ def module(text, name): // Same-VM clean reuse of unit 0 clears ONLY its (16 B), skipping context_store/aux/preempt/seq. let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); assert_eq!(k,0); + assert!(!s.compute_needs_full_work(0)); assert_eq!(arena.compute.compute[0].its.fills.lock().unwrap().len(),2); assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),1); assert_eq!(arena.compute.compute[0].preempt.fills.lock().unwrap().len(),1); @@ -490,6 +491,7 @@ def module(text, name): // Cross-VM switch on unit 1 runs full scrub. let k=s.claim_compute_for(&arena.compute,&mut c,Some(b.id)).unwrap().unwrap(); assert_eq!(k,1); + assert!(s.compute_needs_full_work(1)); assert_eq!(arena.compute.compute[1].context_store.fills.lock().unwrap().len(),2); assert_eq!(arena.compute.compute[1].preempt.fills.lock().unwrap().len(),2); s.hold_vm(&c,&b).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); @@ -497,11 +499,13 @@ def module(text, name): s.invalidate_scrub(); let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); assert_eq!(k,0); + assert!(s.compute_needs_full_work(0)); assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),2); // Cancelled preparation forces full scrub on next claim. s.release(&mut c); let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); assert_eq!(k,0); + assert!(s.compute_needs_full_work(0)); assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),3); s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); } @@ -521,10 +525,12 @@ def module(text, name): retire(&mut s,1,&a); let p0=&arena.render.passes[0]; assert_eq!(p0.aux.fills.lock().unwrap().len(),1); + assert_eq!(p0.scene.fills.lock().unwrap().last(),Some(&(0,0x4000))); assert_eq!(p0.tpc.fills.lock().unwrap().len(),1); - // Same-VM clean reuse of slot 0: clears tilemap/its/heap(0x1000)/pre headers only; skips aux/tpc/scratch. + // Same-VM clean reuse of slot 0: clears tilemap/its/heap(0x1000)/pre headers only; skips aux/tpc/scratch/scene. s.claim_pass_for(&arena.render,0,Some(a.id)).unwrap(); assert_eq!(p0.aux.fills.lock().unwrap().len(),1); + assert_eq!(p0.scene.fills.lock().unwrap().len(),1); assert_eq!(p0.ta_scratch.fills.lock().unwrap().len(),1); assert_eq!(p0.fs_scratch.fills.lock().unwrap().len(),1); assert_eq!(p0.scene_user.fills.lock().unwrap().len(),1); @@ -540,6 +546,7 @@ def module(text, name): retire(&mut s,1,&a); s.claim_pass_for(&arena.render,0,Some(b.id)).unwrap(); assert_eq!(p0.aux.fills.lock().unwrap().len(),2); + assert_eq!(p0.scene.fills.lock().unwrap().len(),2); assert_eq!(p0.scene_list.fills.lock().unwrap().len(),2); assert_eq!(p0.tpc.fills.lock().unwrap().last(),Some(&(0,0x8000))); assert_eq!(p0.tilemap.fills.lock().unwrap().last(),Some(&(0,0x1000))); From 9f14889356cd497b805734355f637352fde64df7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 23:03:22 -0500 Subject: [PATCH 19/19] drm/asahi: g16: fix scheduler job retention, PB quarantine, scrub_gen and idle CLPC drain Address review findings on PR #2741: - Replace Scheduler::last_job (Option>) with a lightweight last_scheduled: Option> signalled after SchedJob::run(), cancel() or drop() finishes handing off the job. Queue-local inline submission ordering is preserved without pinning the previous Arc (and its VmJobGuard / Prepared arenas) across idle periods or subsequent submissions. - Retain the aborted flight's fresh PbEpoch in Pools::quarantine_flight() alongside the prior slot owner, and mem::forget() the removed Flight on fail-stop early returns in retire_oldest() so exposed epochs are never unmapped while firmware may still reference them. - Track a monotonic scrub_gen across Slots::invalidate_scrub() and stamp it on Claims during Slots::publish() so flights that were already in flight across a firmware recovery do not clear scrub_full on retirement. - Report idle work state to CLPC (power.report_work(false)) in poll_step() when flights drain with an empty pending queue. - Drop Cache::ready before the up-to-10 s standby wait in Cache::prepare() so Cache::close() and same-VM compute submits do not block behind a render standby wait. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 2 +- drivers/gpu/drm/asahi/g16/job.rs | 40 ++++- drivers/gpu/drm/asahi/g16/poll.rs | 14 +- drivers/gpu/drm/asahi/g16/pools.rs | 19 ++- drivers/gpu/drm/asahi/g16/resources.rs | 161 +++++++++--------- drivers/gpu/drm/asahi/g16/slots.rs | 19 ++- .../drivers/gpu/asahi-m4/test-resources.py | 76 ++++++--- 7 files changed, 217 insertions(+), 114 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 5b57a40a8828a..0a008b0c550d7 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1336,7 +1336,7 @@ impl Firmware { job.vm.vm.mark_binding_published()?; self.slots.hold_vm(&f.claims, &job.vm)?; self.slots.hold_arenas(&f.claims, &job.resources); - self.slots.publish(&f.claims)?; + self.slots.publish(&mut f.claims)?; // Even a failed first store may have become visible. From this boundary preserve // every owner and return explicit uncertainty rather than guessing from errno. *visible = true; diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 858efa71b4f7e..3613d91234f12 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -483,6 +483,9 @@ pub(crate) fn complete_all(mut done: Completions) { struct SchedJob { job: Arc, shared: Arc, + /// Signalled once `run()`, `cancel()`, or `drop()` finishes handing off `job`. + /// Preserves queue-local inline-submit ordering without retaining `Arc`. + scheduled: Arc, } impl sched::JobImpl for SchedJob { @@ -496,6 +499,7 @@ impl sched::JobImpl for SchedJob { fn run(job: &mut Self) -> Result> { let fence = job.job.fence.fence(); job.job.start(&job.shared); + job.scheduled.store(true, Ordering::Release); Ok(Some(fence)) } @@ -506,6 +510,7 @@ impl sched::JobImpl for SchedJob { fn cancel(job: &mut Self) { job.job.cancel_unstarted(); + job.scheduled.store(true, Ordering::Release); } } @@ -513,6 +518,7 @@ impl Drop for SchedJob { fn drop(&mut self) { // Entity teardown frees jobs it never ran without calling `cancel`. self.job.cancel_unstarted(); + self.scheduled.store(true, Ordering::Release); } } @@ -522,9 +528,10 @@ pub(crate) struct Scheduler { // drains), and only then the scheduler is finalized. entity: sched::Entity, _scheduler: sched::Scheduler, - /// Most recently accepted job of this queue; an inline submit is permitted only once - /// this predecessor has already started so queue-local ordering is strictly preserved. - last_job: Option>, + /// Completion flag of the most recently queued (non-inline) job of this queue; an inline + /// submit is permitted only once this predecessor has started or been cancelled, without + /// retaining the predecessor `Arc` (and its `VmJobGuard` or prepared arenas). + last_scheduled: Option>, } impl Scheduler { @@ -550,7 +557,7 @@ impl Scheduler { Ok(Self { entity, _scheduler: scheduler, - last_job: None, + last_scheduled: None, }) } @@ -558,9 +565,24 @@ impl Scheduler { /// submitted work of its VM) and the error is returned. pub(crate) fn push(&mut self, job: Arc, shared: Arc) -> Result { shared.note_submitter(); - let prev_started = self.last_job.as_ref().is_none_or(|prev| prev.is_started()); + let prev_started = match &self.last_scheduled { + Some(done) if done.load(Ordering::Acquire) => { + self.last_scheduled = None; + true + } + Some(_) => false, + None => true, + }; let handle = job.clone(); - let mut pending = self.entity.new_job(1, SchedJob { job, shared: shared.clone() })?; + let scheduled = Arc::new(AtomicBool::new(false), GFP_KERNEL)?; + let mut pending = self.entity.new_job( + 1, + SchedJob { + job, + shared: shared.clone(), + scheduled: scheduled.clone(), + }, + )?; for fence in handle.inputs.iter() { pending.add_dependency(fence.clone())?; } @@ -569,7 +591,11 @@ impl Scheduler { if prev_started { handle.try_start_inline(&shared); } - self.last_job = Some(handle); + if handle.is_started() { + scheduled.store(true, Ordering::Release); + } else { + self.last_scheduled = Some(scheduled); + } armed.push(); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 784c2fa3915eb..3070e4636d156 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -395,6 +395,9 @@ impl Firmware { } else { self.publish_checked(done) }; + if self.engine.flights.is_empty() { + self.power.report_work(false); + } let s = &mut self.engine.stats; if self.engine.flights.is_empty() && s.idle_from_ns != 0 { // Idle with nothing ready is not a gap: the clients are late. @@ -795,6 +798,7 @@ impl Firmware { self.retain(&f.job); complete(done, &f.job, Err(error)); self.fail_stop(error, done); + core::mem::forget(f); return; } if f.computes != 0 { @@ -815,6 +819,7 @@ impl Firmware { self.retain(&f.job); complete(done, &f.job, Err(error)); self.fail_stop(error, done); + core::mem::forget(f); return; } } @@ -822,6 +827,7 @@ impl Firmware { self.retain(&f.job); complete(done, &f.job, Err(error)); self.fail_stop(error, done); + core::mem::forget(f); return; } if result.is_err() { @@ -833,8 +839,9 @@ impl Firmware { // Only an actual passed abort lacks the full owner receipt. An affected job // with a full normal receipt fails its fence without poisoning healthy storage. if f.renders != 0 { - // Quarantine the aborted allocator slot permanently and keep no epoch for reuse. - self.pools.quarantine_flight(f.pb_slot as usize); + // Quarantine the aborted allocator slot permanently and retain the aborted + // flight's epoch alongside the prior slot owner. + self.pools.quarantine_flight(f.pb_slot as usize, f.pb.take()); } self.slots.quarantine(&mut f.claims); self.retain(&f.job); @@ -851,6 +858,7 @@ impl Firmware { self.retain(&f.job); complete(done, &f.job, Err(error)); self.fail_stop(error, done); + core::mem::forget(f); return; } // Publish queue-local EXACT_PRIOR frontiers only after every normal hardware @@ -860,6 +868,7 @@ impl Firmware { self.retain(&f.job); complete(done, &f.job, Err(error)); self.fail_stop(error, done); + core::mem::forget(f); return; } } @@ -903,6 +912,7 @@ impl Firmware { self.retain(&job); complete(done, &job, Err(proof_error)); self.fail_stop(proof_error, done); + core::mem::forget(f); return; } } diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 3eeb2cf794f21..bdaa2aecbb488 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -308,6 +308,8 @@ pub(crate) struct Pools { inflight: [u32; 2], /// Permanently quarantined allocator slots after an aborted receipt. quarantined: [bool; 2], + /// Fresh PB epoch retained when an aborted render had not yet replaced `owners[k]`. + quarantined_epochs: [Option>; 2], } impl Pools { pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { @@ -325,6 +327,7 @@ impl Pools { last_clean_retired: None, inflight: [0, 0], quarantined: [false, false], + quarantined_epochs: [None, None], } } /// Allocator slot `k`'s owner epoch, if its render retired normally while the slot was still @@ -464,13 +467,25 @@ impl Pools { self.retire_epoch(k, binding, completed); Ok(()) } - /// Quarantines allocator slot `k` permanently after a passed abort, retaining all leases. + /// Quarantines allocator slot `k` permanently after a passed abort, retaining all leases + /// including any fresh epoch published on the aborted flight alongside `owners[k]`. #[allow(dead_code)] - pub(crate) fn quarantine_flight(&mut self, k: usize) { + pub(crate) fn quarantine_flight(&mut self, k: usize, pb: Option>) { if k < 2 { self.inflight[k] = self.inflight[k].saturating_sub(1); self.quarantined[k] = true; self.keep[k] = false; + if let Some(epoch) = pb { + if self.quarantined_epochs[k].is_none() { + self.quarantined_epochs[k] = Some(epoch); + } else { + // Already retaining an aborted epoch on this slot; never unmap an exposed + // epoch or allocate under the device lock. + core::mem::forget(epoch); + } + } + } else if let Some(epoch) = pb { + core::mem::forget(epoch); } } /// Slot `k` is handed to a render's epoch, `reused` or fresh (with InitBM). Returns the diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 98165ef4abe69..f53be8b55c336 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -382,10 +382,9 @@ impl Cache { .count() .try_into()?; let render = render_count != 0; - let (compute, compute_ext, render, render_ext) = { - // Never held by publication, completion, recovery or fence signalling. - // Serializing standby top-up under `ready` prevents concurrent SUBMITs on the - // same VM from over-allocating or racing each other's deficit calculation. + let (compute, compute_ext, render_arena, render_ext) = { + // Never held by publication, completion, recovery, fence signalling or + // standby waits, so Cache::close() and same-VM compute SUBMITs never block. let mut ready = self.ready.lock(); if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { return Err(EIO); @@ -450,98 +449,100 @@ impl Cache { ready.render_ext = RenderExtArena::new(&self.factory, &self.bind, &vm.vm, &self.live).ok(); } - if render_count > super::budget::LIMIT { - return Err(E2BIG); - } - let mut remaining = kernel::time::msecs_to_jiffies(10_000); - loop { - let deficit = { - let mut standby = self.standby.lock(); - if vm.status.get() != 0 - || vm.vm.is_closed() - || self.closed.load(Ordering::Acquire) - { - return Err(EIO); + } + ( + if compute { ready.compute.clone() } else { None }, + if compute { ready.compute_ext.clone() } else { None }, + if render { ready.render.clone() } else { None }, + if render { ready.render_ext.clone() } else { None }, + ) + }; + if render { + if render_count > super::budget::LIMIT { + return Err(E2BIG); + } + let mut remaining = kernel::time::msecs_to_jiffies(10_000); + loop { + let deficit = { + let mut standby = self.standby.lock(); + if vm.status.get() != 0 + || vm.vm.is_closed() + || self.closed.load(Ordering::Acquire) + { + return Err(EIO); + } + if let Some(needed) = standby + .reserved + .checked_add(render_count) + .filter(|&n| n <= super::budget::LIMIT) + { + if standby.epochs.len() >= needed as usize { + standby.reserved = needed; + break; } - if let Some(needed) = standby - .reserved - .checked_add(render_count) - .filter(|&n| n <= super::budget::LIMIT) + needed - standby.epochs.len() as u32 + } else { + match self + .standby_available + .wait_interruptible_timeout(&mut standby, remaining) { - if standby.epochs.len() >= needed as usize { - standby.reserved = needed; - break; + CondVarTimeoutResult::Woken { jiffies } => { + remaining = jiffies; + continue; } - needed - standby.epochs.len() as u32 - } else { - match self - .standby_available - .wait_interruptible_timeout(&mut standby, remaining) - { - CondVarTimeoutResult::Woken { jiffies } => { - remaining = jiffies; - continue; + CondVarTimeoutResult::Signal { .. } => return Err(ERESTARTSYS), + CondVarTimeoutResult::Timeout => { + if vm.status.get() != 0 + || vm.vm.is_closed() + || self.closed.load(Ordering::Acquire) + { + return Err(EIO); } - CondVarTimeoutResult::Signal { .. } => return Err(ERESTARTSYS), - CondVarTimeoutResult::Timeout => { - if vm.status.get() != 0 - || vm.vm.is_closed() - || self.closed.load(Ordering::Acquire) - { - return Err(EIO); - } - let needed = standby - .reserved - .checked_add(render_count) - .filter(|&n| n <= super::budget::LIMIT) - .ok_or(EBUSY)?; - if standby.epochs.len() >= needed as usize { - standby.reserved = needed; - break; - } - needed - standby.epochs.len() as u32 + let needed = standby + .reserved + .checked_add(render_count) + .filter(|&n| n <= super::budget::LIMIT) + .ok_or(EBUSY)?; + if standby.epochs.len() >= needed as usize { + standby.reserved = needed; + break; } + needed - standby.epochs.len() as u32 } } - }; - let mut epochs = super::budget::Budget::reserve(&self.budget, deficit)?; - let mut fresh = KVec::with_capacity(deficit as usize, GFP_KERNEL)?; - for _ in 0..deficit { - fresh.push(PbEpoch::new(&self.factory, vm, epochs.take()?)?, GFP_KERNEL)?; } - let mut overflow = KVec::with_capacity(fresh.len(), GFP_KERNEL)?; - { - let mut standby = self.standby.lock(); - let closed = self.closed.load(Ordering::Acquire); - for epoch in fresh { - if closed { - let _ = overflow.push_within_capacity(epoch); - } else if let Err(err) = standby.epochs.push_within_capacity(epoch) { - let _ = overflow.push_within_capacity(err.0); - } + }; + let mut epochs = super::budget::Budget::reserve(&self.budget, deficit)?; + let mut fresh = KVec::with_capacity(deficit as usize, GFP_KERNEL)?; + for _ in 0..deficit { + fresh.push(PbEpoch::new(&self.factory, vm, epochs.take()?)?, GFP_KERNEL)?; + } + let mut overflow = KVec::with_capacity(fresh.len(), GFP_KERNEL)?; + { + let mut standby = self.standby.lock(); + let closed = self.closed.load(Ordering::Acquire); + for epoch in fresh { + if closed { + let _ = overflow.push_within_capacity(epoch); + } else if let Err(err) = standby.epochs.push_within_capacity(epoch) { + let _ = overflow.push_within_capacity(err.0); } } - drop(overflow); } + drop(overflow); } - // A concurrent fault retains even newly constructed backing in this VM cache. - if vm.status.get() != 0 || vm.vm.is_closed() { - if render { - self.release_reserved(render_count); - } - return Err(EIO); + } + // A concurrent fault or close retains even newly constructed backing in this VM cache. + if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { + if render { + self.release_reserved(render_count); } - ( - if compute { ready.compute.clone() } else { None }, - if compute { ready.compute_ext.clone() } else { None }, - if render { ready.render.clone() } else { None }, - if render { ready.render_ext.clone() } else { None }, - ) - }; + return Err(EIO); + } Ok(Prepared { compute, compute_ext, - render, + render: render_arena, render_ext, unpublished_renders: AtomicU32::new(render_count), cache: (render_count != 0).then(|| self.clone()), diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 38004c8d53570..6b0fa2d5b0b3e 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -368,6 +368,9 @@ pub(crate) struct Claims { pub(crate) ct_count: u32, #[allow(dead_code)] pub(crate) rotating: bool, + /// `Slots::scrub_gen` observed when these claims were published; a recovery invalidation + /// advances `scrub_gen` so in-flight slots still force a full scrub after retiring. + pub(crate) scrub_gen: u64, } impl Claims { pub(crate) const fn new() -> Self { @@ -379,6 +382,7 @@ impl Claims { ct: [0; sizes::RENDER_SLOTS], ct_count: 0, rotating: true, + scrub_gen: 0, } } } @@ -449,6 +453,7 @@ pub(crate) struct Slots { pub(crate) cursor: u32, pub(crate) pass_busy: u32, pub(crate) pass_cursor: u32, + scrub_gen: u64, pub(crate) stats: SlotStats, /// The compute and render owners, on the heap: `Firmware` (and so `Slots`) is built on the /// probe's stack, which has no room for them. @@ -461,6 +466,7 @@ impl Slots { cursor: 0, pass_busy: 0, pass_cursor: 0, + scrub_gen: 0, stats: SlotStats::default(), compute: KBox::new( ComputeOwners { @@ -554,6 +560,7 @@ impl Slots { /// Forces a full scrub on the next claim of every slot (after firmware recovery). #[allow(dead_code)] pub(crate) fn invalidate_scrub(&mut self) { + self.scrub_gen = self.scrub_gen.wrapping_add(1); self.compute.scrub_full = [true; sizes::COMPUTE_UNITS]; self.render.scrub_full = [true; sizes::RENDER_SLOTS]; } @@ -842,7 +849,7 @@ impl Slots { } /// Reserve the actual same-slot publication. Call before producers become visible. - pub(crate) fn publish(&mut self, f: &Claims) -> Result { + pub(crate) fn publish(&mut self, f: &mut Claims) -> Result { // Validate on a private copy so a failure changes no ownership. let mut c = self.compute.lifetime.clone(); let mut p = self.render.lifetime.clone(); @@ -858,6 +865,7 @@ impl Slots { } self.compute.lifetime = c; self.render.lifetime = p; + f.scrub_gen = self.scrub_gen; Ok(()) } /// Full wire retirement is a precondition; completion fences alone are insufficient. @@ -876,16 +884,21 @@ impl Slots { } self.compute.lifetime = c; self.render.lifetime = p; + let clean_scrub = f.scrub_gen == self.scrub_gen; for &k in &f.slot[..f.slot_count as usize] { self.compute.owner[k as usize] = self.compute.pending_owner[k as usize].take(); self.compute.arena[k as usize] = self.compute.pending_arena[k as usize].take(); - self.compute.scrub_full[k as usize] = false; + if clean_scrub { + self.compute.scrub_full[k as usize] = false; + } } for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { self.render.owner[k] = self.render.pending_owner[k].take(); self.render.arena[k] = self.render.pending_arena[k].take(); - self.render.scrub_full[k] = false; + if clean_scrub { + self.render.scrub_full[k] = false; + } } } self.pass_busy &= !f.pass_mask; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index bbfac08651d44..9b4789b9f6d2a 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -181,7 +181,7 @@ def module(text, name): for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} Arenas{compute:g16::resources::ComputeArena{compute},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};8],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};8]}} } - fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<|{ let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1< global pool exhaustion. + // Aborted render on slot 0 with a fresh epoch after slot 1 was previously retired + // retains BOTH the prior owner epoch (e1) and the fresh aborted epoch (e1_fresh), + // leaving slot 1 undisplaced and slot 0 quarantined -> global pool exhaustion. + let e1_fresh=g16::pools::PbEpoch::new(&factory,&vm1,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e1_fresh.prepare(0,0x70c0000000,2048).unwrap();e1_fresh.expose(); assert_eq!(p.pick_slot(&vm1,false),Some(0)); p.publish_flight(0); - p.quarantine_flight(0); + p.quarantine_flight(0,Some(e1_fresh.clone())); + assert_eq!(sync::Arc::strong_count(&e1),2,"prior slot owner epoch must stay mapped"); + assert_eq!(sync::Arc::strong_count(&e1_fresh),2,"aborted fresh epoch must stay mapped"); assert!(p.reusable(0,&vm1).is_none()); assert_eq!(p.pick_slot(&vm1,false),None); assert!(p.exhausted()); @@ -645,7 +650,7 @@ def module(text, name): let mut q=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); assert_eq!(q.pick_slot(&vm1,false),Some(0)); q.publish_flight(0); - q.quarantine_flight(0); + q.quarantine_flight(0,None); assert!(!q.exhausted()); assert_eq!(q.pick_slot(&vm2,false),Some(1)); let qb2=q.bind(1,false); @@ -663,6 +668,39 @@ def module(text, name): assert!(q.exhausted_for(&vm2)); } + #[test]fn recovery_invalidate_scrub_survives_in_flight_retirement(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let a=vm(1); + // Prime unit 0 and unit 1 so unit 0 is clean for same-VM reuse. + let mut c0=Claims::new(); + assert_eq!(s.claim_compute_for(&arena.compute,&mut c0,Some(a.id)).unwrap(),Some(0)); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap(); + // Recovery fires while unit 0 is still in flight. + s.invalidate_scrub(); + s.retire(&mut c0).unwrap(); + // Displace unit 0 via unit 1 (published after recovery -> clean). + let mut c1=Claims::new(); + assert_eq!(s.claim_compute_for(&arena.compute,&mut c1,Some(a.id)).unwrap(),Some(1)); + s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); + // Next claim of unit 0 by the same VM must still perform a full scrub! + let k=s.claim_compute_for(&arena.compute,&mut c0,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert!(s.compute_needs_full_work(0)); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),2); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); + // Same invariant for render pass slots in flight across recovery. + let mut r0=Claims::new();r0.pass[0]=0;r0.pass_mask=1; + s.claim_pass_for(&arena.render,0,Some(a.id)).unwrap(); + s.hold_vm(&r0,&a).unwrap();s.publish(&mut r0).unwrap(); + s.invalidate_scrub(); + s.retire(&mut r0).unwrap(); + let mut r1=Claims::new();r1.pass[0]=1;r1.pass_mask=2; + s.claim_pass_for(&arena.render,1,Some(a.id)).unwrap(); + s.hold_vm(&r1,&a).unwrap();s.publish(&mut r1).unwrap();s.retire(&mut r1).unwrap(); + s.claim_pass_for(&arena.render,0,Some(a.id)).unwrap(); + assert_eq!(arena.render.passes[0].scene.fills.lock().unwrap().len(),2); + } + #[test]fn pipelined_render_pass_slots_keep_seven_in_flight(){ let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut passes=KVec::new(); @@ -682,7 +720,7 @@ def module(text, name): c.pass[0]=k as u32;c.pass_mask=1<